github.com/kaisenlinux/docker.io@v0.0.0-20230510090727-ea55db55fac7/swarmkit/cmd/protoc-gen-gogoswarm/customnameid.go (about)

     1  package main
     2  
     3  import (
     4  	"strings"
     5  
     6  	"github.com/gogo/protobuf/gogoproto"
     7  	"github.com/gogo/protobuf/proto"
     8  	"github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
     9  	"github.com/gogo/protobuf/protoc-gen-gogo/generator"
    10  	"github.com/gogo/protobuf/vanity"
    11  )
    12  
    13  // CustomNameID preprocess the field, and set the [(gogoproto.customname) = "..."]
    14  // if necessary, in order to avoid setting `gogoproto.customname` manually.
    15  // The automatically assigned name should conform to Golang convention.
    16  func CustomNameID(file *descriptor.FileDescriptorProto) {
    17  
    18  	f := func(field *descriptor.FieldDescriptorProto) {
    19  		// Skip if [(gogoproto.customname) = "..."] has already been set.
    20  		if gogoproto.IsCustomName(field) {
    21  			return
    22  		}
    23  		// Skip if embedded
    24  		if gogoproto.IsEmbed(field) {
    25  			return
    26  		}
    27  		if field.OneofIndex != nil {
    28  			return
    29  		}
    30  		fieldName := generator.CamelCase(*field.Name)
    31  		switch {
    32  		case *field.Name == "id":
    33  			// id -> ID
    34  			fieldName = "ID"
    35  		case strings.HasPrefix(*field.Name, "id_"):
    36  			// id_some -> IDSome
    37  			fieldName = "ID" + fieldName[2:]
    38  		case strings.HasSuffix(*field.Name, "_id"):
    39  			// some_id -> SomeID
    40  			fieldName = fieldName[:len(fieldName)-2] + "ID"
    41  		case strings.HasSuffix(*field.Name, "_ids"):
    42  			// some_ids -> SomeIDs
    43  			fieldName = fieldName[:len(fieldName)-3] + "IDs"
    44  		default:
    45  			return
    46  		}
    47  		if field.Options == nil {
    48  			field.Options = &descriptor.FieldOptions{}
    49  		}
    50  		if err := proto.SetExtension(field.Options, gogoproto.E_Customname, &fieldName); err != nil {
    51  			panic(err)
    52  		}
    53  	}
    54  
    55  	// Iterate through all fields in file
    56  	vanity.ForEachFieldExcludingExtensions(file.MessageType, f)
    57  }