cmd

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Jun 12, 2026 License: MPL-2.0 Imports: 32 Imported by: 0

Documentation

Overview

Package cmd provides the structures and functions for constructing commands.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrDisplayHelp can be returned from a run command to print the help text.
	ErrDisplayHelp = errors.New("help")

	// ErrDisplayUsage can be returned from a run command to print the usage text.
	ErrDisplayUsage = errors.New("usage")

	// ErrUnderlyingError can be returned when the command ran successfully but
	// detected an underlying problem (e.g. inspecting a resource that is in an
	// error state). Exits with code 6 and no additional output.
	ErrUnderlyingError = errors.New("underlying error")
)

Functions

func ArbitraryArgs

func ArbitraryArgs(_ *Command, _ []string) error

ArbitraryArgs never returns an error and is used to bypass argument validation at the command level.

func ConfigureRootCommand

func ConfigureRootCommand(i *Invocation, cmd *Command)

ConfigureRootCommand should be only called on the root command. It configures global flags and ensures that the invocation is configured based on any flags set during a command invocation.

func GenMarkdown

func GenMarkdown(c *Command, w io.Writer, link LinkHandler) error

GenMarkdown creates custom markdown output.

func GenMarkdownTree

func GenMarkdownTree(c *Command, dir string, link LinkHandler) error

GenMarkdownTree creates a markdown file for the command and all of its children.

func GenNavJSON

func GenNavJSON(c *Command, w io.Writer) error

GenNavJSON generates the navigation JSON in the format that web-unified-docs expects, for the command structure.

func NewExitError

func NewExitError(code int, wrapErr error) error

NewExitError returns an ExitCodeError. This can be returned to have the command exit code be set to a specific value.

func NoArgs

func NoArgs(_ *Command, args []string) error

NoArgs is a ValidateArgsFunc that validates that no arguments are received.

func RootHelpFunc

func RootHelpFunc(c *Command) func(map[string]cli.CommandFactory) string

RootHelpFunc returns a help function that meets the hashicorp/cli interface for help functions.

func ToCommandMap

func ToCommandMap(c *Command, inv *Invocation) map[string]cli.CommandFactory

ToCommandMap converts a Command and its children to a hashicorp/cli command factory map. The passed Command should be the root command.

Types

type Command

type Command struct {

	// Name is the name of the command.
	Name string

	// Aliases is an array of aliases that can be used instead of the first word
	// in Usage.
	Aliases []string

	// ShortHelp is the short description shown when listing subcommands or when
	// the command is incorrectly invoked.
	ShortHelp string

	// LongHelp is the long message shown in the '<this-command> --help' output.
	LongHelp string

	// Examples is a set of examples of how to use the command.
	Examples []Example

	// AdditionalDocs allows adding additional documentation sections.
	AdditionalDocs []DocSection

	// PersistentPreRun is the set of functions to run for this command and all
	// subcommands.
	PersistentPreRun func(c *Command, args []string) error

	// RunF is the function that will be run when the command is invoked. It may
	// be nil if the command contains children.
	RunF func(c *Command, args []string) error

	// Hidden hides the command from help output and command listings while
	// still allowing it to be invoked directly.
	Hidden bool

	// NoAuthRequired allows a command to indicate that authentication is not
	// required to be invoked.
	NoAuthRequired bool

	// Args documents the expected positional arguments.
	Args PositionalArguments

	// Flags is the set of flags for this command.
	Flags Flags
	// contains filtered or unexported fields
}

Command is used to construct a command.

To create a command that should not be invoked itself but is only used to nest sub-commands, construct the Command without a Run function and call AddChild to add the child commands.

func (*Command) AddChild

func (c *Command) AddChild(cmd *Command)

AddChild is used to add a child command.

func (*Command) CommandPath

func (c *Command) CommandPath() string

CommandPath returns the full command path excluding the root command name. For example, if the command tree is "tfctl" -> "run" -> "start", this returns "run start".

func (*Command) Run

func (c *Command) Run(args []string, inv *Invocation) int

Run runs the given command.

func (*Command) SetIO

func (c *Command) SetIO(io iostreams.IOStreams)

SetIO sets the commands IO for input and output.

func (*Command) Validate

func (c *Command) Validate() error

Validate validates the command and all of its children.

type CompatibleCommand

type CompatibleCommand struct {
	// contains filtered or unexported fields
}

CompatibleCommand is a compatibility layer for interopability with the `cli` package.

func (*CompatibleCommand) AutocompleteArgs

func (cc *CompatibleCommand) AutocompleteArgs() complete.Predictor

AutocompleteArgs implements cli.CommandAutocomplete.

func (*CompatibleCommand) AutocompleteFlags

func (cc *CompatibleCommand) AutocompleteFlags() complete.Flags

AutocompleteFlags implements cli.CommandAutocomplete.

func (*CompatibleCommand) Help

func (cc *CompatibleCommand) Help() string

Help implements cli.Command.

func (*CompatibleCommand) HelpTemplate

func (cc *CompatibleCommand) HelpTemplate() string

HelpTemplate implements cli.CommandHelpTemplate.

func (*CompatibleCommand) Run

func (cc *CompatibleCommand) Run(args []string) int

Run implements cli.Command.

func (*CompatibleCommand) Synopsis

func (cc *CompatibleCommand) Synopsis() string

Synopsis implements cli.Command.

type DocNavItem

type DocNavItem struct {
	Title  string        `json:"title"`
	Href   string        `json:"href,omitempty"`
	Path   string        `json:"path,omitempty"`
	Routes []*DocNavItem `json:"routes,omitempty"`
}

DocNavItem is a single item in the navigation JSON.

type DocSection

type DocSection struct {
	// The title of the section.
	Title string

	// Section documentation. No additional formatting will be applied other
	// than indenting.
	Documentation string
}

DocSection allows adding additional documentation sections.

type Example

type Example struct {
	// Preamble is plaintext displayed before the command. Must be set, start
	// with a captital letter, and end with a colon.
	Preamble string

	// Command is the command example and any output it may contain
	Command string
}

Example is an example of how to use a given command.

type ExitCodeError

type ExitCodeError struct {
	Err  error
	Code int
}

ExitCodeError is an error that includes an exit code. If returned by a command run, the command will exit using the specified exit code.

func (*ExitCodeError) Error

func (e *ExitCodeError) Error() string

func (*ExitCodeError) Unwrap

func (e *ExitCodeError) Unwrap() error

type Flag

type Flag struct {
	// Name is the name of the flag. The name must be lower case.
	Name string

	// Shorthand is an optional shorthand for the flag. Name must still be set
	// and shorthand can only be a single, lowercase character.
	Shorthand string

	// Description is the description of the flag.
	Description string

	// DisplayValue is an optional string that will be used when displaying
	// help for using the flag. If set, the displayed value will be
	// --Name=DISPLAY_NAME, otherwise it will just be --Name.
	//
	// As an example, a Flag with the name "project" and display value of "ID",
	// would be displayed as "--project=ID".
	//
	// DisplayValue must be upper case.
	DisplayValue string

	// Value is the value that will be set by the flag. The value should be set
	// using flagvalue package.
	//
	// Examples are:
	//
	//   flagvalue.Simple("", &destination)
	//   flagvalue.Enum[string]([]string{"ONE", "TWO"}, "", &myEnum)
	Value flagvalue.Value

	// IsBooleanFlag indicates that the flag is a boolean flag.
	IsBooleanFlag bool

	// InvertBooleanNoValue treats the boolean flag as being specified to equal
	// the value false. This should be set if the flag indicates the disabling
	// of a value (e.g. --no-replication).
	InvertBooleanNoValue bool

	// Repeatable marks whether the positional argument can be repeated.
	Repeatable bool

	// Required marks whether the flag is required.
	Required bool

	// Hidden hides the flag.
	Hidden bool

	// Autocomplete is the predictor for this flag.
	Autocomplete complete.Predictor
	// contains filtered or unexported fields
}

Flag instantiates a flag. An example flag is:

Flag{
  Name: "project",
  Shorthand: "p",
  DisplayValue: "ID",
  Description: "project sets the project ID to target.",
  Value: flagvalue.Simple("", &projectID),
  Required: true,
}

type Flags

type Flags struct {
	// Local is the set of flags for this command.
	Local []*Flag

	// Persistent is the set of flags that exist for this command and all
	// its children.
	Persistent []*Flag
}

Flags is the set of flags for a command. It includes both local flags (specific to the command) and persistent flags (inherited by child commands).

type GlobalFlags

type GlobalFlags struct {

	// Version indicates the user has requested the version of the CLI
	Version bool

	// Quiet indicates the user has requested minimal output
	Quiet bool
	// contains filtered or unexported fields
}

GlobalFlags contains the global flags.

type Invocation

type Invocation struct {
	// IO is used to interact directly with IO or the terminal.
	IO iostreams.IOStreams

	// Output is used to print structured output.
	Output *format.Outputter

	// ShutdownCtx is a context that is canceled if the user requests the
	// command to be shutdown. If a command can block for an extended amount of
	// time, the context should be used to exit early.
	ShutdownCtx context.Context

	Profile *profile.Profile
	// contains filtered or unexported fields
}

Invocation passes global objects for constructing and invoking a command.

func (*Invocation) GetGlobalFlags

func (i *Invocation) GetGlobalFlags() GlobalFlags

GetGlobalFlags returns the global flags. It panics if the flags have not been parsed yet, which should only be the case if they are accessed outside of a run command.

func (*Invocation) IsDryRun

func (i *Invocation) IsDryRun() bool

IsDryRun returns true when commands should avoid making mutating changes.

func (*Invocation) NewAPIClient

func (i *Invocation) NewAPIClient() (*client.Client, error)

NewAPIClient returns a new API Client configured using the invocation Profile. When debug output is enabled and a non-nil logger is provided, the client's HTTP transport is wrapped to log requests and responses.

func (*Invocation) ParseFlags

func (i *Invocation) ParseFlags(c *Command, args []string) ([]string, error)

ParseFlags can be used to parse the flags for a given command before it is run. This can be helpful in very specific cases such as accessing flags during autocompletion. The return args are the non-flag arguments.

func (*Invocation) ResolveLogLevel

func (i *Invocation) ResolveLogLevel() hclog.Level

ResolveLogLevel returns the resolved verbosity level, with the --debug flag taking precedence over the profile setting.

type LinkHandler

type LinkHandler func(path string) string

LinkHandler is a function that can be used to modify the links in the generated markdown. The path string is the unmodified path to the file.

type PositionalArgument

type PositionalArgument struct {
	// Name is the name of the positional argument
	Name string

	// Preamble is plaintext displayed before the command
	Documentation string

	// Optional marks the argument as optional. If set, the argument must be the
	// last argument or all positional arguments following this must be optional
	// as well.
	Optional bool

	// Repeatable marks whether the positional argument can be repeated. Only
	// the last argument is repeatable.
	Repeatable bool
}

PositionalArgument documents a positional argument.

type PositionalArguments

type PositionalArguments struct {
	// Preamble allows injecting documentation before individual positional
	// arguments. It is optional.
	Preamble string

	// Args in an inorder list of arguments.
	Args []PositionalArgument

	// Validate if set is invoked to validate the command has received an
	// expected set of arguments. If not set, it will be defaulted based on the
	// passed Args. If no args are set, NoArgs will be enforced. If all
	// arguments are not repeated, ExactArgs will be used, otherwise,
	// MinimumNArgs will be set. To bypass argument validation, set this to
	// ArbitraryArgs.
	Validate ValidateArgsFunc

	// Autocomplete allows configuring autocompletion of arguments.
	Autocomplete complete.Predictor
}

PositionalArguments documents a positional argument in a command.

type ValidateArgsFunc

type ValidateArgsFunc func(c *Command, args []string) error

ValidateArgsFunc is a function used to validate a command has received valid arguments.

func ExactArgs

func ExactArgs(n int) ValidateArgsFunc

ExactArgs returns an error if there are not exactly N args.

func MaximumNArgs

func MaximumNArgs(n int) ValidateArgsFunc

MaximumNArgs returns an error if there are more than N (inclusive) args.

func MinimumNArgs

func MinimumNArgs(n int) ValidateArgsFunc

MinimumNArgs returns an error if there is not at least N (inclusive) args.

func RangeArgs

func RangeArgs(minimum int, maximum int) ValidateArgsFunc

RangeArgs returns an error if the number of args is not within the expected range.

Jump to

Keyboard shortcuts

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