cobra

package module
v0.0.6 Latest Latest
Warning

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

Go to latest
Published: Nov 9, 2020 License: Apache-2.0 Imports: 11 Imported by: 0

README

cobra

GoDoc

A simple "replacement" for spf13/cobra, and it just works!

Example

package main

import (
	"fmt"

	"github.com/robinWongM/cobra"
)

func main() {
	rootCmd := &cobra.Command{Use: "root", Run: func(_ *cobra.Command, _ []string) {}}

	helloCmd := &cobra.Command{
		Use: "hello",
		Run: func(_ *cobra.Command, args []string) {
			name := "World"
			if len(args) >= 1 {
				name = args[0]
			}
			fmt.Printf("Hello, %v!\n", name)
		},
	}

	rootCmd.AddCommand(helloCmd)

	rootCmd.Execute()
}

Acknowledgements

This repository contains (lots of) code from spf13/cobra, which is licensed under Apache License, Version 2.0.

Documentation

Index

Constants

View Source
const (
	BashCompFilenameExt     = "cobra_annotation_bash_completion_filename_extensions"
	BashCompCustom          = "cobra_annotation_bash_completion_custom"
	BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
	BashCompSubdirsInDir    = "cobra_annotation_bash_completion_subdirs_in_dir"
)

Annotations for Bash completion.

Variables

This section is empty.

Functions

func Eq

func Eq(a interface{}, b interface{}) bool

Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.

func Gt

func Gt(a interface{}, b interface{}) bool

Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans, Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as ints and then compared.

Types

type Command

type Command struct {
	// Use is the one-line usage message.
	// Recommended syntax is as follow:
	//   [ ] identifies an optional argument. Arguments that are not enclosed in brackets are required.
	//   ... indicates that you can specify multiple values for the previous argument.
	//   |   indicates mutually exclusive information. You can use the argument to the left of the separator or the
	//       argument to the right of the separator. You cannot use both arguments in a single use of the command.
	//   { } delimits a set of mutually exclusive arguments when one of the arguments is required. If the arguments are
	//       optional, they are enclosed in brackets ([ ]).
	// Example: add [-F file | -D dir]... [-f format] profile
	Use string

	// Short is the short description shown in the 'help' output.
	Short string

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

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

	// Hidden defines, if this command is hidden and should NOT show up in the list of available commands.
	Hidden bool

	// DisableAutoGenTag defines, if gen tag ("Auto generated by spf13/cobra...")
	// will be printed by generating docs for this command.
	DisableAutoGenTag bool

	// ValidArgs is list of all valid non-flag arguments that are accepted in bash completions
	ValidArgs []string
	// ValidArgsFunction is an optional function that provides valid non-flag arguments for bash completion.
	// It is a dynamic version of using ValidArgs.
	// Only one of ValidArgs and ValidArgsFunction can be used for a command.
	ValidArgsFunction func(cmd *Command, args []string, toComplete string) ([]string, ShellCompDirective)

	// Run: Typically the actual work function. Most commands will only implement this.
	Run func(cmd *Command, args []string)
	// RunE: Run but returns an error.
	RunE func(cmd *Command, args []string) error

	DisableFlagParsing bool

	// SilenceUsage is an option to silence usage when an error occurs.
	// We didn't, however, implement it in this simplified version of cobra.
	// Just for compatibility with hugo.
	SilenceUsage bool
	// contains filtered or unexported fields
}

func (*Command) AddCommand

func (c *Command) AddCommand(childCmd ...*Command)

AddCommand adds one or more commands to this parent command.

func (*Command) CommandPath

func (c *Command) CommandPath() string

CommandPath returns the full path to this command.

func (*Command) Commands

func (c *Command) Commands() []*Command

Commands returns a sorted slice of child commands.

func (*Command) ErrOrStderr

func (c *Command) ErrOrStderr() io.Writer

ErrOrStderr returns output to stderr

func (*Command) Execute

func (c *Command) Execute() error

Execute uses the args (os.Args[1:] by default) and run through the command tree finding appropriate matches for commands and then corresponding flags.

func (*Command) ExecuteC

func (c *Command) ExecuteC() (cmd *Command, err error)

ExecuteC executes the command.

func (*Command) Find

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

Find the target command given the args and command tree Meant to be run on the highest node. Only searches down.

func (*Command) Flags

func (c *Command) Flags() *flag.FlagSet

Flags returns the complete FlagSet that applies to this command (local and persistent declared here and by all parents).

func (*Command) GenBashCompletionFile

func (c *Command) GenBashCompletionFile(filename string) error

GenBashCompletionFile generates bash completion file.

func (*Command) HasParent

func (c *Command) HasParent() bool

HasParent determines if the command is a child command.

func (*Command) HasSubCommands

func (c *Command) HasSubCommands() bool

HasSubCommands determines if the command has children commands.

func (*Command) Help

func (c *Command) Help() error

Help puts out the help for the command. Used when a user calls help [command]. Can be defined by user by overriding HelpFunc.

func (*Command) HelpFunc

func (c *Command) HelpFunc() func(*Command, []string)

HelpFunc returns either the function set by SetHelpFunc for this command or a parent, or it returns a function with default help behavior.

func (*Command) HelpTemplate

func (c *Command) HelpTemplate() string

HelpTemplate return help template for the command.

func (*Command) InOrStdin

func (c *Command) InOrStdin() io.Reader

InOrStdin returns input to stdin

func (*Command) InitDefaultHelpCmd

func (c *Command) InitDefaultHelpCmd()

InitDefaultHelpCmd adds default help command to c. It is called automatically by executing the c or by calling help and usage. If c already has help command or c has no subcommands, it will do nothing.

func (*Command) InitDefaultHelpFlag

func (c *Command) InitDefaultHelpFlag()

InitDefaultHelpFlag adds default help flag to c. It is called automatically by executing the c or by calling help and usage. If c already has help flag, it will do nothing.

func (*Command) Name

func (c *Command) Name() string

Name returns the command's name: the first word in the use line.

func (*Command) OutOrStderr

func (c *Command) OutOrStderr() io.Writer

OutOrStderr returns output to stderr

func (*Command) OutOrStdout

func (c *Command) OutOrStdout() io.Writer

OutOrStdout returns output to stdout.

func (*Command) Parent

func (c *Command) Parent() *Command

Parent returns a commands parent command.

func (*Command) ParseFlags

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

ParseFlags parses persistent flag tree and local flags.

func (*Command) PersistentFlags

func (c *Command) PersistentFlags() *flag.FlagSet

PersistentFlags returns the persistent FlagSet specifically set in the current command.

func (*Command) Print

func (c *Command) Print(i ...interface{})

Print is a convenience method to Print to the defined output, fallback to Stderr if not set.

func (*Command) PrintErr

func (c *Command) PrintErr(i ...interface{})

PrintErr is a convenience method to Print to the defined Err output, fallback to Stderr if not set.

func (*Command) PrintErrf

func (c *Command) PrintErrf(format string, i ...interface{})

PrintErrf is a convenience method to Printf to the defined Err output, fallback to Stderr if not set.

func (*Command) PrintErrln

func (c *Command) PrintErrln(i ...interface{})

PrintErrln is a convenience method to Println to the defined Err output, fallback to Stderr if not set.

func (*Command) Printf

func (c *Command) Printf(format string, i ...interface{})

Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.

func (*Command) Println

func (c *Command) Println(i ...interface{})

Println is a convenience method to Println to the defined output, fallback to Stderr if not set.

func (*Command) Root

func (c *Command) Root() *Command

Root finds root command.

func (*Command) Runnable

func (c *Command) Runnable() bool

Runnable determines if the command is itself runnable.

func (*Command) SetArgs

func (c *Command) SetArgs(args []string)

func (*Command) SetErr

func (c *Command) SetErr(newErr io.Writer)

func (*Command) SetGlobalNormalizationFunc

func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string) flag.NormalizedName)

SetGlobalNormalizationFunc sets a normalization function to all flag sets and also to child commands. The user should not have a cyclic dependency on commands.

func (*Command) SetOut

func (c *Command) SetOut(newOut io.Writer)

func (*Command) Usage

func (c *Command) Usage() error

Usage puts out the usage for the command. Used when a user provides invalid input. Can be defined by user by overriding UsageFunc.

func (*Command) UsageFunc

func (c *Command) UsageFunc() (f func(*Command) error)

UsageFunc returns either the function set by SetUsageFunc for this command or a parent, or it returns a default usage function.

func (*Command) UsageString

func (c *Command) UsageString() string

UsageString returns usage string.

func (*Command) UsageTemplate

func (c *Command) UsageTemplate() string

UsageTemplate returns usage template for the command.

func (*Command) VisitParents

func (c *Command) VisitParents(fn func(*Command))

VisitParents visits all parents of the command and invokes fn on each parent.

type FParseErrWhitelist

type FParseErrWhitelist flag.ParseErrorsWhitelist

FParseErrWhitelist configures Flag parse errors to be ignored

type PositionalArgs

type PositionalArgs func(cmd *Command, args []string) error

type ShellCompDirective

type ShellCompDirective int

ShellCompDirective is a bit map representing the different behaviors the shell can be instructed to have once completions have been provided.

const (
	// ShellCompDirectiveError indicates an error occurred and completions should be ignored.
	ShellCompDirectiveError ShellCompDirective = 1 << iota

	// ShellCompDirectiveNoSpace indicates that the shell should not add a space
	// after the completion even if there is a single completion provided.
	ShellCompDirectiveNoSpace

	// ShellCompDirectiveNoFileComp indicates that the shell should not provide
	// file completion even when no completion is provided.
	// This currently does not work for zsh or bash < 4
	ShellCompDirectiveNoFileComp

	// ShellCompDirectiveFilterFileExt indicates that the provided completions
	// should be used as file extension filters.
	// For flags, using Command.MarkFlagFilename() and Command.MarkPersistentFlagFilename()
	// is a shortcut to using this directive explicitly.  The BashCompFilenameExt
	// annotation can also be used to obtain the same behavior for flags.
	ShellCompDirectiveFilterFileExt

	// ShellCompDirectiveFilterDirs indicates that only directory names should
	// be provided in file completion.  To request directory names within another
	// directory, the returned completions should specify the directory within
	// which to search.  The BashCompSubdirsInDir annotation can be used to
	// obtain the same behavior but only for flags.
	ShellCompDirectiveFilterDirs

	// ShellCompDirectiveDefault indicates to let the shell perform its default
	// behavior after completions have been provided.
	// This one must be last to avoid messing up the iota count.
	ShellCompDirectiveDefault ShellCompDirective = 0
)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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