cc
github.com/yaegashi/cobra-cmder
go get github.com/yaegashi/cobra-cmder
cc

github.com/yaegashi/cobra-cmder

Useful command builder for spf13/cobra

by YAEGASHI Takeshi

v0.0.1 (see all)License:BSD-3-Clause
go get github.com/yaegashi/cobra-cmder
Readme

cobra-cmder

go.dev

Introduction

This Go module contains cmder library package which is a useful command builder for spf13/cobra.

It helps you to easily build a cobra.Command hierarchy in the non-invasive and test-friendly way without any global variables or init().

Basic usage

Define each command's sturct that implements Cmder interface:

type App struct {
    Bool bool // storage for flag -b
}
type AppAlpha struct {
    *App          // storage for parent Cmder (embedded)
    String string // storage for flag -s
}
type AppAlphaOne struct {
    *AppAlpha     // storage for parent Cmder (embedded)
    Int       int // storage for flag -i
}

Define each Comder's Cmd() method that returns *cobra.Command:

func (app *App) Cmd() *cobra.Command {
    cmd := &cobra.Command{
        Use: "app",
    }
    cmd.PersistentFlags().BoolVarP(&app.Bool, "bool", "b", false, "Bool flag")
    return cmd
}

func (app *AppAlpha) Cmd() *cobra.Command {
    cmd := &cobra.Command{
        Use: "alpha",
    }
    cmd.PersistentFlags().StringVarP(&app.String, "string", "s", "", "String flag")
    return cmd
}

func (app *AppAlphaOne) Cmd() *cobra.Command {
    cmd := &cobra.Command{
        Use: "one",
        Run: app.Run,
    }
    cmd.Flags().IntVarP(&app.Int, "int", "i", 0, "Int flag")
    return cmd
}

func (app *AppAlphaOne) Run(cmd *cobra.Command, args []string) {
    fmt.Println(app.Bool, app.String, app.Int)
}

Associate Cmders each other by defining a method that returns a child Cmder:

func (app *App) AppAlphaCmder() cmder.Cmder         { return &AppAlpha{App: app} }
func (app *AppAlpha) AppAlphaOneCmder() cmder.Cmder { return &AppAlphaOne{AppAlpha: app} }

Call cmder.Cmd() to collect and associate all cobra.Command instances:

func main() {
    app := &App{}
    cmd := cmder.Cmd(app)
    err := cmd.Execute()
    if err != nil {
        os.Exit(1)
    }
}

Visit https://play.golang.org/p/zw4arxJfUkt to see and test the complete source code.

Unit test

You can easily perform the Go standard unit tests on CLI apps with cobra-cmder.

See https://play.golang.org/p/tijvjDzmwqW for another example.

Examples

See the sample CLI app in cmd/sample for more comprehensive example.

Usage in real applications:

GitHub Stars

11

LAST COMMIT

2yrs ago

MAINTAINERS

0

CONTRIBUTORS

1

OPEN ISSUES

0

OPEN PRs

0
VersionTagPublished
v0.0.1
2yrs ago
v0.0.0-20200628142505-a2967771bb84
2yrs ago
v0.0.0-20200628124938-5ed492801bc5
2yrs ago
v0.0.0-20200628123847-e4e907acc944
2yrs ago
No alternatives found
No tutorials found
Add a tutorial