Created
June 2, 2021 01:56
-
-
Save RoryQ/5de8b9c606b423d62343f69ffa059f6f to your computer and use it in GitHub Desktop.
renumber protobuf model fields to start from one
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // This go program will renumber the proto model fields in gen/models starting at 1. | |
| package main | |
| import ( | |
| "flag" | |
| "fmt" | |
| "io/ioutil" | |
| "os" | |
| "path/filepath" | |
| "regexp" | |
| "strings" | |
| ) | |
| var protoDir = flag.String("dir", "gen/models", "directory containing protobuf models") | |
| func main() { | |
| flag.Parse() | |
| _ = filepath.Walk(*protoDir, func(path string, info os.FileInfo, err error) error { | |
| if !info.IsDir() && strings.HasSuffix(info.Name(), ".proto") { | |
| fmt.Println(path) | |
| bytes, _ := ioutil.ReadFile(path) | |
| renumberedAll := renumberAllMessages(string(bytes)) | |
| ioutil.WriteFile(path, []byte(renumberedAll), 0644) | |
| } | |
| return nil | |
| }) | |
| } | |
| func renumberAllMessages(text string) string { | |
| messages := regexp.MustCompile(`(?sm)^message.*?{$.*?^}`).FindAllString(text, -1) | |
| for _, msg := range messages { | |
| renumbered := renumberFields(msg) | |
| text = strings.ReplaceAll(text, msg, renumbered) | |
| } | |
| return text | |
| } | |
| func renumberFields(text string) string { | |
| loc := regexp.MustCompile(`(?sm){$.*^}`).FindStringIndex(text) | |
| body := text[loc[0]:loc[1]] | |
| i := 1 | |
| replaced := regexp.MustCompile(`(?sm)\d+;$`).ReplaceAllStringFunc(body, func(s string) string { | |
| s = fmt.Sprintf("%d;", i) | |
| i++ | |
| return s | |
| }) | |
| return strings.ReplaceAll(text, body, replaced) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment