Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Module aware generator #1436

Merged
merged 8 commits into from Nov 3, 2021
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Expand Up @@ -46,15 +46,15 @@ Cobra provides:
* Fully POSIX-compliant flags (including short & long versions)
* Nested subcommands
* Global, local and cascading flags
* Easy generation of applications & commands with `cobra init appname` & `cobra add cmdname`
* Easy generation of applications & commands with `cobra init` & `cobra add cmdname`
* Intelligent suggestions (`app srver`... did you mean `app server`?)
* Automatic help generation for commands and flags
* Automatic help flag recognition of `-h`, `--help`, etc.
* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)
* Automatically generated man pages for your application
* Command aliases so you can change things without breaking them
* The flexibility to define your own help, usage, etc.
* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps
* Optional seamless integration with [viper](http://github.com/spf13/viper) for 12-factor apps

# Concepts

Expand Down
4 changes: 4 additions & 0 deletions cobra/cmd/add_test.go
Expand Up @@ -4,9 +4,13 @@ import (
"fmt"
"os"
"testing"

"github.com/spf13/viper"
)

func TestGoldenAddCmd(t *testing.T) {
viper.Set("useViper", true)
viper.Set("license", "apache")
command := &Command{
CmdName: "test",
CmdParent: parentName,
Expand Down
78 changes: 64 additions & 14 deletions cobra/cmd/init.go
@@ -1,4 +1,4 @@
// Copyright © 2015 Steve Francia <spf@spf13.com>.
// Copyright © 2021 Steve Francia <spf@spf13.com>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand All @@ -14,42 +14,41 @@
package cmd

import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"strings"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var (
pkgName string

initCmd = &cobra.Command{
Use: "init [name]",
Use: "init [path]",
Aliases: []string{"initialize", "initialise", "create"},
Short: "Initialize a Cobra Application",
Long: `Initialize (cobra init) will create a new application, with a license
and the appropriate structure for a Cobra-based CLI application.

* If a name is provided, a directory with that name will be created in the current directory;
* If no name is provided, the current directory will be assumed;
Cobra init must be run inside of a go module (please run "go mod init <MODNAME>" first)
`,

Run: func(_ *cobra.Command, args []string) {

projectPath, err := initializeProject(args)
cobra.CheckErr(err)
cobra.CheckErr(goGet("github.com/spf13/cobra"))
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not sure how I feel about this utility fetching dependencies for the user. @wfernandes @jpmcb thoughts here?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess the point is having them explicitly added to the go.mod file of the user? Not so much about fetching them.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, that is the intent. Russ Cox suggested we do this extra step and I agree. It streamlines the experience for the user as well as simplifying the instructions.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One of the motivations for this update is that we are writing a tutorial on building CLIs with Go for golang.org / go.dev which uses Cobra. As we wrote the tutorial it became clear that there were lots of places in the onboarding experience that could be streamlined. This set of changes comes from those learnings.

Copy link
Contributor

@umarcor umarcor Jul 2, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@spf13, in the context of writing a tutorial and streamlining the experience for newcommers, you might want to have a look at #1240. I do think that might be a very disruptive change, but at the same time it would be very valuable to have your feedback.

That is also the purpose of #1430.

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my note on #1240. I think we're likely to resolve this in the next few months by removing the need for cobra generator entirely.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As we wrote the tutorial it became clear that there were lots of places in the onboarding experience that could be streamlined.

I'm inclined to agree on this point but am always wary of tools that try to do too many things.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can move forward with this change though.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this is just in the cobra CLI tool, sounds good to me. I'd be more cautious of anything in the API that would automatically fetch dependencies. But it makes sense to try and streamline the onboarding experience and get people up and going with cobra init as quick as possible 👍

if viper.GetBool("useViper") {
cobra.CheckErr(goGet("github.com/spf13/viper"))
}
fmt.Printf("Your Cobra application is ready at\n%s\n", projectPath)
},
}
)

func init() {
initCmd.Flags().StringVar(&pkgName, "pkg-name", "", "fully qualified pkg name")
jharshman marked this conversation as resolved.
Show resolved Hide resolved
cobra.CheckErr(initCmd.MarkFlagRequired("pkg-name"))
}

func initializeProject(args []string) (string, error) {
wd, err := os.Getwd()
if err != nil {
Expand All @@ -62,13 +61,15 @@ func initializeProject(args []string) (string, error) {
}
}

modName := getModImportPath()

project := &Project{
AbsolutePath: wd,
PkgName: pkgName,
PkgName: modName,
Legal: getLicense(),
Copyright: copyrightLine(),
Viper: viper.GetBool("useViper"),
AppName: path.Base(pkgName),
AppName: path.Base(modName),
}

if err := project.Create(); err != nil {
Expand All @@ -77,3 +78,52 @@ func initializeProject(args []string) (string, error) {

return project.AbsolutePath, nil
}

func getModImportPath() string {
mod, cd := parseModInfo()
return path.Join(mod.Path, fileToURL(strings.TrimPrefix(cd.Dir, mod.Dir)))
}

func fileToURL(in string) string {
spf13 marked this conversation as resolved.
Show resolved Hide resolved
i := strings.Split(in, string(filepath.Separator))
return path.Join(i...)
}

func parseModInfo() (Mod, CurDir) {
var mod Mod
var dir CurDir

m := modInfoJSON("-m")
cobra.CheckErr(json.Unmarshal(m, &mod))

// Unsure why, but if no module is present Path is set to this string.
if mod.Path == "command-line-arguments" {
cobra.CheckErr("Please run `go mod init <MODNAME>` before `cobra init`")
}

e := modInfoJSON("-e")
cobra.CheckErr(json.Unmarshal(e, &dir))

return mod, dir
}

type Mod struct {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: can you put each of these variables on their own line?

Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I can. What is the motivation for doing so? (mostly just curious).

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

For me it's readability. I find it easier to read the structure fields when they are not condensed on one line.

Path, Dir, GoMod string
}

type CurDir struct {
Dir string
}

func goGet(mod string) error {
cmd := exec.Command("go", "get", mod)
spf13 marked this conversation as resolved.
Show resolved Hide resolved
return cmd.Run()
}

func modInfoJSON(args ...string) []byte {
cmdArgs := append([]string{"list", "-json"}, args...)
out, err := exec.Command("go", cmdArgs...).Output()
cobra.CheckErr(err)

return out
}
20 changes: 4 additions & 16 deletions cobra/cmd/init_test.go
Expand Up @@ -16,8 +16,8 @@ func getProject() *Project {
AbsolutePath: fmt.Sprintf("%s/testproject", wd),
Legal: getLicense(),
Copyright: copyrightLine(),
AppName: "testproject",
PkgName: "github.com/spf13/testproject",
AppName: "cmd",
PkgName: "github.com/spf13/cobra/cobra/cmd/cmd",
Viper: true,
}
}
Expand All @@ -37,30 +37,18 @@ func TestGoldenInitCmd(t *testing.T) {
expectErr bool
}{
{
name: "successfully creates a project with name",
name: "successfully creates a project based on module",
args: []string{"testproject"},
pkgName: "github.com/spf13/testproject",
expectErr: false,
},
{
name: "returns error when passing an absolute path for project",
args: []string{dir},
pkgName: "github.com/spf13/testproject",
expectErr: true,
},
{
name: "returns error when passing a relative path for project",
args: []string{"github.com/spf13/testproject"},
pkgName: "github.com/spf13/testproject",
expectErr: true,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {

assertNoErr(t, initCmd.Flags().Set("pkg-name", tt.pkgName))
viper.Set("useViper", true)
viper.Set("license", "apache")
projectPath, err := initializeProject(tt.args)
defer func() {
if projectPath != "" {
Expand Down
8 changes: 4 additions & 4 deletions cobra/cmd/licenses.go
@@ -1,4 +1,4 @@
// Copyright © 2015 Steve Francia <spf@spf13.com>.
// Copyright © 2021 Steve Francia <spf@spf13.com>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -53,7 +53,7 @@ func init() {
}

// getLicense returns license specified by user in flag or in config.
// If user didn't specify the license, it returns Apache License 2.0.
// If user didn't specify the license, it returns none
//
// TODO: Inspect project for existing license
func getLicense() License {
Expand All @@ -73,8 +73,8 @@ func getLicense() License {
return findLicense(viper.GetString("license"))
}

// If user didn't set any license, use Apache 2.0 by default.
return Licenses["apache"]
// If user didn't set any license, use none by default
return Licenses["none"]
}

func copyrightLine() string {
Expand Down
6 changes: 3 additions & 3 deletions cobra/cmd/root.go
@@ -1,4 +1,4 @@
// Copyright © 2015 Steve Francia <spf@spf13.com>.
// Copyright © 2021 Steve Francia <spf@spf13.com>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
Expand Down Expand Up @@ -46,11 +46,11 @@ func init() {
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
rootCmd.PersistentFlags().Bool("viper", false, "use Viper for configuration")
cobra.CheckErr(viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author")))
cobra.CheckErr(viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper")))
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
viper.SetDefault("license", "apache")
viper.SetDefault("license", "none")

rootCmd.AddCommand(addCmd)
rootCmd.AddCommand(initCmd)
Expand Down
2 changes: 1 addition & 1 deletion cobra/cmd/testdata/main.go.golden
Expand Up @@ -15,7 +15,7 @@ limitations under the License.
*/
package main

import "github.com/spf13/testproject/cmd"
import "github.com/spf13/cobra/cobra/cmd/cmd"

func main() {
cmd.Execute()
Expand Down
10 changes: 5 additions & 5 deletions cobra/cmd/testdata/root.go.golden
Expand Up @@ -18,16 +18,16 @@ package cmd
import (
"fmt"
"os"
"github.com/spf13/cobra"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var cfgFile string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "testproject",
Use: "cmd",
Short: "A brief description of your application",
Long: `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:
Expand All @@ -53,7 +53,7 @@ func init() {
// Cobra supports persistent flags, which, if defined here,
// will be global for your application.

rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.testproject.yaml)")
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cmd.yaml)")

// Cobra also supports local flags, which will only run
// when this action is called directly.
Expand All @@ -70,10 +70,10 @@ func initConfig() {
home, err := os.UserHomeDir()
cobra.CheckErr(err)

// Search config in home directory with name ".testproject" (without extension).
// Search config in home directory with name ".cmd" (without extension).
viper.AddConfigPath(home)
viper.SetConfigType("yaml")
viper.SetConfigName(".testproject")
viper.SetConfigName(".cmd")
}

viper.AutomaticEnv() // read in environment variables that match
Expand Down
17 changes: 16 additions & 1 deletion cobra/tpl/main.go
@@ -1,3 +1,16 @@
// Copyright © 2021 Steve Francia <spf@spf13.com>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package tpl

func MainTemplate() []byte {
Expand All @@ -23,10 +36,12 @@ func RootTemplate() []byte {
package cmd

import (
{{- if .Viper }}
"fmt"
"os"
{{ end }}
"github.com/spf13/cobra"
{{ if .Viper }}
{{- if .Viper }}
"github.com/spf13/viper"{{ end }}
)

Expand Down