core

package
v2.30.0 Latest Latest
Warning

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

Go to latest
Published: Apr 11, 2024 License: Apache-2.0 Imports: 54 Imported by: 0

Documentation

Overview

shell is disabled on freebsd as current version of github.com/pkg/term@v1.1.0 is not compiling

Index

Constants

View Source
const (
	// PrinterTypeJSON defines a JSON formatter.
	PrinterTypeJSON = PrinterType("json")

	// PrinterTypeYAML defines a YAML formatter.
	PrinterTypeYAML = PrinterType("yaml")

	// PrinterTypeHuman defines a human readable formatted formatter.
	PrinterTypeHuman = PrinterType("human")

	// PrinterTypeWide defines a human-readable formatted formatter without shrinking.
	PrinterTypeWide = PrinterType("wide")

	// PrinterTypeTemplate defines a go template to use to format output.
	PrinterTypeTemplate = PrinterType("template")

	// Option to enable pretty output on json printer.
	PrinterOptJSONPretty = "pretty"
)

Variables

View Source
var (
	// UpdateGoldens will update all the golden files of a given test
	UpdateGoldens = flag.Bool("goldens", os.Getenv("CLI_UPDATE_GOLDENS") == "true", "Record goldens")

	// UpdateCassettes will update all cassettes of a given test
	UpdateCassettes = flag.Bool("cassettes", os.Getenv("CLI_UPDATE_CASSETTES") == "true", "Record Cassettes")

	// Debug set the log level to LogLevelDebug
	Debug = flag.Bool("debug", os.Getenv("SCW_DEBUG") == "true", "Enable Debug Mode")
)

Test flags You can create a binary of each test using "go test -c -o myBinary"

View Source
var AllLocalities = "all"
View Source
var DefaultRetryInterval *time.Duration

DefaultRetryInterval is used across all wait functions in the CLI In particular it is very handy to define this RetryInterval at 0 second while running cassette in testing because they will be executed without waiting.

Functions

func ApplyDefaultValues

func ApplyDefaultValues(ctx context.Context, argSpecs ArgSpecs, rawArgs args.RawArgs) args.RawArgs

ApplyDefaultValues will hydrate args with default values.

func ArgIsOption added in v2.28.0

func ArgIsOption(arg string) bool

ArgIsOption returns if an argument is an option

func AutoCompleteArgValue

func AutoCompleteArgValue(ctx context.Context, cmd *Command, argSpec *ArgSpec, argValuePrefix string, completedArgs map[string]string) []string

AutoCompleteArgValue returns suggestions for a (argument name, argument value prefix) pair. Priority is given to the AutoCompleteFunc from the ArgSpec, if it is set. Otherwise, we use EnumValues from the ArgSpec.

func AutocompleteGetArg added in v2.8.0

func AutocompleteGetArg(ctx context.Context, cmd *Command, argSpec *ArgSpec, completedArgs map[string]string) []string

AutocompleteGetArg tries to complete an argument by using the list verb if it exists for the same resource It will search for the same field in the response of the list Field name will be stripped of the resource name (ex: cluster-id -> id)

func Bootstrap

func Bootstrap(config *BootstrapConfig) (exitCode int, result interface{}, err error)

Bootstrap is the main entry point. It is directly called from main. BootstrapConfig.Args is usually os.Args BootstrapConfig.Commands is a list of command available in CLI.

func BuildUsageArgs added in v2.28.0

func BuildUsageArgs(ctx context.Context, cmd *Command, deprecated bool) string

BuildUsageArgs builds usage args string. If deprecated is true, true only deprecated argSpecs will be considered. This string will be used by cobra usage template.

func CreateAndCloseFile added in v2.28.0

func CreateAndCloseFile(path string) error

CreateAndCloseFile creates a file and closes it. It returns true on succeed, false on failure.

func ExecCmd

func ExecCmd(ctx context.Context, cmd *exec.Cmd) (exitCode int, err error)

func ExtractAliases added in v2.12.0

func ExtractAliases(ctx context.Context) *alias.Config

func ExtractBetaMode added in v2.8.0

func ExtractBetaMode(ctx context.Context) bool

func ExtractBinaryName

func ExtractBinaryName(ctx context.Context) string

func ExtractCacheDir

func ExtractCacheDir(ctx context.Context) string

func ExtractCliConfig added in v2.12.0

func ExtractCliConfig(ctx context.Context) *cliConfig.Config

func ExtractCliConfigPath added in v2.12.0

func ExtractCliConfigPath(ctx context.Context) string

func ExtractClient

func ExtractClient(ctx context.Context) *scw.Client

func ExtractConfigPath

func ExtractConfigPath(ctx context.Context) string

func ExtractConfigPathFlag

func ExtractConfigPathFlag(ctx context.Context) string

func ExtractEnv

func ExtractEnv(ctx context.Context, envKey string) string

func ExtractHTTPClient

func ExtractHTTPClient(ctx context.Context) *http.Client

func ExtractProfileFlag

func ExtractProfileFlag(ctx context.Context) string

func ExtractProfileName

func ExtractProfileName(ctx context.Context) string

func ExtractStdin

func ExtractStdin(ctx context.Context) io.Reader

func ExtractUserHomeDir

func ExtractUserHomeDir(ctx context.Context) string

func GetDocGenContext

func GetDocGenContext() context.Context

GetDocGenContext returns a minimal context that can be used by scw-doc-gen

func GetLatestVersionUpdateFilePath added in v2.28.0

func GetLatestVersionUpdateFilePath(cacheDir string) string

func GetOrganizationIDFromContext

func GetOrganizationIDFromContext(ctx context.Context) string

func GetProjectIDFromContext

func GetProjectIDFromContext(ctx context.Context) string

func GetRandomName

func GetRandomName(prefix string) string

GetRandomName returns a random name prefixed for the CLI.

func GetValuesForFieldByName added in v2.30.0

func GetValuesForFieldByName(value reflect.Value, parts []string) (values []reflect.Value, err error)

GetValuesForFieldByName recursively search for fields in a cmdArgs' value and returns its values if they exist. The search is based on the name of the field.

func GoldenReplacePatterns added in v2.28.0

func GoldenReplacePatterns(golden string, replacements ...GoldenReplacement) (string, error)

GoldenReplacePatterns replace the list of patterns with their given replacement

func InjectConfig added in v2.28.0

func InjectConfig(ctx context.Context, config *scw.Config)

injectSDKConfig add config to a Meta context

func InjectMeta added in v2.28.0

func InjectMeta(ctx context.Context, meta *Meta) context.Context

InjectMeta creates a new ctx based on the given one with injected meta and returns it.

func IsNotFoundError added in v2.14.0

func IsNotFoundError(err error) bool

func OptionToArgSpecName added in v2.28.0

func OptionToArgSpecName(option string) string

OptionToArgSpecName convert option to arg spec name from additional-volumes.0=hello to additional-volumes.{index} also with multiple indexes pools.0.kubelet-args. to pools.{index}.kubelet-args.{key}

func ReloadClient

func ReloadClient(ctx context.Context) error

func RunShell added in v2.6.0

func RunShell(ctx context.Context, printer *Printer, meta *Meta, rootCmd *cobra.Command, args []string)

RunShell will run an interactive shell that runs cobra commands

func Test

func Test(config *TestConfig) func(t *testing.T)

Run a CLI integration test. See TestConfig for configuration option

func ValidateNoConflict added in v2.28.0

func ValidateNoConflict(cmd *Command, rawArgs args.RawArgs) error

Types

type AfterCommandCheckFunc added in v2.15.0

type AfterCommandCheckFunc func(ctx context.Context)

type AfterFunc

type AfterFunc func(ctx *AfterFuncCtx) error

func AfterFuncCombine

func AfterFuncCombine(afterFuncs ...AfterFunc) AfterFunc

AfterFuncCombine combines multiple after functions into one.

func AfterFuncWhenUpdatingCassette added in v2.27.0

func AfterFuncWhenUpdatingCassette(afterFunc AfterFunc) AfterFunc

func ExecAfterCmd

func ExecAfterCmd(cmd string) AfterFunc

ExecAfterCmd executes the given before command.

type AfterFuncCtx

type AfterFuncCtx struct {
	T           *testing.T
	Client      *scw.Client
	ExecuteCmd  func(args []string) interface{}
	Meta        testMetadata
	CmdResult   interface{}
	OverrideEnv map[string]string
	Logger      *Logger
}

type ArgSpec

type ArgSpec struct {
	// Name of the argument.
	Name string

	// Short description.
	Short string

	// Required defines whether the argument is required.
	Required bool

	// Default is the argument default value.
	Default DefaultFunc

	// EnumValues contains all possible values of an enum.
	EnumValues []string

	// AutoCompleteFunc is used to autocomplete possible values for a given argument.
	AutoCompleteFunc AutoCompleteArgFunc

	// ValidateFunc validates an argument.
	ValidateFunc ArgSpecValidateFunc

	// Positional defines whether the argument is a positional argument. NB: a positional argument is required.
	Positional bool

	// Only one argument of the same OneOfGroup could be specified
	OneOfGroup string

	// Deprecated is used to flag an argument as deprecated.
	// Use the short field to indicate migration tips for users.
	Deprecated bool

	// CanLoadFile allow to use @ prefix to load a file as content
	CanLoadFile bool
}

func OrganizationArgSpec

func OrganizationArgSpec() *ArgSpec

func OrganizationIDArgSpec

func OrganizationIDArgSpec() *ArgSpec

func ProjectArgSpec

func ProjectArgSpec() *ArgSpec

func ProjectIDArgSpec

func ProjectIDArgSpec() *ArgSpec

func RegionArgSpec

func RegionArgSpec(regions ...scw.Region) *ArgSpec

func WaitTimeoutArgSpec added in v2.15.0

func WaitTimeoutArgSpec(defaultTimeout time.Duration) *ArgSpec

func ZoneArgSpec

func ZoneArgSpec(zones ...scw.Zone) *ArgSpec

func (*ArgSpec) ConflictWith

func (a *ArgSpec) ConflictWith(b *ArgSpec) bool

func (*ArgSpec) IsPartOfMapOrSlice

func (a *ArgSpec) IsPartOfMapOrSlice() bool

func (*ArgSpec) Prefix

func (a *ArgSpec) Prefix() string

type ArgSpecValidateFunc

type ArgSpecValidateFunc func(argSpec *ArgSpec, value interface{}) error

ArgSpecValidateFunc validates one argument of a command.

func DefaultArgSpecValidateFunc

func DefaultArgSpecValidateFunc() ArgSpecValidateFunc

DefaultArgSpecValidateFunc validates a value passed for an ArgSpec Uses ArgSpec.EnumValues

func ValidateAccessKey added in v2.11.1

func ValidateAccessKey() ArgSpecValidateFunc

ValidateAccessKey validates an access key ID.

func ValidateOrganizationID

func ValidateOrganizationID() ArgSpecValidateFunc

ValidateOrganizationID validates a non-required organization ID. By default, for most command, the organization ID is not required. In that case, we allow the empty-string value "".

func ValidateProjectID

func ValidateProjectID() ArgSpecValidateFunc

ValidateProjectID validates a non-required project ID. By default, for most command, the project ID is not required. In that case, we allow the empty-string value "".

func ValidateSecretKey

func ValidateSecretKey() ArgSpecValidateFunc

ValidateSecretKey validates a secret key ID.

type ArgSpecs

type ArgSpecs []*ArgSpec

func (*ArgSpecs) AddBefore

func (s *ArgSpecs) AddBefore(name string, argSpec *ArgSpec)

func (*ArgSpecs) DeleteByName

func (s *ArgSpecs) DeleteByName(name string)

func (ArgSpecs) GetByName

func (s ArgSpecs) GetByName(name string) *ArgSpec

func (ArgSpecs) GetDeprecated

func (s ArgSpecs) GetDeprecated(deprecated bool) ArgSpecs

GetDeprecated gets all fields filtered by the deprecation state.

func (ArgSpecs) GetPositionalArg

func (s ArgSpecs) GetPositionalArg() *ArgSpec

type AutoCompleteArgFunc

type AutoCompleteArgFunc func(ctx context.Context, prefix string, request any) AutocompleteSuggestions

AutoCompleteArgFunc is the function called to complete arguments values. It is retrieved from core.ArgSpec.AutoCompleteFunc.

func AutocompleteProfileName

func AutocompleteProfileName() AutoCompleteArgFunc

type AutoCompleteNode

type AutoCompleteNode struct {
	Children map[string]*AutoCompleteNode
	Command  *Command
	ArgSpec  *ArgSpec
	Type     AutoCompleteNodeType

	// Name of the current node. Useful for debugging.
	Name string
}

AutoCompleteNode is a node in the AutoComplete Tree. An AutoCompleteNode can either represent a command, a subcommand, or a command argument.

func BuildAutoCompleteTree

func BuildAutoCompleteTree(ctx context.Context, commands *Commands) *AutoCompleteNode

BuildAutoCompleteTree builds the autocomplete tree from the commands, subcommands and arguments

func NewAutoCompleteArgNode

func NewAutoCompleteArgNode(cmd *Command, argSpec *ArgSpec) *AutoCompleteNode

NewAutoCompleteArgNode creates a new node corresponding to a command argument. These nodes are leaf nodes.

func NewAutoCompleteCommandNode

func NewAutoCompleteCommandNode(flags []FlagSpec) *AutoCompleteNode

NewAutoCompleteCommandNode creates a new node corresponding to a command or subcommand. These nodes are not necessarily leaf nodes.

func NewAutoCompleteFlagNode

func NewAutoCompleteFlagNode(parent *AutoCompleteNode, flagSpec *FlagSpec) *AutoCompleteNode

NewAutoCompleteFlagNode returns a node representing a Flag. It creates the children node with possible values if they exist. It sets parent.children as children of the lowest nodes: the lowest node is the flag if it has no possible value ; or the lowest nodes are the possible values if the exist.

func (*AutoCompleteNode) GetChildMatch

func (node *AutoCompleteNode) GetChildMatch(name string) (*AutoCompleteNode, bool)

GetChildMatch returns a child for a node if the child exists for this node. 3 types of children are supported : - command: command - singular argument name: argument= - plural argument name + alphanumeric: arguments.key1=

func (*AutoCompleteNode) GetChildOrCreate

func (node *AutoCompleteNode) GetChildOrCreate(name string, aliases []string, flags []FlagSpec) *AutoCompleteNode

GetChildOrCreate search a child node by name, and either returns it if found or create new children with the given name and aliases, and returns it.

type AutoCompleteNodeType

type AutoCompleteNodeType uint
const (
	AutoCompleteNodeTypeCommand AutoCompleteNodeType = iota
	AutoCompleteNodeTypeArgument
	AutoCompleteNodeTypeFlag
	AutoCompleteNodeTypeFlagValueConst
	AutoCompleteNodeTypeFlagValueVariable
)

type AutocompleteResponse

type AutocompleteResponse struct {
	Suggestions AutocompleteSuggestions
}

AutocompleteResponse contains the autocomplete suggestions

func AutoComplete

func AutoComplete(ctx context.Context, leftWords []string, wordToComplete string, rightWords []string) *AutocompleteResponse

AutoComplete process a command line and returns autocompletion suggestions.

command <flag name>=<flag value beginning><tab> gives no suggestion for now eg: scw test flower create name=p -o=jso

type AutocompleteSuggestions

type AutocompleteSuggestions []string

AutocompleteSuggestions is a list of words to be set to the shell as autocomplete suggestions.

type BeforeFunc

type BeforeFunc func(ctx *BeforeFuncCtx) error

func BeforeFuncCombine

func BeforeFuncCombine(beforeFuncs ...BeforeFunc) BeforeFunc

BeforeFuncCombine combines multiple before functions into one.

func BeforeFuncOsExec

func BeforeFuncOsExec(cmd string, args ...string) BeforeFunc

func BeforeFuncStoreInMeta

func BeforeFuncStoreInMeta(key string, value interface{}) BeforeFunc

func BeforeFuncWhenUpdatingCassette

func BeforeFuncWhenUpdatingCassette(beforeFunc BeforeFunc) BeforeFunc

func ExecBeforeCmd

func ExecBeforeCmd(cmd string) BeforeFunc

ExecBeforeCmd executes the given before command.

func ExecBeforeCmdArgs added in v2.12.0

func ExecBeforeCmdArgs(args []string) BeforeFunc

ExecBeforeCmdArgs executes the given command before command.

func ExecStoreBeforeCmd

func ExecStoreBeforeCmd(metaKey, cmd string) BeforeFunc

ExecStoreBeforeCmd executes the given before command and register the result in the context Meta at metaKey.

type BeforeFuncCtx

type BeforeFuncCtx struct {
	T           *testing.T
	Client      *scw.Client
	ExecuteCmd  func(args []string) interface{}
	Meta        testMetadata
	OverrideEnv map[string]string
	Logger      *Logger
}

type BootstrapConfig

type BootstrapConfig struct {
	// Args to use for the command. Usually os.Args
	Args []string

	// A list of all available commands
	Commands *Commands

	// BuildInfo contains information about cli build
	BuildInfo *BuildInfo

	// Stdout stream to use. Usually os.Stdout
	Stdout io.Writer

	// Stderr stream to use. Usually os.Stderr
	Stderr io.Writer

	// Stdin stream to use. Usually os.Stdin
	Stdin io.Reader

	// If provided this client will be passed to all commands.
	// If not a client will be automatically created by the CLI using Config, Env and flags see createClient().
	Client *scw.Client

	// DisableTelemetry, if set to true this will disable telemetry report no matter what the config send_telemetry is set to.
	// This is useful when running test to avoid sending meaningless telemetries.
	DisableTelemetry bool

	// DisableAliases, if set to true this will disable aliases expanding
	DisableAliases bool

	// OverrideEnv overrides environment variables returned by core.ExtractEnv function.
	// This is useful for tests as it allows overriding env without relying on global state.
	OverrideEnv map[string]string

	// OverrideExec allow to override exec.Cmd.Run method. In order for this to work
	// your code must call le core.ExecCmd function to execute a given command.
	// If this function is not defined the exec.Cmd.Run function will be called directly.
	// This function is intended to be use for tests purposes.
	OverrideExec OverrideExecFunc

	// BaseContest is the base context that will be used across all function call from top to bottom.
	Ctx context.Context

	// Optional we use it if defined
	Logger *Logger

	// Default HTTPClient to use. If not provided it will use a basic http client with a simple retry policy
	// This client will be used to create SDK client, account call, version checking and telemetry
	HTTPClient *http.Client

	// Enable beta functionalities
	BetaMode bool

	// The current platform, should probably be platform.Default
	Platform platform.Platform
}

type BuildInfo

type BuildInfo struct {
	Version   *version.Version `json:"-"`
	BuildDate string           `json:"build_date"`
	GoVersion string           `json:"go_version"`
	GitBranch string           `json:"git_branch"`
	GitCommit string           `json:"git_commit"`
	GoArch    string           `json:"go_arch"`
	GoOS      string           `json:"go_os"`
}

func ExtractBuildInfo

func ExtractBuildInfo(ctx context.Context) *BuildInfo

func (*BuildInfo) GetUserAgent

func (b *BuildInfo) GetUserAgent() string

func (*BuildInfo) IsRelease

func (b *BuildInfo) IsRelease() bool

IsRelease returns true when the version of the CLI is an official release: - version must be non-empty (exclude tests) - version must not contain metadata (e.g. '+dev')

func (*BuildInfo) MarshalJSON

func (b *BuildInfo) MarshalJSON() ([]byte, error)

func (*BuildInfo) Tags added in v2.16.1

func (b *BuildInfo) Tags() map[string]string

type CheckFuncCtx

type CheckFuncCtx struct {
	// Exit code return by the CLI
	ExitCode int

	// Content print on stdout
	Stdout []byte

	// Content print on stderr
	Stderr []byte

	// Error returned by the command
	Err error

	// Command result
	Result interface{}

	// Meta bag
	Meta testMetadata

	// Scaleway client
	Client *scw.Client

	// OverrideEnv passed in the TestConfig
	OverrideEnv map[string]string

	Logger *Logger

	// The content logged by the command
	LogBuffer string
}

CheckFuncCtx contain the result of a command execution

type CliError

type CliError struct {

	// The original error that triggers this CLI error.
	// The Err.String() will be print in red to the user.
	Err error

	// Message allow to override the red message shown to the use.
	// By default we will use Err.String() but in same case you may want to keep Err
	// to avoid loosing detail in json output.
	Message string

	Details string
	Hint    string

	// Code allows to return a sepcific error code from the main binary.
	Code int

	// Empty tells the marshaler to not print any message for the error
	Empty bool
}

CliError is an all-in-one error structure that can be used in commands to return useful errors to the user. CliError implements JSON and human marshaler for a smooth experience.

func ArgumentConflictError

func ArgumentConflictError(arg1 string, arg2 string) *CliError

func InvalidAPIURLError added in v2.16.0

func InvalidAPIURLError(value string) *CliError

func InvalidAccessKeyError

func InvalidAccessKeyError(value string) *CliError

func InvalidOrganizationIDError

func InvalidOrganizationIDError(value string) *CliError

func InvalidProjectIDError

func InvalidProjectIDError(value string) *CliError

func InvalidRegionError added in v2.16.0

func InvalidRegionError(value string) *CliError

func InvalidSecretKeyError

func InvalidSecretKeyError(value string) *CliError

func InvalidValueForEnumError

func InvalidValueForEnumError(argSpecName string, argSpecEnumValues []string, value string) *CliError

func InvalidZoneError added in v2.16.0

func InvalidZoneError(value string) *CliError

func MissingRequiredArgumentError

func MissingRequiredArgumentError(argumentName string) *CliError

func WindowIsNotSupportedError

func WindowIsNotSupportedError() *CliError

func (*CliError) Error

func (s *CliError) Error() string

func (*CliError) MarshalHuman

func (s *CliError) MarshalHuman() (string, error)

func (*CliError) MarshalJSON

func (s *CliError) MarshalJSON() ([]byte, error)

type Command

type Command struct {

	// Namespace is the top level entry point of a command. (e.g scw instance)
	Namespace string

	// Resource is the 2nd command level. Resources are nested in a namespace. (e.g scw instance server)
	Resource string

	// Verb is the 3rd command level. Verbs are nested in a resource. (e.g scw instance server list)
	Verb string

	// Short documentation.
	Short string

	// Long documentation.
	Long string

	// AllowAnonymousClient defines whether the SDK client can run the command without be authenticated.
	AllowAnonymousClient bool

	// DisableTelemetry disable telemetry for the command.
	DisableTelemetry bool

	// DisableAfterChecks disable checks that run after the command to avoid superfluous message
	DisableAfterChecks bool

	// Hidden hides the command form usage and auto-complete.
	Hidden bool

	// ArgsType defines the type of argument for this command.
	ArgsType reflect.Type

	// ArgSpecs defines specifications for arguments.
	ArgSpecs ArgSpecs

	// AcceptMultiplePositionalArgs defines whether the command can accept multiple positional arguments.
	// If enabled, positional argument is expected to be a list.
	AcceptMultiplePositionalArgs bool

	// View defines the View for this command.
	// It is used to create the different options for the different Marshalers.
	View *View

	// Examples defines Examples for this command.
	Examples []*Example

	// SeeAlsos presents commands related to this command.
	SeeAlsos []*SeeAlso

	// PreValidateFunc allows to manipulate args before validation
	PreValidateFunc CommandPreValidateFunc

	// ValidateFunc validates a command.
	// If nil, core.DefaultCommandValidateFunc is used by default.
	ValidateFunc CommandValidateFunc

	// Interceptor are middleware func that can intercept context and args before they are sent to Run
	// You can combine multiple CommandInterceptor using AddInterceptors method.
	Interceptor CommandInterceptor

	// Run will be called to execute a command. It will receive a context and parsed argument.
	// Non-nil values returned by this method will be printed out.
	Run CommandRunner

	// WaitFunc will be called if non-nil when the -w (--wait) flag is passed.
	WaitFunc WaitFunc

	// WebURL will be used as url to open when the --web flag is passed
	// Can contain template of values in request, ex: "url/{{ .Zone }}/{{ .ResourceID }}"
	WebURL string

	// WaitUsage override the usage for the -w (--wait) flag
	WaitUsage string

	// Aliases contains a list of aliases for a command
	Aliases []string

	// Groups contains a list of groups IDs
	Groups []string
	// contains filtered or unexported fields
}

Command represent a CLI command. From this higher level type we create Cobra command objects.

func (*Command) AddInterceptors

func (c *Command) AddInterceptors(interceptors ...CommandInterceptor)

AddInterceptors add one or multiple interceptors to a command. These new interceptors will be added after the already present interceptors (if any).

func (*Command) Copy added in v2.12.0

func (c *Command) Copy() *Command

Copy returns a copy of a command

func (*Command) GetCommandLine

func (c *Command) GetCommandLine(binaryName string) string

func (*Command) GetUsage

func (c *Command) GetUsage(binaryName string, commands *Commands) string

func (*Command) MatchAlias added in v2.28.0

func (c *Command) MatchAlias(alias alias.Alias) bool

MatchAlias returns true if the alias can be used for this command

func (*Command) Override

func (c *Command) Override(builder func(command *Command) *Command)

Override replaces or mutates the Command via a builder function.

type CommandInterceptor

type CommandInterceptor func(ctx context.Context, argsI interface{}, runner CommandRunner) (interface{}, error)

CommandInterceptor allow to intercept and manipulate a runner arguments and return value. It can for example be used to change arguments type or catch runner errors.

func CombineCommandInterceptor added in v2.28.0

func CombineCommandInterceptor(interceptors ...CommandInterceptor) CommandInterceptor

CombineCommandInterceptor will combine one or more CommandInterceptor. Resulting CommandInterceptor can be viewed as a chain composed by all interceptors passed as parameter.

type CommandPreValidateFunc

type CommandPreValidateFunc func(ctx context.Context, argsI interface{}) error

CommandPreValidateFunc allows to manipulate args before validation.

type CommandRunner

type CommandRunner func(ctx context.Context, argsI interface{}) (interface{}, error)

CommandRunner returns the command response or an error.

type CommandValidateFunc

type CommandValidateFunc func(ctx context.Context, cmd *Command, cmdArgs interface{}, rawArgs args.RawArgs) error

CommandValidateFunc validates en entire command. Used in core.cobraRun().

func DefaultCommandValidateFunc

func DefaultCommandValidateFunc() CommandValidateFunc

DefaultCommandValidateFunc is the default validation function for commands.

type Commands

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

Commands represent a list of CLI commands, with a index to allow searching.

func ExtractCommands

func ExtractCommands(ctx context.Context) *Commands

func NewCommands

func NewCommands(cmds ...*Command) *Commands

func NewCommandsMerge added in v2.8.0

func NewCommandsMerge(cmdsList ...*Commands) *Commands

func (*Commands) Add

func (c *Commands) Add(cmd *Command)

func (*Commands) AliasIsValidCommandChild added in v2.28.0

func (c *Commands) AliasIsValidCommandChild(command *Command, alias alias.Alias) bool

AliasIsValidCommandChild returns true is alias is a valid child command of given command Useful for this case: isl => instance server list valid child of "instance" invalid child of "rdb instance"

func (*Commands) Copy added in v2.12.0

func (c *Commands) Copy() *Commands

Copy return a copy of all commands

func (*Commands) Find added in v2.12.0

func (c *Commands) Find(path ...string) *Command

func (*Commands) GetAll

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

func (*Commands) GetSortedCommand

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

GetSortedCommand returns a slice of commands sorted alphabetically

func (*Commands) HasSubCommands

func (c *Commands) HasSubCommands(cmd *Command) bool

func (*Commands) Merge

func (c *Commands) Merge(cmds *Commands)

func (*Commands) MustFind

func (c *Commands) MustFind(path ...string) *Command

func (*Commands) Remove added in v2.6.0

func (c *Commands) Remove(namespace, verb string)

type Completer added in v2.6.0

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

func NewShellCompleter added in v2.6.0

func NewShellCompleter(ctx context.Context) *Completer

func (*Completer) Complete added in v2.6.0

func (c *Completer) Complete(d prompt.Document) []prompt.Suggest

Complete returns the list of suggestion based on prompt content

type DefaultFunc

type DefaultFunc func(ctx context.Context) (value string, doc string)

func DefaultValueSetter

func DefaultValueSetter(defaultValue string) DefaultFunc

func RandomValueGenerator

func RandomValueGenerator(prefix string) DefaultFunc

type Example

type Example struct {

	// Short is the title given to the example.
	Short string

	// ArgsJSON is a JSON encoded representation of the request used in the example. Only one of ArgsJSON or Raw should be provided.
	ArgsJSON string

	// Raw is a raw example. Only one of ArgsJSON or Raw should be provided.
	Raw string
}

Example represents an example for the usage of a CLI command.

func (*Example) GetCommandLine

func (e *Example) GetCommandLine(binaryName string, cmd *Command) string

type ExecFuncCtx

type ExecFuncCtx struct {
	T      *testing.T
	Meta   testMetadata
	Client *scw.Client
}

type FlagSpec

type FlagSpec struct {
	Name             string
	HasVariableValue bool
	EnumValues       []string
}

type GoldenReplacement added in v2.11.0

type GoldenReplacement struct {
	// Line will be matched using this regex
	Pattern *regexp.Regexp
	// Content that will replace the matched regex
	// This is the format for repl in (*regexp.Regexp).ReplaceAll
	// You can use $ to represent groups $1, $2...
	Replacement string

	// OptionalMatch allow the golden to not contain the given patterns
	// if false, the golden must contain the given pattern
	OptionalMatch bool
}

GoldenReplacement describe patterns to be replaced in goldens

type Logger

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

func ExtractLogger

func ExtractLogger(ctx context.Context) *Logger

func (*Logger) Debug

func (l *Logger) Debug(args ...interface{})

func (*Logger) Debugf

func (l *Logger) Debugf(format string, args ...interface{})

func (*Logger) Error

func (l *Logger) Error(args ...interface{})

func (*Logger) Errorf

func (l *Logger) Errorf(format string, args ...interface{})

func (*Logger) Info

func (l *Logger) Info(args ...interface{})

func (*Logger) Infof

func (l *Logger) Infof(format string, args ...interface{})

func (*Logger) ShouldLog

func (l *Logger) ShouldLog(level logger.LogLevel) bool

func (*Logger) Warning

func (l *Logger) Warning(args ...interface{})

func (*Logger) Warningf

func (l *Logger) Warningf(format string, args ...interface{})

type Meta added in v2.28.0

type Meta struct {
	BinaryName string

	ProfileFlag    string
	ConfigPathFlag string
	Logger         *Logger

	BuildInfo    *BuildInfo
	Client       *scw.Client
	Commands     *Commands
	OverrideEnv  map[string]string
	OverrideExec OverrideExecFunc
	CliConfig    *cliConfig.Config
	Platform     platform.Platform

	BetaMode bool
	// contains filtered or unexported fields
}

Meta store globally available variables like sdk client or global Flags.

type MultiResults

type MultiResults []interface{}

func (MultiResults) MarshalHuman

func (mr MultiResults) MarshalHuman() (string, error)

type OverrideExecFunc

type OverrideExecFunc func(cmd *exec.Cmd) (exitCode int, err error)

type OverrideExecTestFunc

type OverrideExecTestFunc func(ctx *ExecFuncCtx, cmd *exec.Cmd) (exitCode int, err error)

func OverrideExecSimple

func OverrideExecSimple(cmdStr string, exitCode int) OverrideExecTestFunc

type Printer

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

func NewPrinter

func NewPrinter(config *PrinterConfig) (*Printer, error)

NewPrinter returns an initialized formatter corresponding to a given FormatterType.

func (*Printer) Print

func (p *Printer) Print(data interface{}, opt *human.MarshalOpt) error

type PrinterConfig

type PrinterConfig struct {
	OutputFlag string
	Stdout     io.Writer
	Stderr     io.Writer
}

type PrinterType

type PrinterType string

Type defines an formatter format.

func (PrinterType) String

func (p PrinterType) String() string

type RawResult

type RawResult []byte

This type can be return by a command that need to output specific content on stdout directly. When a command return this type, default printer will not be used and bytes will be directly print on stdout.

type SeeAlso

type SeeAlso struct {
	Command string
	Short   string
}

type ShellSuggestion added in v2.6.0

type ShellSuggestion struct {
	Text string
	Arg  *ArgSpec
	Cmd  *Command
}

type SocketPassthroughTransport added in v2.14.0

type SocketPassthroughTransport struct{}

func (*SocketPassthroughTransport) RoundTrip added in v2.14.0

func (r *SocketPassthroughTransport) RoundTrip(request *http.Request) (*http.Response, error)

type SuccessResult

type SuccessResult struct {
	Message  string
	Details  string
	Resource string
	Verb     string
	Empty    bool
	// Used to pass resource to an AfterFunc on success
	TargetResource any
}

func (*SuccessResult) MarshalHuman

func (s *SuccessResult) MarshalHuman() (string, error)

func (*SuccessResult) MarshalJSON

func (s *SuccessResult) MarshalJSON() ([]byte, error)

type TestCheck

type TestCheck func(t *testing.T, ctx *CheckFuncCtx)

TestCheck is a function that perform assertion on a CheckFuncCtx

func TestCheckCombine

func TestCheckCombine(checks ...TestCheck) TestCheck

TestCheckCombine combines multiple check functions into one.

func TestCheckError

func TestCheckError(err error) TestCheck

TestCheckError asserts error

func TestCheckExitCode

func TestCheckExitCode(expectedCode int) TestCheck

TestCheckExitCode assert exitCode

func TestCheckGolden

func TestCheckGolden() TestCheck

TestCheckGolden assert stderr and stdout using golden

func TestCheckGoldenAndReplacePatterns added in v2.11.0

func TestCheckGoldenAndReplacePatterns(replacements ...GoldenReplacement) TestCheck

TestCheckGoldenAndReplacePatterns assert stderr and stdout using golden, golden are matched against given regex and edited with replacements

func TestCheckStdout

func TestCheckStdout(stdout string) TestCheck

TestCheckStdout asserts stdout using string

type TestConfig

type TestConfig struct {

	// Array of command to load (see main.go)
	Commands *Commands

	// If set to true the client will be initialize to use a e2e token.
	UseE2EClient bool

	// DefaultRegion to use with scw client (default: scw.RegionFrPar)
	DefaultRegion scw.Region

	// DefaultZone to use with scw client (default: scw.ZoneFrPar1)
	DefaultZone scw.Zone

	// BeforeFunc is a hook that will be called before test is run. You can use this function to bootstrap resources.
	BeforeFunc BeforeFunc

	// The command line you want to test
	// The arguments in this command MUST have only one space between each others to be split successfully
	// Conflict with Args
	Cmd string

	// Args represents a program arguments and should be used, when you cannot Cmd because your arguments include space characters
	// Conflict with Cmd
	Args []string

	// A list of check function that will be run on result.
	Check TestCheck

	// AfterFunc is a hook that will be called after test is run. You can use this function to teardown resources.
	AfterFunc AfterFunc

	// Run tests in parallel.
	DisableParallel bool

	// Fake build info for this test.
	BuildInfo *BuildInfo

	// If set, it will create a temporary home directory during the tests.
	// Get this folder with ExtractUserHomeDir()
	// This will also use this temporary directory as a cache directory.
	// Get this folder with ExtractCacheDir()
	TmpHomeDir bool

	// OverrideEnv contains environment variables that will be overridden during the test.
	OverrideEnv map[string]string

	// see BootstrapConfig.OverrideExec
	OverrideExec OverrideExecTestFunc

	// Custom client to use for test, if none are provided will create one automatically
	Client *scw.Client

	// Context that will be forwarded to Bootstrap
	Ctx context.Context

	// If this is specified this value will be passed to interactive.InjectMockResponseToContext ans will allow
	// to mock response a user would have enter in a prompt.
	// Warning: All prompts MUST be mocked or test will hang.
	PromptResponseMocks []string

	// Allow to mock stdin
	Stdin io.Reader

	// EnabledAliases enables aliases that are disabled in tests
	EnableAliases bool
}

TestConfig contain configuration that can be used with the Test function

type View

type View struct {
	Title    string
	Fields   []*ViewField
	Sections []*ViewSection
}

View hydrates human.MarshalOpt

type ViewField

type ViewField struct {

	// Label is the string displayed as header or key for a field.
	Label string

	// FieldName is the key used to retrieve the value from a field (or nested field) of a structure.
	FieldName string
}

type ViewSection

type ViewSection struct {
	Title       string
	FieldName   string
	HideIfEmpty bool
}

type WaitFunc

type WaitFunc func(ctx context.Context, argsI, respI interface{}) (interface{}, error)

WaitFunc returns the updated response (respI if unchanged) or an error.

Jump to

Keyboard shortcuts

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