1/*
2   Copyright The containerd Authors.
3
4   Licensed under the Apache License, Version 2.0 (the "License");
5   you may not use this file except in compliance with the License.
6   You may obtain a copy of the License at
7
8       http://www.apache.org/licenses/LICENSE-2.0
9
10   Unless required by applicable law or agreed to in writing, software
11   distributed under the License is distributed on an "AS IS" BASIS,
12   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   See the License for the specific language governing permissions and
14   limitations under the License.
15*/
16
17package main
18
19import (
20	"strings"
21
22	"github.com/gogo/protobuf/gogoproto"
23	"github.com/gogo/protobuf/proto"
24	"github.com/gogo/protobuf/protoc-gen-gogo/descriptor"
25	"github.com/gogo/protobuf/protoc-gen-gogo/generator"
26	"github.com/gogo/protobuf/vanity"
27)
28
29// CustomNameID preprocess the field, and set the [(gogoproto.customname) = "..."]
30// if necessary, in order to avoid setting `gogoproto.customname` manually.
31// The automatically assigned name should conform to Golang convention.
32func CustomNameID(file *descriptor.FileDescriptorProto) {
33
34	f := func(field *descriptor.FieldDescriptorProto) {
35		// Skip if [(gogoproto.customname) = "..."] has already been set.
36		if gogoproto.IsCustomName(field) {
37			return
38		}
39		// Skip if embedded
40		if gogoproto.IsEmbed(field) {
41			return
42		}
43		if field.OneofIndex != nil {
44			return
45		}
46		fieldName := generator.CamelCase(*field.Name)
47		switch {
48		case *field.Name == "id":
49			// id -> ID
50			fieldName = "ID"
51		case strings.HasPrefix(*field.Name, "id_"):
52			// id_some -> IDSome
53			fieldName = "ID" + fieldName[2:]
54		case strings.HasSuffix(*field.Name, "_id"):
55			// some_id -> SomeID
56			fieldName = fieldName[:len(fieldName)-2] + "ID"
57		case strings.HasSuffix(*field.Name, "_ids"):
58			// some_ids -> SomeIDs
59			fieldName = fieldName[:len(fieldName)-3] + "IDs"
60		default:
61			return
62		}
63		if field.Options == nil {
64			field.Options = &descriptor.FieldOptions{}
65		}
66		if err := proto.SetExtension(field.Options, gogoproto.E_Customname, &fieldName); err != nil {
67			panic(err)
68		}
69	}
70
71	// Iterate through all fields in file
72	vanity.ForEachFieldExcludingExtensions(file.MessageType, f)
73}
74