Skip to content
Myr

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

4 files+73 added−36 removed

modified:cobra/cmd/testdata/main.go.golden+1 added-1 removed
13 unmodified lines
14limitations under the License.15*/16package main1718import "github.com/spf13/testproject/cmd"18import "github.com/spf13/cobra/cobra/cmd/cmd"1920func main() {21 cmd.Execute()22}
modified:cobra/cmd/testdata/root.go.golden+5 added-5 removed
16 unmodified lines
1718import (19 "fmt"20 "os"21 "github.com/spf13/cobra"2122 "github.com/spf13/cobra"23 "github.com/spf13/viper"24)2526var cfgFile string2728// rootCmd represents the base command when called without any subcommands29var 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 contains33examples and usage of using your application. For example:34
17 unmodified lines
52 // 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.5556 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)")5758 // 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 lines
69 // Find home directory.70 home, err := os.UserHomeDir()71 cobra.CheckErr(err)7273 // 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 }7879 viper.AutomaticEnv() // read in environment variables that match80
5 unmodified lines
modified:cobra/cmd/init_test.go+3 added-16 removed
14 unmodified lines
15 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 lines
36 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 }4647 for _, tt := range tests {48 t.Run(tt.name, func(t *testing.T) {4962 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 lines
modified: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 at
7 unmodified lines
1314package cmd1516import (17 "encoding/json"18 "fmt"19 "os"20 "os/exec"21 "path"22 "path/filepath"23 "strings"2425 "github.com/spf13/cobra"26 "github.com/spf13/viper"27)2829var (26 pkgName string2730 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 license35and the appropriate structure for a Cobra-based CLI application.3635 * 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;37Cobra init must be run inside of a go module (please run "go mod init <MODNAME>" first)38`,3940 Run: func(_ *cobra.Command, args []string) {4041 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)5148func init() {49 initCmd.Flags().StringVar(&pkgName, "pkg-name", "", "fully qualified pkg name")50 cobra.CheckErr(initCmd.MarkFlagRequired("pkg-name"))51}5252func initializeProject(args []string) (string, error) {53 wd, err := os.Getwd()54 if err != nil {55 return "", err
4 unmodified lines
60 wd = fmt.Sprintf("%s/%s", wd, args[0])61 }62 }6364 modName := getModImportPath()6566 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 }7475 if err := project.Create(); err != nil {76 return "", err77 }7879 return project.AbsolutePath, nil80}8182func getModImportPath() string {83 mod, cd := parseModInfo()84 return path.Join(mod.Path, fileToURL(strings.TrimPrefix(cd.Dir, mod.Dir)))85}8687func fileToURL(in string) string {88 i := strings.Split(in, string(filepath.Separator))89 return path.Join(i...)90}9192func parseModInfo() (Mod, CurDir) {93 var mod Mod94 var dir CurDir9596 m := modInfoJSON("-m")97 cobra.CheckErr(json.Unmarshal(m, &mod))9899 // 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 }103104 e := modInfoJSON("-e")105 cobra.CheckErr(json.Unmarshal(e, &dir))106107 return mod, dir108}109110type Mod struct {111 Path, Dir, GoMod string112}113114type CurDir struct {115 Dir string116}117118func goGet(mod string) error {119 cmd := exec.Command("go", "get", mod)120 return cmd.Run()121}122123func modInfoJSON(args ...string) []byte {124 cmdArgs := append([]string{"list", "-json"}, args...)125 out, err := exec.Command("go", cmdArgs...).Output()126 cobra.CheckErr(err)127128 return out129}