cmder

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 28, 2020 License: BSD-3-Clause Imports: 2 Imported by: 5

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 a sturct (later implements cmder.Cmder interface) for each command:

type App struct {
	Root bool // storage for flag -R
}
type AppAlpha struct {
	*App         // storage for parent Cmder (embedded)
	Alpha string // storage for flag -A
}
type AppAlphaOne struct {
	*AppAlpha     // storage for parent Cmder (embedded)
	One       int // storage for flag -1
}

Associate Cmders by defining methods returning child Cmder instances:

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

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


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

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

func (app *AppAlphaOne) Cmd() *cobra.Command {
	cmd := &cobra.Command{
		Use: "one",
		Run: func(cmd *cobra.Command, args []string) { fmt.Println(app.Root, app.Alpha, app.One) },
	}
	cmd.Flags().IntVarP(&app.One, "one", "1", 0, "One flag")
	return cmd
}

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

func main() {
	app := &App{}
	cmd := cmder.Cmd(app)
	cmd.SetArgs([]string{"alpha", "one", "-R", "-A", "abc", "-1", "123"})
	err := cmd.Execute()
	if err != nil {
		os.Exit(1)
	}
}

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

Examples

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

Usage in real applications:

Documentation

Overview

Package cmder contains a command builder library 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.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Cmd

func Cmd(cmder Cmder) *cobra.Command

Cmd traverses a Cmder hierarchy and returns a configured cobra.Command. It recursively calls all methods that return a Cmder to collect and associate cobra.Command instances.

Types

type Cmder

type Cmder interface {
	Cmd() *cobra.Command
}

Cmder is an interface for objects that return cobra.Command

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL