Damien Neil | 220c202 | 2018-08-15 11:24:18 -0700 | [diff] [blame^] | 1 | package protogen |
| 2 | |
| 3 | import ( |
| 4 | "go/token" |
| 5 | "strconv" |
| 6 | "strings" |
| 7 | "unicode" |
| 8 | "unicode/utf8" |
| 9 | ) |
| 10 | |
| 11 | // A GoImportPath is the import path of a Go package. e.g., "google.golang.org/genproto/protobuf". |
| 12 | type GoImportPath string |
| 13 | |
| 14 | func (p GoImportPath) String() string { return strconv.Quote(string(p)) } |
| 15 | |
| 16 | // A GoPackageName is the name of a Go package. e.g., "protobuf". |
| 17 | type GoPackageName string |
| 18 | |
| 19 | // cleanPacakgeName converts a string to a valid Go package name. |
| 20 | func cleanPackageName(name string) GoPackageName { |
| 21 | name = strings.Map(badToUnderscore, name) |
| 22 | // Identifier must not be keyword: insert _. |
| 23 | if token.Lookup(name).IsKeyword() { |
| 24 | name = "_" + name |
| 25 | } |
| 26 | // Identifier must not begin with digit: insert _. |
| 27 | if r, _ := utf8.DecodeRuneInString(name); unicode.IsDigit(r) { |
| 28 | name = "_" + name |
| 29 | } |
| 30 | return GoPackageName(name) |
| 31 | } |
| 32 | |
| 33 | // badToUnderscore is the mapping function used to generate Go names from package names, |
| 34 | // which can be dotted in the input .proto file. It replaces non-identifier characters such as |
| 35 | // dot or dash with underscore. |
| 36 | func badToUnderscore(r rune) rune { |
| 37 | if unicode.IsLetter(r) || unicode.IsDigit(r) || r == '_' { |
| 38 | return r |
| 39 | } |
| 40 | return '_' |
| 41 | } |
| 42 | |
| 43 | // baseName returns the last path element of the name, with the last dotted suffix removed. |
| 44 | func baseName(name string) string { |
| 45 | // First, find the last element |
| 46 | if i := strings.LastIndex(name, "/"); i >= 0 { |
| 47 | name = name[i+1:] |
| 48 | } |
| 49 | // Now drop the suffix |
| 50 | if i := strings.LastIndex(name, "."); i >= 0 { |
| 51 | name = name[:i] |
| 52 | } |
| 53 | return name |
| 54 | } |