github.com/mloves0824/enron/cmd/enron@v0.0.0-20230830012320-113bbf6be3c8/internal/proto/add/add.go (about) 1 package add 2 3 import ( 4 "fmt" 5 "os" 6 "strings" 7 8 "github.com/spf13/cobra" 9 "golang.org/x/mod/modfile" 10 "golang.org/x/text/cases" 11 "golang.org/x/text/language" 12 ) 13 14 // CmdAdd represents the add command. 15 var CmdAdd = &cobra.Command{ 16 Use: "add", 17 Short: "Add a proto API template", 18 Long: "Add a proto API template. Example: enron proto add helloworld/v1/hello.proto", 19 Run: run, 20 } 21 22 func run(_ *cobra.Command, args []string) { 23 if len(args) == 0 { 24 fmt.Println("Please enter the proto file or directory") 25 return 26 } 27 input := args[0] 28 n := strings.LastIndex(input, "/") 29 if n == -1 { 30 fmt.Println("The proto path needs to be hierarchical.") 31 return 32 } 33 path := input[:n] 34 fileName := input[n+1:] 35 pkgName := strings.ReplaceAll(path, "/", ".") 36 37 p := &Proto{ 38 Name: fileName, 39 Path: path, 40 Package: pkgName, 41 GoPackage: goPackage(path), 42 JavaPackage: javaPackage(pkgName), 43 Service: serviceName(fileName), 44 } 45 if err := p.Generate(); err != nil { 46 fmt.Println(err) 47 return 48 } 49 } 50 51 func modName() string { 52 modBytes, err := os.ReadFile("go.mod") 53 if err != nil { 54 if modBytes, err = os.ReadFile("../go.mod"); err != nil { 55 return "" 56 } 57 } 58 return modfile.ModulePath(modBytes) 59 } 60 61 func goPackage(path string) string { 62 s := strings.Split(path, "/") 63 return modName() + "/" + path + ";" + s[len(s)-1] 64 } 65 66 func javaPackage(name string) string { 67 return name 68 } 69 70 func serviceName(name string) string { 71 return toUpperCamelCase(strings.Split(name, ".")[0]) 72 } 73 74 func toUpperCamelCase(s string) string { 75 s = strings.ReplaceAll(s, "_", " ") 76 s = cases.Title(language.Und, cases.NoLower).String(s) 77 return strings.ReplaceAll(s, " ", "") 78 }