Cobra generator now works within Go modules
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Pretty major change in behavior, but with modules a change is needed. Now cobra can initialize and add from within any Go module. The experience is simplified and streamlined, but requires `go mod init` to happen first.
authored by Steve Francia · committed by Steve Francia · parent c9edb78 · Browse files · 4 files·+73 added−36 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+73 added−36 removed
- other:+73 added−36 removed
Provenance
- Commit
9388e79- Tree
af4dba9- Author
Steve Francia <steve.francia@gmail.com>- Committer
Steve Francia <steve.francia@gmail.com>- Parent
c9edb78
4 files changed+73 added−36 removed
modified:cobra/cmd/testdata/main.go.golden+1 added-1 removed
13 unmodified lines14 limitations under the License.15 */16 package main17 18-import "github.com/spf13/testproject/cmd"18+import "github.com/spf13/cobra/cobra/cmd/cmd"19 20 func main() {21 cmd.Execute()22 }modified:cobra/cmd/testdata/root.go.golden+5 added-5 removed
16 unmodified lines17 18 import (19 "fmt"20 "os"21- "github.com/spf13/cobra"21 22+ "github.com/spf13/cobra"23 "github.com/spf13/viper"24 )25 26 var cfgFile string27 28 // rootCmd represents the base command when called without any subcommands29 var rootCmd = &cobra.Command{30- Use: "testproject",30+ Use: "cmd",31 Short: "A brief description of your application",32 Long: `A longer description that spans multiple lines and likely contains33 examples and usage of using your application. For example:34 17 unmodified lines52 // Here you will define your flags and configuration settings.53 // Cobra supports persistent flags, which, if defined here,54 // will be global for your application.55 56- rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.testproject.yaml)")56+ rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cmd.yaml)")57 58 // Cobra also supports local flags, which will only run59 // when this action is called directly.60 rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")8 unmodified lines69 // Find home directory.70 home, err := os.UserHomeDir()71 cobra.CheckErr(err)72 73- // Search config in home directory with name ".testproject" (without extension).73+ // Search config in home directory with name ".cmd" (without extension).74 viper.AddConfigPath(home)75 viper.SetConfigType("yaml")76- viper.SetConfigName(".testproject")76+ viper.SetConfigName(".cmd")77 }78 79 viper.AutomaticEnv() // read in environment variables that match80 5 unmodified linesmodified:cobra/cmd/init_test.go+3 added-16 removed
14 unmodified lines15 return &Project{16 AbsolutePath: fmt.Sprintf("%s/testproject", wd),17 Legal: getLicense(),18 Copyright: copyrightLine(),19- AppName: "testproject",20- PkgName: "github.com/spf13/testproject",19+ AppName: "cmd",20+ PkgName: "github.com/spf13/cobra/cobra/cmd/cmd",21 Viper: true,22 }23 }24 11 unmodified lines36 pkgName string37 expectErr bool38 }{39 {40- name: "successfully creates a project with name",40+ name: "successfully creates a project based on module",41 args: []string{"testproject"},42 pkgName: "github.com/spf13/testproject",43 expectErr: false,44 },45- {46- name: "returns error when passing an absolute path for project",47- args: []string{dir},48- pkgName: "github.com/spf13/testproject",49- expectErr: true,50- },51- {52- name: "returns error when passing a relative path for project",53- args: []string{"github.com/spf13/testproject"},54- pkgName: "github.com/spf13/testproject",55- expectErr: true,56- },45 }46 47 for _, tt := range tests {48 t.Run(tt.name, func(t *testing.T) {49 62- assertNoErr(t, initCmd.Flags().Set("pkg-name", tt.pkgName))50 viper.Set("useViper", true)51 viper.Set("license", "apache")52 projectPath, err := initializeProject(tt.args)53 defer func() {29 unmodified linesmodified:cobra/cmd/init.go+64 added-14 removed
1-// Copyright © 2015 Steve Francia <spf@spf13.com>.1+// Copyright © 2021 Steve Francia <spf@spf13.com>.2 //3 // Licensed under the Apache License, Version 2.0 (the "License");4 // you may not use this file except in compliance with the License.5 // You may obtain a copy of the License at7 unmodified lines13 14 package cmd15 16 import (17+ "encoding/json"18 "fmt"19 "os"20+ "os/exec"21 "path"22+ "path/filepath"23+ "strings"24 25 "github.com/spf13/cobra"26 "github.com/spf13/viper"27 )28 29 var (26- pkgName string27-30 initCmd = &cobra.Command{29- Use: "init [name]",31+ Use: "init [path]",32 Aliases: []string{"initialize", "initialise", "create"},33 Short: "Initialize a Cobra Application",34 Long: `Initialize (cobra init) will create a new application, with a license35 and the appropriate structure for a Cobra-based CLI application.36 35- * If a name is provided, a directory with that name will be created in the current directory;36- * If no name is provided, the current directory will be assumed;37+Cobra init must be run inside of a go module (please run "go mod init <MODNAME>" first)38 `,39 40 Run: func(_ *cobra.Command, args []string) {40-41 projectPath, err := initializeProject(args)42 cobra.CheckErr(err)43+ cobra.CheckErr(goGet("github.com/spf13/cobra"))44+ if viper.GetBool("useViper") {45+ cobra.CheckErr(goGet("github.com/spf13/viper"))46+ }47 fmt.Printf("Your Cobra application is ready at\n%s\n", projectPath)48 },49 }50 )51 48-func init() {49- initCmd.Flags().StringVar(&pkgName, "pkg-name", "", "fully qualified pkg name")50- cobra.CheckErr(initCmd.MarkFlagRequired("pkg-name"))51-}52-52 func initializeProject(args []string) (string, error) {53 wd, err := os.Getwd()54 if err != nil {55 return "", err4 unmodified lines60 wd = fmt.Sprintf("%s/%s", wd, args[0])61 }62 }63 64+ modName := getModImportPath()65+66 project := &Project{67 AbsolutePath: wd,67- PkgName: pkgName,68+ PkgName: modName,69 Legal: getLicense(),70 Copyright: copyrightLine(),71 Viper: viper.GetBool("useViper"),71- AppName: path.Base(pkgName),72+ AppName: path.Base(modName),73 }74 75 if err := project.Create(); err != nil {76 return "", err77 }78 79 return project.AbsolutePath, nil80 }81+82+func getModImportPath() string {83+ mod, cd := parseModInfo()84+ return path.Join(mod.Path, fileToURL(strings.TrimPrefix(cd.Dir, mod.Dir)))85+}86+87+func fileToURL(in string) string {88+ i := strings.Split(in, string(filepath.Separator))89+ return path.Join(i...)90+}91+92+func parseModInfo() (Mod, CurDir) {93+ var mod Mod94+ var dir CurDir95+96+ m := modInfoJSON("-m")97+ cobra.CheckErr(json.Unmarshal(m, &mod))98+99+ // Unsure why, but if no module is present Path is set to this string.100+ if mod.Path == "command-line-arguments" {101+ cobra.CheckErr("Please run `go mod init <MODNAME>` before `cobra init`")102+ }103+104+ e := modInfoJSON("-e")105+ cobra.CheckErr(json.Unmarshal(e, &dir))106+107+ return mod, dir108+}109+110+type Mod struct {111+ Path, Dir, GoMod string112+}113+114+type CurDir struct {115+ Dir string116+}117+118+func goGet(mod string) error {119+ cmd := exec.Command("go", "get", mod)120+ return cmd.Run()121+}122+123+func modInfoJSON(args ...string) []byte {124+ cmdArgs := append([]string{"list", "-json"}, args...)125+ out, err := exec.Command("go", cmdArgs...).Output()126+ cobra.CheckErr(err)127+128+ return out129+}