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 7 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
12 changes: 8 additions & 4 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 Expand Up @@ -88,7 +88,7 @@ have children commands and optionally run an action.

In the example above, 'server' is the command.

[More about cobra.Command](https://godoc.org/github.com/spf13/cobra#Command)
[More about cobra.Command](https://pkg.go.dev/github.com/spf13/cobra#Command)

## Flags

Expand Down Expand Up @@ -117,8 +117,12 @@ import "github.com/spf13/cobra"
```

# Usage
Cobra provides its own program that will create your application and add any
commands you want. It's the easiest way to incorporate Cobra into your application.

See [User Guide](user_guide.md).
For complete details on using the Cobra generator, please read [The Cobra Generator README](https://github.com/spf13/cobra/blob/master/cobra/README.md)

For complete details on using the Cobra library, please read the [The Cobra User Guide](user_guide.md).

# License

Expand Down
88 changes: 69 additions & 19 deletions cobra/README.md
Expand Up @@ -3,41 +3,78 @@
Cobra provides its own program that will create your application and add any
commands you want. It's the easiest way to incorporate Cobra into your application.

In order to use the cobra command, compile it using the following command:
Install the cobra generator with the command `go install github.com/spf13/cobra/cobra`.
Copy link
Contributor

Choose a reason for hiding this comment

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

Copy link
Owner Author

Choose a reason for hiding this comment

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

good idea.

Go will automatically install it in your `$GOPATH/bin` directory which should be in your $PATH.

go get github.com/spf13/cobra/cobra
Once installed you should have the `cobra` command available. Confirm by typing `cobra` at a
command line.

This will create the cobra executable under your `$GOPATH/bin` directory.
There are only two operations currently supported by Cobra generator:
spf13 marked this conversation as resolved.
Show resolved Hide resolved

### cobra init

The `cobra init [app]` command will create your initial application code
for you. It is a very powerful application that will populate your program with
the right structure so you can immediately enjoy all the benefits of Cobra. It
will also automatically apply the license you specify to your application.
the right structure so you can immediately enjoy all the benefits of Cobra.
It can also apply the license you specify to your application.

Cobra init is pretty smart. You can either run it in your current application directory
or you can specify a relative path to an existing project. If the directory does not exist, it will be created for you.
With the introduction of Go modules, the Cobra generator has been simplified to
take advantage of modules. The Cobra generator works from within a Go module.

Updates to the Cobra generator have now decoupled it from the GOPATH.
As such `--pkg-name` is required.
#### Initalizing a module

**Note:** init will no longer fail on non-empty directories.
__If you already have a module, skip this step.__

If you want to initialize a new Go module:

1. Create a new directory
2. `cd` into that directory
3. run `go mod init <MODNAME>`

e.g.
```
mkdir -p newApp && cd newApp
cobra init --pkg-name github.com/spf13/newApp
cd $HOME/code
mkdir myapp
cd myapp
go mod init github.com/spf13/myapp
```

or
#### Initalizing an Cobra CLI application

From within a Go module run `cobra init`. This will create a new barebones project
for you to edit.

You should be able to run you new application immediately. Try it with
spf13 marked this conversation as resolved.
Show resolved Hide resolved
`go run main.go`.

You will want to open up and edit 'cmd/root.go' and provide your own description and logic.

e.g.
```
cobra init --pkg-name github.com/spf13/newApp path/to/newApp
cd $HOME/code/myapp
cobra init
go run main.go
```

### cobra add
Cobra init can also be run from a subdirectory such as how the [cobra generator itself is organized](https://github.com/spf13/cobra).
This is useful if you want to keep your application code separate from your library code.

#### Optional flags:
You can provide it your author name with the `--author` flag.
e.g. `cobra init --author "Steve Francia spf@spf13.com"`

You can provide a license to use with `--license`
e.g. `cobra init --license apache`

Use the `--viper` flag to automatically setup [viper](https://github.com/spf13/viper)

Viper is a companion to Cobra intended to provide easy handling of environment variables and config files and seamlessly connecting them to the application flags.

### Add commands to a project

Once a cobra application is initialized you can continue to use cobra generator to
spf13 marked this conversation as resolved.
Show resolved Hide resolved
add additional commands to your application. The command to do this is `cobra add`.

Once an application is initialized, Cobra can create additional commands for you.
Let's say you created an app and you wanted the following commands for it:

* app serve
Expand All @@ -52,6 +89,14 @@ cobra add config
cobra add create -p 'configCmd'
```

`cobra add` supports all the same optional flags as `cobra init` does mentioned above.
spf13 marked this conversation as resolved.
Show resolved Hide resolved

You'll notice that this final command has a `-p` flag. This is used to assign a
parent command to the newly added command. In this case, we want to assign the
"create" command to the "config" command. All commands have a default parent of rootCmd if not specified.

By default `cobra` will append `Cmd` to the name provided and uses this to name for the internal variable name. When specifying a parent, be sure to match the variable name used in the code.
spf13 marked this conversation as resolved.
Show resolved Hide resolved

*Note: Use camelCase (not snake_case/kebab-case) for command names.
Otherwise, you will encounter errors.
For example, `cobra add add-user` is incorrect, but `cobra add addUser` is valid.*
Expand All @@ -62,18 +107,22 @@ the following:
```
▾ app/
▾ cmd/
serve.go
config.go
create.go
serve.go
root.go
main.go
```

At this point you can run `go run main.go` and it would run your app. `go run
main.go serve`, `go run main.go config`, `go run main.go config create` along
with `go run main.go help serve`, etc. would all work.

Obviously you haven't added your own code to these yet. The commands are ready
for you to give them their tasks. Have fun!
You now have a basic Cobra-based application up and running. Next step is to edit the files in cmd and customize them for your application.

For complete details on using the Cobra library, please read the [The Cobra User Guide](https://github.com/spf13/cobra/blob/master/user_guide.md#using-the-cobra-library).

Have fun!

### Configuring the cobra generator

Expand All @@ -86,6 +135,7 @@ An example ~/.cobra.yaml file:
```yaml
author: Steve Francia <spf@spf13.com>
license: MIT
viper: true
```

You can also use built-in licenses. For example, **GPLv2**, **GPLv3**, **LGPL**,
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
77 changes: 63 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,51 @@ 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 {
return exec.Command("go", "get", mod).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