core

package
v6.10.2 Latest Latest
Warning

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

Go to latest
Published: Jul 8, 2026 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Index

Constants

View Source
const (
	RequiredFlagsAnnotation   = "RequiredFlags"
	DeprecatedFlagsAnnotation = "DeprecatedFlags"
)
View Source
const (
	// AnnotationLocations is set by WithRegionalConfigOverride on the service
	// root command. It contains comma-separated allowed locations (e.g. "de/fra,de/txl").
	AnnotationLocations = "regional.locations"

	// AnnotationTemplateURL is the URL template with %s placeholder for location.
	AnnotationTemplateURL = "regional.templateURL"

	// AnnotationProductNames is the comma-separated product names used to look
	// up per-location config-file URL overrides (mirrors WithRegionalConfigOverride).
	AnnotationProductNames = "regional.productNames"
)

Variables

View Source
var NoPreRun = func(c *PreCommandConfig) error { return nil }
View Source
var (
	RootCmdTest = Command{
		Command: &cobra.Command{
			Use: testConst,
		},
	}
)

Functions

func CheckRequiredFlags

func CheckRequiredFlags(cmd *Command, ns string, localFlagsName ...string) error

func CheckRequiredFlagsSets

func CheckRequiredFlagsSets(cmd *Command, ns string, localFlagsNameSets ...[]string) error

CheckRequiredFlagsSets focuses on commands that support multiple ways to run, and it is required at least one of the ways to be set. For example: for `datacenter delete`, it is required to be set either `--datacenter-id` option, either `--all` option.

func CheckRequiredFlagsSetsIfPredicate

func CheckRequiredFlagsSetsIfPredicate(cmd *Command, ns string, localFlagsNameSets ...FlagNameSetWithPredicate) error

If a flag being set to a certain value creates some extra flag dependencies, then use this function!

func CmdConfigTest

func CmdConfigTest(t *testing.T, writer io.Writer, runner CmdRunnerTest)

func ExecuteTestCases

func ExecuteTestCases(t *testing.T, funcToTest func(c *CommandConfig) error, testCases []TestCase, cfg *CommandConfig)

func FlagAsVariable

func FlagAsVariable(flag string) string

FlagAsVariable takes a flag name and returns it as a screaming camel case

e.g. `FlagAsVariable("datacenter-id") -> "DATACENTER_ID"

func FlagUsage

func FlagUsage(flag string) string

FlagUsage ("datacenter-id") -> "--datacenter-id DATACENTER_ID"

Used as a convenience func

func FlagsUsage

func FlagsUsage(flags ...string) string

FlagsUsage calls FlagUsage for every flag in the slice

FlagsUsage ("datacenter-id") -> "--datacenter-id DATACENTER_ID"

func GetFlagName

func GetFlagName(ns, flagName string) string

func PreCmdConfigTest

func PreCmdConfigTest(t *testing.T, writer io.Writer, preRunner PreCmdRunTest)

func RequiresMinOptionsErr

func RequiresMinOptionsErr(cmd *Command, flagNames ...string) error

func RequiresMultipleOptionsErr

func RequiresMultipleOptionsErr(cmd *Command, flagNamesSets ...[]string) error

Types

type CmdRunnerTest

type CmdRunnerTest func(c *CommandConfig, mocks *ResourcesMocksTest)

type Command

type Command struct {
	// NS is the Global Namespace of the Command
	NS      string
	Command *cobra.Command
	// contains filtered or unexported fields
}

func NewCommand

func NewCommand(ctx context.Context, parent *Command, info CommandBuilder) *Command

func NewCommandWithJsonProperties

func NewCommandWithJsonProperties(ctx context.Context, parent *Command, jsonExample string, toUnmarshal interface{}, info CommandBuilder) *Command

func WithConfigOverride added in v6.9.0

func WithConfigOverride(c *Command, productNames []string, fallbackURL string) *Command

func WithRegionalConfigOverride added in v6.9.0

func WithRegionalConfigOverride(c *Command, productNames []string, templateFallbackURL string, allowedLocations []string) *Command

WithRegionalConfigOverride adds regional flag support to a command, allowing users to specify a location or override the server URL. To use this function, wrap the root command of your API and specify the baseURL and allowed locations.

Example:

	func DNSCommand() *core.Command {
		cmd := &core.Command{
			Command: &cobra.Command{
				Use:              "dns",
				Short:            "The sub-commands of the 'dns' resource help automate DNS Zone and Record management",
				TraverseChildren: true,
			},
		}

		// Add regional flags
		return core.WithRegionalConfigOverride(cmd, []string{fileconfiguration.Cloud, "compute"}, "https://dns.%s.ionos.com", []string{"de/fra", "de/txl"})
	}

  - 'baseURL': The base URL for the API, with an optional '%s' placeholder for the location (e.g., '"https://dns.%s.ionos.com"').
  - 'allowedLocations': A slice of allowed locations (e.g., '[]string{"de/fra", "de/txl"}'). These will populate the '--location' flag completion.

Notes

  • The '--server-url' flag allows users to override the API host URL manually.
  • The '--location' flag allows users to specify a region, which replaces the '%s' placeholder in the 'baseURL'.
  • If '--location' is used and is valid (from 'allowedLocations'), the 'baseURL' is formatted with the normalized location.
  • If '--location' is invalid or unsupported, a warning is logged, but the constructed URL is still attempted.
  • If 'allowedLocations' is empty, the function panics, as this is considered a programming error.
  • If an unsupported location is provided, a warning is logged: 'WARN: <location> is an invalid location. Valid locations are: <allowedLocations>'
  • This also marks '--api-url' and '--location' flags as mutually exclusive.
  • The first location in 'allowedLocations' is used as the default for non-list commands.
  • List commands using CommandConfig.ListAllLocations query all locations when '--location' is not set.

func (*Command) AddBoolFlag

func (c *Command) AddBoolFlag(name, shorthand string, defaultValue bool, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddColsFlag added in v6.10.1

func (c *Command) AddColsFlag(columns []table.Column)

AddColsFlag registers a persistent --cols flag with tab-completion on the command. The flag is inherited by all subcommands and controls which table columns are displayed.

func (*Command) AddCommand

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

func (*Command) AddDurationFlag

func (c *Command) AddDurationFlag(name, shorthand string, defaultValue time.Duration, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddFloat32Flag

func (c *Command) AddFloat32Flag(name, shorthand string, defaultValue float32, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddFloat64Flag added in v6.9.0

func (c *Command) AddFloat64Flag(name, shorthand string, defaultValue float64, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddInt32Flag

func (c *Command) AddInt32Flag(name, shorthand string, defaultValue int32, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddInt32VarFlag

func (c *Command) AddInt32VarFlag(address *int32, name, shorthand string, defaultValue int32, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddIntFlag

func (c *Command) AddIntFlag(name, shorthand string, defaultValue int, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddIntSliceFlag

func (c *Command) AddIntSliceFlag(name, shorthand string, defaultValue []int, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddIpFlag

func (c *Command) AddIpFlag(name, shorthand string, defaultValue net.IP, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddIpSliceFlag

func (c *Command) AddIpSliceFlag(name, shorthand string, defaultValue []net.IP, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddSetFlag

func (c *Command) AddSetFlag(name, shorthand, defaultValue string, allowed []string, desc string, optionFunc ...FlagOptionFunc)

AddSetFlag adds a String slice flag with support for limitation to certain values in a slice. It also adds completions for those limited values, on top of throwing an error if the flag value isn't found among the marked valid values

func (*Command) AddStringFlag

func (c *Command) AddStringFlag(name, shorthand, defaultValue, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddStringSliceFlag

func (c *Command) AddStringSliceFlag(name, shorthand string, defaultValue []string, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddStringSliceVarFlag

func (c *Command) AddStringSliceVarFlag(address *[]string, name, shorthand string, defaultValue []string, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddStringToStringFlag

func (c *Command) AddStringToStringFlag(name, shorthand string, defaultValue map[string]string, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddStringToStringVarFlag

func (c *Command) AddStringToStringVarFlag(v *map[string]string, name, shorthand string, defaultValue map[string]string, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddStringVarFlag

func (c *Command) AddStringVarFlag(address *string, name, shorthand, value, desc string, optionFunc ...FlagOptionFunc)

func (*Command) AddUUIDFlag

func (c *Command) AddUUIDFlag(name, shorthand, defaultValue, desc string, optionFunc ...FlagOptionFunc)

func (*Command) CommandPath

func (c *Command) CommandPath() string

func (*Command) GetAnnotations

func (c *Command) GetAnnotations() map[string]string

func (*Command) GetAnnotationsByKey

func (c *Command) GetAnnotationsByKey(key string) string

func (*Command) GlobalFlags

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

func (*Command) IsAvailableCommand

func (c *Command) IsAvailableCommand() bool

func (*Command) Name

func (c *Command) Name() string

func (*Command) SetFlagAnnotation

func (c *Command) SetFlagAnnotation(name, key string, values ...string)

func (*Command) SubCommands

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

type CommandBuilder

type CommandBuilder struct {
	// Command is a Wrapper around Cobra Command
	Command *Command

	// Command Levels
	// Namespace is the first level of the Command. e.g. [ionosctl] server
	Namespace string
	// Resource is the second level of the Command. e.g. [ionosctl server] volume
	Resource string
	// Verb is the 3rd level of the Command. e.g. [ionosctl server volume] attach
	Verb string

	// Short Description
	ShortDesc string
	// Long Description
	LongDesc string
	// Aliases
	Aliases []string
	// Example of Command run
	Example string

	// Command Run functions
	// to be executed
	PreCmdRun PreCommandRun
	CmdRun    CommandRun
	// Init Client Services
	InitClient bool
}

CommandBuilder contains information about the new Command to be used in Cobra Command

func (*CommandBuilder) GetNS

func (c *CommandBuilder) GetNS() string

type CommandConfig

type CommandConfig struct {
	// Command is a Wrapper around Cobra Command
	Command *Command

	// CLI Engine
	// NS is Global Namespace for all Command Levels
	NS string
	// Namespace is the first level of the Command. e.g. [ionosctl] server
	Namespace string
	// Resource is the second level of the Command. e.g. [ionosctl server] volume
	Resource string
	// Verb is the 3rd level of the Command. e.g. [ionosctl server volume] attach
	Verb  string
	Stdin io.Reader

	// Services
	CloudApiV6Services cloudapiv6.Services

	// Context
	Context context.Context
	// contains filtered or unexported fields
}

CommandConfig Properties and Services

func NewCommandCfg

func NewCommandCfg(ctx context.Context, info CommandBuilder) (*CommandConfig, error)

func (*CommandConfig) Cols added in v6.10.1

func (c *CommandConfig) Cols() []string

Cols returns the user-specified --cols flag value, or nil for defaults.

func (*CommandConfig) ListAllLocations added in v6.10.2

func (c *CommandConfig) ListAllLocations(
	columns []table.Column,
	fetchFn func(cfg *shared.Configuration) (any, error),
) error

ListAllLocations runs fetchFn against one or more locations and renders a single, consistently-shaped view. For a regional API the output always carries location provenance, regardless of whether --location was set:

  • text: table with "Location" as the first column.
  • json: items merged under "items", each stamped with a "location" field.
  • api-json: array of per-location responses, each with a "location" field.

The set of locations queried is: the single value of --location if set; otherwise the one location a single-location API exposes; otherwise all locations (queried concurrently). This means the output shape does not shift with --location - only the number of locations queried changes.

Non-regional commands (no regional config) print the raw response unchanged.

The fetchFn receives a shared.Configuration for the target location URL. It must create its own SDK client from the config and execute the API call.

func (*CommandConfig) Msg added in v6.9.8

func (c *CommandConfig) Msg(format string, args ...any)

Msg writes a formatted message to stdout, respecting --quiet and --output flags. In text mode it prints the message as-is; in JSON modes it marshals the string.

func (*CommandConfig) Out added in v6.9.8

func (c *CommandConfig) Out(s string, err error) error

Out writes pre-rendered output (e.g. from table.Sprint or table.Render) to stdout. It accepts (string, error) so it chains directly:

return c.Out(table.Sprint(cols, data, userCols))
return c.Out(t.Render(table.ResolveCols(cols, userCols)))

func (*CommandConfig) Printer added in v6.10.1

func (c *CommandConfig) Printer(columns []table.Column) *printer

Printer returns a builder for table-based output. Usage:

return c.Printer(allCols).Print(data)
return c.Printer(allCols).Prefix("items").Print(data)

func (*CommandConfig) RequireExplicitLocation added in v6.10.2

func (c *CommandConfig) RequireExplicitLocation() error

RequireExplicitLocation enforces that --location is set for location-scoped (single-resource) operations on regional APIs. This CommandConfig variant is for hybrid list commands that only take a single-location branch at runtime (e.g. when a specific parent ID is provided); call it inside that branch. It is a no-op for non-regional commands, single-location APIs, or when --location is already set.

func (*CommandConfig) RunForAllLocations added in v6.10.2

func (c *CommandConfig) RunForAllLocations(fn func(cfg *shared.Configuration, location string) error) error

RunForAllLocations invokes fn once per allowed location (sequentially) for multi-location regional APIs when --location is not set, so bulk operations such as `delete --all` span every location the same way `list` does. Errors from individual locations are aggregated; a failure in one location does not stop the others.

For non-regional commands, single-location APIs, or when --location is set explicitly, fn runs exactly once against the resolved single-location config.

fn receives a per-location shared.Configuration and the location label; it must build its own SDK client from that config (do not use the global client.Must() singleton, which is bound to a single location).

func (*CommandConfig) Verbose added in v6.9.8

func (c *CommandConfig) Verbose(format string, args ...any)

Verbose writes a formatted informational message to stderr, only when --verbose is set. Respects --quiet and --output flags.

type CommandRun

type CommandRun func(commandConfig *CommandConfig) error

type FlagNameSetWithPredicate

type FlagNameSetWithPredicate struct {
	FlagNameSet    []string
	Predicate      func(interface{}) bool
	PredicateParam interface{}
}

type FlagOptionFunc

type FlagOptionFunc func(cmd *Command, flagName string)

func DeprecatedFlagOption

func DeprecatedFlagOption(help string) FlagOptionFunc

func RequiredFlagOption

func RequiredFlagOption() FlagOptionFunc

func WithCompletion added in v6.7.9

func WithCompletion(completionFunc func() []string, baseURL string, locations []string) FlagOptionFunc

WithCompletion is a FlagOptionFunc that allows for a completion function that returns a list of strings.

Usage:

- WithCompletion(completionFunc, "api.%s.ionos.com") for a regional API

- WithCompletion(completionFunc, "api.ionos.com") for an API with a single endpoint

- WithCompletion(completionFunc, "") to let the SDKs choose the API endpoint

func WithCompletionComplex added in v6.7.9

func WithCompletionComplex(
	completionFunc func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective),
	baseURL string, locations []string,
) FlagOptionFunc

WithCompletionComplex is a FlagOptionFunc that allows for more complex completion logic. It is recommended to use one of the simpler helper functions WithCompletion or WithCompletionE instead. Use this complex function only if you need to handle advanced logic, like args-based completion, or custom filtering based on already typed keys (from toComplete).

The function determines the URL to set based on the following rules: 1. If the baseURL does not contain a placeholder (e.g., "%s"), it will be used directly. 2. If the baseURL contains a placeholder and a location is provided, the location will be used to construct the URL. 3. If no location is provided, the first location in the `locations` list will be used as a default.

func WithCompletionE added in v6.7.9

func WithCompletionE(completionFunc func() ([]string, error), baseURL string, locations []string) FlagOptionFunc

WithCompletionE is a FlagOptionFunc that allows for a completion function that can return an error.

Usage:

- WithCompletionE(completionFuncE, "api.%s.ionos.com") for a regional API

- WithCompletionE(completionFuncE, "api.ionos.com") for an API with a single endpoint

- WithCompletionE(completionFuncE, "") to let the SDK choose the API endpoint

type FlagValuePair

type FlagValuePair struct {
	Flag  string
	Value interface{}
}

type PreCmdRunTest

type PreCmdRunTest func(c *PreCommandConfig)

type PreCommandConfig

type PreCommandConfig struct {
	// Command is a Wrapper around Cobra Command
	Command *Command

	// NS is Global Namespace for all Command Levels
	NS string
	// Namespace is the first level of the Command. e.g. [ionosctl] server
	Namespace string
	// Resource is the second level of the Command. e.g. [ionosctl server] volume
	Resource string
	// Verb is the 3rd level of the Command. e.g. [ionosctl server volume] attach
	Verb string
}

PreCommandConfig Properties

func NewPreCommandCfg

func NewPreCommandCfg(info CommandBuilder) *PreCommandConfig

func (*PreCommandConfig) CheckRequiredFlagsAndLocation added in v6.10.2

func (c *PreCommandConfig) CheckRequiredFlagsAndLocation(flags ...string) error

CheckRequiredFlagsAndLocation behaves like CheckRequiredFlags, but for multi-location regional APIs it also requires --location. This makes the requirement visible up front: --location appears in the usage/error together with the other required flags, instead of failing only after the user has already satisfied everything else. It is a no-op location requirement for single-location APIs or non-regional commands.

Use this from PreCmdRun of single-resource commands (create/get/update) instead of a separate PreCommandConfig.RequireExplicitLocation call.

func (*PreCommandConfig) CheckRequiredFlagsSetsAndLocation added in v6.10.2

func (c *PreCommandConfig) CheckRequiredFlagsSetsAndLocation(sets ...[]string) error

CheckRequiredFlagsSetsAndLocation is the CheckRequiredFlagsSets equivalent of PreCommandConfig.CheckRequiredFlagsAndLocation: on multi-location regional APIs it also requires --location, adding it to every flag set so the requirement shows up in the usage/error alongside the other required flags.

Only use this for commands where --location is needed regardless of which set is satisfied (create/update/get). Do NOT use it for delete commands whose sets include an --all escape that must fan out without --location; those enforce --location inside their single-resource branch instead.

func (*PreCommandConfig) RequireExplicitLocation added in v6.10.2

func (c *PreCommandConfig) RequireExplicitLocation() error

RequireExplicitLocation enforces that --location is set for location-scoped (single-resource) operations on regional APIs. Call it from PreCmdRun of commands that operate on a specific resource ID. It is a no-op for non-regional commands or when --location is already set.

List commands that fan out over all locations must NOT call this; they use CommandConfig.ListAllLocations instead.

type PreCommandRun

type PreCommandRun func(commandConfig *PreCommandConfig) error

PreCommandRun will run in PreRun of Cobra Command structure, before running the actual Command. Its purpose is to keep the validate part separate from run part.

func PreRunWithDeprecatedFlags added in v6.7.4

func PreRunWithDeprecatedFlags(f PreCommandRun, flags ...functional.Tuple[string]) PreCommandRun

PreRunWithDeprecatedFlags is a decorator for using a command with deprecated flags The value of the first flag in the Tuple is set as the value of the second flag of the Tuple

type ResourcesMocksTest

type ResourcesMocksTest struct {
	// Add New Services Resources Mocks
	CloudApiV6Mocks cloudapiv6.ResourcesMocks
}

type SetFlag

type SetFlag struct {
	Value   string
	Allowed []string
}

SetFlag / Values set for this flag must be part of allowed values NOTE: Track progress of https://github.com/spf13/pflag/issues/236 : Might be implemented in pflag

func (*SetFlag) Set

func (a *SetFlag) Set(p string) error

func (SetFlag) String

func (a SetFlag) String() string

func (*SetFlag) Type

func (a *SetFlag) Type() string

type TestCase

type TestCase struct {
	Name        string
	UserInput   io.Reader
	Args        []FlagValuePair
	Calls       func(...*gomock.Call)
	ExpectedErr bool // To be replaced by `error` type once it makes sense to do so (currently only one type of error is thrown)
}

Directories

Path Synopsis
Package doc generates Markdown files and organizes a directory structure that follows the command hierarchy.
Package doc generates Markdown files and organizes a directory structure that follows the command hierarchy.

Jump to

Keyboard shortcuts

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