github.com/cosmos/cosmos-proto@v1.0.0-beta.3/generator/features.go (about)

     1  // Copyright (c) 2021 PlanetScale Inc. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package generator
     6  
     7  import (
     8  	"fmt"
     9  	"sort"
    10  
    11  	"google.golang.org/protobuf/compiler/protogen"
    12  )
    13  
    14  var defaultFeatures = make(map[string]Feature)
    15  
    16  func findFeatures(featureNames []string) ([]Feature, error) {
    17  	required := make(map[string]Feature)
    18  	for _, name := range featureNames {
    19  		if name == "all" {
    20  			required = defaultFeatures
    21  			break
    22  		}
    23  
    24  		feat, ok := defaultFeatures[name]
    25  		if !ok {
    26  			return nil, fmt.Errorf("unknown feature: %q", name)
    27  		}
    28  		required[name] = feat
    29  	}
    30  
    31  	type namefeat struct {
    32  		name string
    33  		feat Feature
    34  	}
    35  	var sorted []namefeat
    36  	for name, feat := range required {
    37  		sorted = append(sorted, namefeat{name, feat})
    38  	}
    39  	sort.Slice(sorted, func(i, j int) bool {
    40  		return sorted[i].name < sorted[j].name
    41  	})
    42  
    43  	var features []Feature
    44  	for _, sp := range sorted {
    45  		features = append(features, sp.feat)
    46  	}
    47  	return features, nil
    48  }
    49  
    50  func RegisterFeature(name string, feat Feature) {
    51  	defaultFeatures[name] = feat
    52  }
    53  
    54  type Feature func(gen *GeneratedFile, plugin *protogen.Plugin) FeatureGenerator
    55  
    56  type FeatureGenerator interface {
    57  	GenerateFile(file *protogen.File, plugin *protogen.Plugin) bool
    58  	GenerateHelpers()
    59  }