simplecommand

package module
v0.5.1 Latest Latest
Warning

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

Go to latest
Published: Feb 20, 2026 License: MIT Imports: 2 Imported by: 1

README

simplecommand

Go Report Card GoDoc codecov

This module provides a *Command type that satisfies the simplecobra.Commander interface.

The main motivation for this module is to only have to implement the bare minimum of methods for any custom commands that are implemented with github.com/bep/simplecobra.

Example

As an example, your command may only need to implement a Run method as it may not rely on any command-line flags, which would look something like this:

package main

import (
    "context"
    "fmt"
    "os"
    
    "github.com/andrewheberle/simplecommand"
    "github.com/bep/simplecobra"
)

type subCommand struct {
    *simplecommand.Command
}

func (c *subCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
    fmt.Printf("This is where the work would be done in sub-command \"%s\" for \"%s\"\n", c.Name(), cd.Root.Command.Name())

    return nil
}

func main() {
    rootCmd := simplecommand.New("root-command", "This is an example root-command")
    rootCmd.SubCommands = []simplecobra.Commander{
        &subCommand{
            Command: simplecommand.New("sub-command", "This is an example sub-command"),
        },
    }

    // Set up simplecobra
    x, err := simplecobra.New(rootCmd)
    if err != nil {
        panic(err)
    }

    // run command with the provided args
    if _, err := x.Execute(context.Background(), os.Args[1:]); err != nil {
        panic(err)
    }
}

Viper Integration

GoDoc

An alternate implementation of the simplecobra.Commander interface is provided by *vipercommand.Command.

This functionality was previously included in *Command however this mean that viper and it's associated dependencies were required even if these features were not used.

To use this functionality you can simple replace *simpleviper.Command in your command's struct with *vipercommand.Command.

Documentation

Overview

The package simplecommand reduces to amount of boilerplate code required to use simplecobra as it provides a *Command type that satisfies the simplecobra.Commander that you can embed within your own custom type and implement your own *Command.Init, *Command.PreRun and *Command.Run methods as required.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Command

type Command struct {
	// CommandName is used as the commands name for any help pages
	CommandName string

	// Short, Long and Deprecated are set to the commands short and long
	// descriptions for help pages when using the default Init method however
	// when implementing your own Init method you should set these yourself.
	Short      string
	Long       string
	Deprecated string

	// SubCommands holds the list of sub-commands for this command
	SubCommands []simplecobra.Commander
}

Command is the basis for creating your own simplecobra.Commander quickly. A *Command satisfies the simplecobra.Commander interface and is best used by embedding it in your own struct.

func New

func New(name, short string, opts ...CommandOption) *Command

New creates a bare minimum *Command with a name and a short description set

Example
package main

import (
	"context"

	"github.com/andrewheberle/simplecommand"
	"github.com/bep/simplecobra"
)

func main() {
	// Here we create a simple command that does nothing
	command := simplecommand.New("example-command", "This is an example command that does nothing")

	// Set up simplecobra
	x, err := simplecobra.New(command)
	if err != nil {
		panic(err)
	}

	// run our simplecobra command with the provided args, in a real program args would be os.Args[1:]
	args := []string{"--help"}
	if _, err := x.Execute(context.Background(), args); err != nil {
		panic(err)
	}

}
Output:

This is an example command that does nothing

Usage:
  example-command [flags] [args]

Flags:
  -h, --help   help for example-command
Example (Embedded)
package main

import (
	"context"
	"fmt"

	"github.com/andrewheberle/simplecommand"
	"github.com/bep/simplecobra"
)

// this is our custom command type
type ourCommand struct {
	exampleFlag string

	*simplecommand.Command
}

// The Init method is implemented to handle our command line flags, however we also run the default *Command.Init method
// to minimise our work a little (ie setting "Short", "Long" and "Deprecated")
func (c *ourCommand) Init(cd *simplecobra.Commandeer) error {

	c.Command.Init(cd)

	cmd := cd.CobraCommand
	cmd.Flags().StringVar(&c.exampleFlag, "example", "", "Example flag")

	return nil
}

// The Run method is implemented to do our actual work
func (c *ourCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
	fmt.Printf("Ran \"%s\" with the example flag set to \"%s\"\n", c.Name(), c.exampleFlag)

	return nil
}

func main() {
	// Here we create a simple command using our custom type
	command := &ourCommand{
		Command: simplecommand.New("example-command", "This is an example command"),
	}

	// Set up simplecobra
	x, err := simplecobra.New(command)
	if err != nil {
		panic(err)
	}

	// run our simplecobra command with the provided args, in a real program args would be os.Args[1:]
	args := []string{"--example", "test"}
	if _, err := x.Execute(context.Background(), args); err != nil {
		panic(err)
	}

}
Output:

Ran "example-command" with the example flag set to "test"
Example (SubCommand)
package main

import (
	"context"
	"fmt"

	"github.com/andrewheberle/simplecommand"
	"github.com/bep/simplecobra"
)

// this is our custom command type
type ourCommand struct {
	exampleFlag string

	*simplecommand.Command
}

// The Init method is implemented to handle our command line flags, however we also run the default *Command.Init method
// to minimise our work a little (ie setting "Short", "Long" and "Deprecated")
func (c *ourCommand) Init(cd *simplecobra.Commandeer) error {

	c.Command.Init(cd)

	cmd := cd.CobraCommand
	cmd.Flags().StringVar(&c.exampleFlag, "example", "", "Example flag")

	return nil
}

// The Run method is implemented to do our actual work
func (c *ourCommand) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error {
	fmt.Printf("Ran \"%s\" with the example flag set to \"%s\"\n", c.Name(), c.exampleFlag)

	return nil
}

func main() {
	// Here we create a command that has one sub-command
	rootCommand := simplecommand.New("example-command", "This is an example command that has a single sub-command")
	rootCommand.SubCommands = []simplecobra.Commander{
		&ourCommand{
			Command: simplecommand.New("sub-command", "This is an example sub-command"),
		},

		// this sub-command will not appear in help output and will print its deprecated message if run
		simplecommand.New("old-command", "This is an old-command", simplecommand.Deprecated("this should no longer be used")),
	}

	// Set up simplecobra
	x, err := simplecobra.New(rootCommand)
	if err != nil {
		panic(err)
	}

	// run our simplecobra command with the provided args, in a real program args would be os.Args[1:]
	args := []string{"sub-command", "--example", "another value"}
	if _, err := x.Execute(context.Background(), args); err != nil {
		panic(err)
	}

}
Output:

Ran "sub-command" with the example flag set to "another value"

func (*Command) Commands

func (c *Command) Commands() []simplecobra.Commander

func (*Command) Init

func (c *Command) Init(cd *simplecobra.Commandeer) error

Init is where the short and long description of the command are set and also where command line flags can be handled. The default is only suitable for implementing a deprecated command (see the Deprecated CommandOption) or a command that does not make use of any command line flags.

See simplecobra.Commander for more information.

func (*Command) Name

func (c *Command) Name() string

func (*Command) PreRun

func (c *Command) PreRun(this, runner *simplecobra.Commandeer) error

PreRun is where command line flags have been parsed, so is a place for any initialisation would go for the command. The default is only suitable for implementing a command that has no reliance on internal state such as command line flags.

See simplecobra.Commander for more information.

func (*Command) Run

func (c *Command) Run(ctx context.Context, cd *simplecobra.Commandeer, args []string) error

Run is where the command actually does it's work The default does no actual work, so is likely not suitable for any use case except for possibly a deprecated command.

See simplecobra.Commander for more information.

type CommandOption

type CommandOption func(*Command)

A CommandOption is passed to New to change the defaults of the *Command

func Deprecated

func Deprecated(reason string) CommandOption

Deprecated sets command as deprecated when the default *Command.Init is used.

func Long

func Long(description string) CommandOption

Long sets the long description of the command when the default *Command.Init is used.

Example
package main

import (
	"context"

	"github.com/andrewheberle/simplecommand"
	"github.com/bep/simplecobra"
)

func main() {
	// Here we create a simple command that does nothing
	command := simplecommand.New("example-command",
		"This is an example command that does nothing",
		simplecommand.Long(`Here is a much longer help description of this example-command
that is shown when the --help flag is provided.

This can include line breaks and be as long as you like.`),
	)

	// Set up simplecobra
	x, err := simplecobra.New(command)
	if err != nil {
		panic(err)
	}

	// run our simplecobra command with the provided args, in a real program args would be os.Args[1:]
	args := []string{"--help"}
	if _, err := x.Execute(context.Background(), args); err != nil {
		panic(err)
	}

}
Output:

Here is a much longer help description of this example-command
that is shown when the --help flag is provided.

This can include line breaks and be as long as you like.

Usage:
  example-command [flags] [args]

Flags:
  -h, --help   help for example-command

Directories

Path Synopsis
vipercommand module

Jump to

Keyboard shortcuts

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