Documentation
¶
Index ¶
- Constants
- Variables
- func ApplyLimitAndPrint[T any](items []T, limit int, outputFormat string, noColor bool, emptyMessage string, ...) error
- func ApplyTagFilter[T any](ctx context.Context, resources []T, uidFunc func(T) string, ...) ([]T, map[string]error)
- func BuyConfirmPrompt(resourceType string, details []BuyConfirmDetail, noColor bool) bool
- func ConfirmDelete(resourceType ResourceType, resourceID string, force, noColor bool) (bool, error)
- func ConfirmPrompt(question string, noColor bool) bool
- func ContextFromCmd(cmd *cobra.Command) (context.Context, context.CancelFunc)
- func ContextFromCmdWithDefault(cmd *cobra.Command, defaultTimeout time.Duration) (context.Context, context.CancelFunc)
- func DesignConfirmPrompt(resourceType string, details []BuyConfirmDetail, noColor bool) bool
- func FetchTagsConcurrently(ctx context.Context, uids []string, ...) (map[string]map[string]string, map[string]error)
- func Filter[T any](items []T, predicate func(T) bool) []T
- func GetBuyConfirmPrompt() func(string, []BuyConfirmDetail, bool) bool
- func GetConfirmPrompt() func(string, bool) bool
- func GetCurrentEnv() string
- func GetDesignConfirmPrompt() func(string, []BuyConfirmDetail, bool) bool
- func GetPasswordPrompt() func(string, bool) (string, error)
- func GetPrompt() func(string, bool) (string, error)
- func GetResourcePrompt() func(string, string, bool) (string, error)
- func GetResourceTagsPrompt() func(bool) (map[string]string, error)
- func GetSecretResourcePrompt() func(string, string, bool) (string, error)
- func GetUpdateResourceTagsPrompt() func(map[string]string, bool) (map[string]string, error)
- func ListResourceTags(resourceType, uid string, noColor bool, outputFormat string, ...) error
- func LoginClient(cmd *cobra.Command, defaultTimeout time.Duration, login LoginFunc) (context.Context, context.CancelFunc, *megaport.Client, error)
- func MatchesTagFilters(tags map[string]string, filters []string) bool
- func ParseResourceTagsInput(cmd *cobra.Command) (map[string]string, error)
- func PasswordPrompt(msg string, noColor bool) (string, error)
- func Prompt(msg string, noColor bool) (string, error)
- func ReadJSONInput(jsonStr, jsonFile string) ([]byte, error)
- func ResolveInput[T any](cfg InputConfig[T]) (T, error)
- func ResourcePrompt(resourceType string, msg string, noColor bool) (string, error)
- func ResourceTagsPrompt(noColor bool) (map[string]string, error)
- func RetryWithBackoff(ctx context.Context, opts RetryOpts, fn func(ctx context.Context) error) error
- func SecretResourcePrompt(resourceType string, msg string, noColor bool) (string, error)
- func SetBuyConfirmPrompt(fn func(string, []BuyConfirmDetail, bool) bool)
- func SetConfirmPrompt(fn func(string, bool) bool)
- func SetDesignConfirmPrompt(fn func(string, []BuyConfirmDetail, bool) bool)
- func SetPasswordPrompt(fn func(string, bool) (string, error))
- func SetPrompt(fn func(string, bool) (string, error))
- func SetResourcePrompt(fn func(string, string, bool) (string, error))
- func SetResourceTagsPrompt(fn func(bool) (map[string]string, error))
- func SetSecretResourcePrompt(fn func(string, string, bool) (string, error))
- func SetUpdateResourceTagsPrompt(fn func(map[string]string, bool) (map[string]string, error))
- func ShouldDisableColors() bool
- func TimeoutFromCmd(cmd *cobra.Command, defaultTimeout time.Duration) time.Duration
- func UpdateResourceTags(opts UpdateTagsOptions) error
- func UpdateResourceTagsPrompt(existingTags map[string]string, noColor bool) (map[string]string, error)
- func WatchLoop(ctx context.Context, cfg WatchConfig, ...) error
- func WatchResource(cmd *cobra.Command, resourceType string, resourceUID string, noColor bool, ...) error
- func WithIdempotentRetry(ctx context.Context, fn func(ctx context.Context) error) error
- func WithOrderOnceRetry(ctx context.Context, fn func(ctx context.Context) error) error
- func WithRetry(ctx context.Context, fn func(ctx context.Context) error) error
- func WrapAPIError(err error, resourceType, resourceUID string) error
- func WrapColorAwareRunE(fn func(cmd *cobra.Command, args []string, noColor bool) error) func(cmd *cobra.Command, args []string) error
- func WrapOutputFormatRunE(fn func(cmd *cobra.Command, args []string, noColor bool, format string) error) func(cmd *cobra.Command, args []string) error
- func WrapRunE(runE func(cmd *cobra.Command, args []string) error) func(cmd *cobra.Command, args []string) error
- type BuyConfirmDetail
- type InputConfig
- type LoginFunc
- type ResourceType
- type RetryOpts
- type TagListerFunc
- type TagUpdaterFunc
- type UpdateTagsOptions
- type WatchConfig
Constants ¶
const ( // DefaultProvisionTimeout is the default wait time for provisioning operations // (buy, update commands that wait for the resource to become ready). DefaultProvisionTimeout = 10 * time.Minute // DefaultMutationTimeout is the default context timeout for buy/update/delete // commands that may take longer than the standard request timeout. DefaultMutationTimeout = 15 * time.Minute // DefaultWatchTimeout is the default timeout for watch mode loops. // Watch mode monitors resource status which can take 15+ minutes during // provisioning, so this is set generously. Users can override with --timeout. DefaultWatchTimeout = 30 * time.Minute )
const ( FormatTable = "table" FormatJSON = "json" FormatCSV = "csv" FormatXML = "xml" FormatGoTemplate = "go-template" // StatusDecommissioning is used for filtering inactive resources. The SDK // exports STATUS_CANCELLED and STATUS_DECOMMISSIONED but not this one. StatusDecommissioning = "DECOMMISSIONING" )
Variables ¶
var ( // Env is the target environment (prod, dev, staging). Env string // ProfileOverride is the config profile name selected via --profile. ProfileOverride string // NoRetry disables automatic retry on transient API failures. Set via --no-retry flag. NoRetry bool // MaxRetries overrides the default retry count. Set via --max-retries flag. MaxRetries int // LogHTTP enables raw HTTP request/response logging to stderr. Set via --log-http flag. LogHTTP bool // BaseURL overrides the API base URL (e.g. http://localhost:8080). Set via --base-url flag. BaseURL string // TokenURL overrides the OAuth token endpoint. Use with --base-url when the token server // is not one of the three standard Megaport auth hosts. Set via --token-url flag. TokenURL string ValidFormats = []string{FormatTable, FormatJSON, FormatCSV, FormatXML, FormatGoTemplate} ValidFormatsWASM = []string{FormatTable, FormatJSON, FormatCSV, FormatXML} )
These persistent-flag variables are written by cobra during flag parsing on the main goroutine (via PersistentFlags().<T>Var(&utils.X, ...)) and read later while the command runs. They are intentionally plain types rather than sync/atomic wrappers because pflag binds to *string, *bool and *int — switching to atomics would require per-flag pflag.Value shims and break every test that assigns these directly (see auth/login tests).
The safety argument rests on a strict happens-before ordering *per invocation*:
- cmd.Execute() parses flags and writes each variable on the main goroutine.
- Only after parsing completes does cobra invoke PersistentPreRunE / RunE, which may spawn background work (spinners, API retry loops).
- Nothing writes these variables again until the command returns and all spawned work has been joined, so concurrent readers within a single invocation always observe the parsed value.
In the long-lived WASM process each subsequent command re-enters this sequence: flags are re-parsed on the main goroutine only after the previous invocation has fully returned, so the per-invocation invariant holds across re-entries too.
If a future caller needs to mutate any of these at runtime (for example: re-login with a new profile mid-command, toggle LogHTTP after a suspicious response, or adjust MaxRetries between API calls), introduce an atomic snapshot rather than mutating the globals — the set-once invariant is what makes plain variables acceptable here, and it applies equally to every variable in this block.
Functions ¶
func ApplyLimitAndPrint ¶ added in v0.5.9
func ApplyLimitAndPrint[T any]( items []T, limit int, outputFormat string, noColor bool, emptyMessage string, printFunc func([]T, string, bool) error, ) error
ApplyLimitAndPrint handles the common post-filter pipeline for all List commands: validate and apply --limit, check for empty results, and print.
For table output an empty result prints a human-readable message instead of an empty table. For machine formats (json/csv/xml/go-template) it always calls printFunc so an empty result still emits a valid document ([] for json, header-only or empty for csv, <items></items> for xml) rather than zero bytes.
func ApplyTagFilter ¶ added in v0.9.0
func ApplyTagFilter[T any]( ctx context.Context, resources []T, uidFunc func(T) string, fetch func(context.Context, string) (map[string]string, error), tagFilters []string, limit int, ) ([]T, map[string]error)
ApplyTagFilter filters resources by tag, choosing the optimal fetch strategy:
- limit > 0: sequential fetch with early stopping (avoids unnecessary API calls once enough matches are found)
- limit == 0: parallel fetch via FetchTagsConcurrently (minimises wall-clock time when all results are needed)
Resources whose tags could not be fetched are excluded from the results; their UIDs and errors are returned in the second map so the caller can report them after any spinner has been stopped (avoiding interleaved terminal output).
func BuyConfirmPrompt ¶ added in v0.5.4
func BuyConfirmPrompt(resourceType string, details []BuyConfirmDetail, noColor bool) bool
BuyConfirmPrompt displays a purchase summary and asks for confirmation.
func ConfirmDelete ¶ added in v0.11.0
func ConfirmDelete(resourceType ResourceType, resourceID string, force, noColor bool) (bool, error)
ConfirmDelete prompts the user to confirm deletion of a resource. If force is true, confirmation is skipped and (true, nil) is returned. If the user declines, it returns (false, err) with a Cancelled exit code.
func ConfirmPrompt ¶
ConfirmPrompt asks the user a yes/no question.
func ContextFromCmd ¶ added in v0.5.8
ContextFromCmd creates a context with timeout from the command's --timeout flag. If no timeout flag is set or the duration is zero or negative, defaults to 90 seconds.
func ContextFromCmdWithDefault ¶ added in v0.5.8
func ContextFromCmdWithDefault(cmd *cobra.Command, defaultTimeout time.Duration) (context.Context, context.CancelFunc)
ContextFromCmdWithDefault creates a context with timeout from the command's --timeout flag, falling back to defaultTimeout when the flag is not set or is zero or negative. Use this for long-running operations (e.g. provisioning) where the operation-appropriate default differs from the global 90-second default.
func DesignConfirmPrompt ¶ added in v0.11.0
func DesignConfirmPrompt(resourceType string, details []BuyConfirmDetail, noColor bool) bool
DesignConfirmPrompt displays a design summary and asks for confirmation. Use this for commands that create a DESIGN-state resource without billing (e.g. nat-gateway create) — BuyConfirmPrompt's purchase wording is reserved for commands that actually trigger billing.
func FetchTagsConcurrently ¶ added in v0.9.0
func FetchTagsConcurrently( ctx context.Context, uids []string, fetch func(ctx context.Context, uid string) (map[string]string, error), ) (map[string]map[string]string, map[string]error)
FetchTagsConcurrently fetches resource tags for multiple UIDs using a fixed worker pool capped at defaultTagFetchConcurrency, so neither goroutine count nor channel buffer grows with the number of UIDs. It returns two maps: uid→tags for successful fetches and uid→error for failures.
func Filter ¶ added in v0.5.8
Filter returns a new slice containing only the elements of items for which predicate returns true. Returns nil (not an empty slice) when no elements match, consistent with the existing filter functions across this codebase. Callers need not special-case a nil result: len(nil) == 0 in Go.
func GetBuyConfirmPrompt ¶ added in v0.6.0
func GetBuyConfirmPrompt() func(string, []BuyConfirmDetail, bool) bool
func GetConfirmPrompt ¶ added in v0.6.0
func GetCurrentEnv ¶
func GetCurrentEnv() string
func GetDesignConfirmPrompt ¶ added in v0.11.0
func GetDesignConfirmPrompt() func(string, []BuyConfirmDetail, bool) bool
func GetPasswordPrompt ¶ added in v0.13.0
func GetResourcePrompt ¶ added in v0.6.0
func GetResourceTagsPrompt ¶ added in v0.6.0
func GetSecretResourcePrompt ¶ added in v0.11.0
func GetUpdateResourceTagsPrompt ¶ added in v0.6.0
func ListResourceTags ¶ added in v0.5.1
func ListResourceTags(resourceType, uid string, noColor bool, outputFormat string, listFunc TagListerFunc) error
ListResourceTags handles the common pattern of listing resource tags: setting output format, calling the list function, converting to ResourceTag slice, sorting, and printing output.
func LoginClient ¶ added in v0.7.0
func LoginClient(cmd *cobra.Command, defaultTimeout time.Duration, login LoginFunc) (context.Context, context.CancelFunc, *megaport.Client, error)
LoginClient creates a context from the command and logs in to the Megaport API. Returns the context, cancel function, and authenticated client. The caller must defer cancel().
func MatchesTagFilters ¶ added in v0.9.0
MatchesTagFilters returns true if the tags map satisfies all filter specs. Each filter is either "key=value" (exact match) or "key" (key-exists match). An empty filters slice always returns true. A nil tags map is treated as an empty map: key-exists and exact-match filters will both return false, consistent with Go's zero-value map lookup semantics. Filters with an empty key (e.g. "" or "=value") never match.
func ParseResourceTagsInput ¶ added in v0.5.1
ParseResourceTagsInput reads resource tags from --json or --json-file flags.
func PasswordPrompt ¶ added in v0.13.0
PasswordPrompt asks the user for sensitive input with masked terminal echo.
func ReadJSONInput ¶ added in v0.7.0
ReadJSONInput reads JSON data from either a raw string or a file path. If jsonStr is non-empty, it takes precedence; otherwise reads from jsonFile.
func ResolveInput ¶ added in v0.5.9
func ResolveInput[T any](cfg InputConfig[T]) (T, error)
ResolveInput determines which input mode the user chose (JSON, flags, or interactive) and delegates to the appropriate builder function.
Precedence: JSON > flags > interactive > error.
func ResourcePrompt ¶ added in v0.4.0
ResourcePrompt asks the user for resource-specific input.
func ResourceTagsPrompt ¶ added in v0.4.3
ResourceTagsPrompt asks the user to enter resource tags.
func RetryWithBackoff ¶ added in v0.6.0
func RetryWithBackoff(ctx context.Context, opts RetryOpts, fn func(ctx context.Context) error) error
RetryWithBackoff calls fn up to opts.MaxRetries+1 times with exponential backoff and jitter. It respects the Retry-After header from 429 responses and only retries on transient/server errors.
func SecretResourcePrompt ¶ added in v0.11.0
SecretResourcePrompt asks the user for a sensitive resource-specific input (e.g. an admin password) without echoing the input to the terminal when stdin is a TTY. Falls back to the standard echoed prompt for piped input.
func SetBuyConfirmPrompt ¶ added in v0.6.0
func SetBuyConfirmPrompt(fn func(string, []BuyConfirmDetail, bool) bool)
func SetConfirmPrompt ¶ added in v0.6.0
func SetDesignConfirmPrompt ¶ added in v0.11.0
func SetDesignConfirmPrompt(fn func(string, []BuyConfirmDetail, bool) bool)
func SetPasswordPrompt ¶ added in v0.13.0
func SetResourcePrompt ¶ added in v0.6.0
func SetResourceTagsPrompt ¶ added in v0.6.0
func SetSecretResourcePrompt ¶ added in v0.11.0
func SetUpdateResourceTagsPrompt ¶ added in v0.6.0
func ShouldDisableColors ¶ added in v0.3.2
func ShouldDisableColors() bool
func TimeoutFromCmd ¶ added in v0.13.0
TimeoutFromCmd returns the effective timeout duration from the command's --timeout flag, falling back to defaultTimeout when the flag is not set or is zero or negative. Use it when you need the duration itself rather than a context (e.g. to start a fresh context with the same configured timeout).
func UpdateResourceTags ¶ added in v0.5.1
func UpdateResourceTags(opts UpdateTagsOptions) error
UpdateResourceTags handles the common pattern of updating resource tags: fetching existing tags, parsing input (interactive/JSON/JSON file), calling the update function, and printing results.
func UpdateResourceTagsPrompt ¶ added in v0.4.3
func UpdateResourceTagsPrompt(existingTags map[string]string, noColor bool) (map[string]string, error)
UpdateResourceTagsPrompt asks the user to update existing resource tags.
func WatchLoop ¶ added in v0.5.8
func WatchLoop(ctx context.Context, cfg WatchConfig, pollFn func(ctx context.Context) (string, error)) error
WatchLoop runs pollFn repeatedly at the configured interval until interrupted. pollFn should fetch and print its output, returning the current status string for transition tracking.
func WatchResource ¶ added in v0.7.0
func WatchResource( cmd *cobra.Command, resourceType string, resourceUID string, noColor bool, outputFormat string, login LoginFunc, pollFn func(ctx context.Context, client *megaport.Client) (string, error), ) error
WatchResource handles the common watch boilerplate: context creation, login, config setup, and WatchLoop invocation. The pollFn receives the authenticated client and should fetch the resource, print it, and return its provisioning status.
func WithIdempotentRetry ¶ added in v0.6.0
WithIdempotentRetry wraps fn with the default retry policy including network-level error retries. Use this for read-only or idempotent operations where retrying after an ambiguous network failure is safe. If --no-retry was set globally, fn is called exactly once.
func WithOrderOnceRetry ¶ added in v0.13.0
WithOrderOnceRetry wraps fn with a retry policy safe for non-idempotent buy/order operations. It retries ONLY when the request provably never reached processing: HTTP 429, or a connection-refused error raised before the request was sent. It never retries on 5xx or other ambiguous-outcome errors, which could double-submit an order and cause duplicate billing. If --no-retry was set globally, fn is called exactly once.
func WithRetry ¶ added in v0.6.0
WithRetry wraps fn with the default retry policy, only retrying on server-confirmed errors (HTTP status codes like 429, 502, 503, 504). Network-level errors (connection reset, EOF, timeout) are NOT retried because it is unsafe for non-idempotent operations — the server may have processed the request despite the client-side failure. Use WithIdempotentRetry for read-only or otherwise idempotent operations where retrying network errors is safe. If --no-retry was set globally, fn is called exactly once.
func WrapAPIError ¶ added in v0.5.5
WrapAPIError wraps a megaport SDK error with an actionable message based on the HTTP status code. Falls back to the original error if the type cannot be extracted.
func WrapColorAwareRunE ¶
func WrapColorAwareRunE(fn func(cmd *cobra.Command, args []string, noColor bool) error) func(cmd *cobra.Command, args []string) error
WrapColorAwareRunE combines WrapRunE and WrapCommandFunc to handle both error formatting and passing the noColor flag to command functions.
func WrapOutputFormatRunE ¶
func WrapOutputFormatRunE(fn func(cmd *cobra.Command, args []string, noColor bool, format string) error) func(cmd *cobra.Command, args []string) error
WrapOutputFormatRunE handles both output format and color settings in command functions. This wrapper takes a function that needs both output format and noColor parameters.
Types ¶
type BuyConfirmDetail ¶ added in v0.5.4
BuyConfirmDetail represents a key-value detail line in the purchase summary.
type InputConfig ¶ added in v0.5.9
type InputConfig[T any] struct { // ResourceName is used in the fallback error message (e.g. "port", "MCR"). ResourceName string // Cmd is the cobra command whose flags are inspected. Cmd *cobra.Command // NoColor disables colored output. NoColor bool // FlagsProvided should return true when any resource-specific CLI flags // have been explicitly set by the user. FlagsProvided func() bool // FromJSON builds the request from --json or --json-file input. FromJSON func(jsonStr, jsonFile string) (T, error) // FromFlags builds the request from CLI flags. FromFlags func() (T, error) // FromPrompt builds the request via interactive prompts. // May be nil if the command does not support interactive mode. FromPrompt func() (T, error) }
InputConfig configures how ResolveInput resolves the request object from one of the three input modes (JSON, flags, interactive prompts).
type LoginFunc ¶ added in v0.7.0
LoginFunc is the function signature for authenticating with the Megaport API.
type ResourceType ¶ added in v0.11.0
type ResourceType string
ResourceType represents the type of a Megaport resource.
const ( ResourceTypePort ResourceType = "Port" ResourceTypeMCR ResourceType = "MCR" ResourceTypeMVE ResourceType = "MVE" ResourceTypeVXC ResourceType = "VXC" ResourceTypeIX ResourceType = "IX" )
type RetryOpts ¶ added in v0.6.0
type RetryOpts struct {
MaxRetries int
InitialDelay time.Duration
MaxDelay time.Duration
BackoffMultiplier float64
// RetryNetworkErrors enables retrying on ambiguous network failures
// (connection reset, EOF, timeout). Only set this for idempotent operations.
RetryNetworkErrors bool
// OrderOnce restricts retries to errors that prove the request never reached
// processing (HTTP 429, connection-refused-before-send). Set this for
// non-idempotent buy/order calls so an ambiguous failure cannot double-submit.
OrderOnce bool
}
RetryOpts configures the retry behaviour of RetryWithBackoff.
func DefaultRetryOpts ¶ added in v0.6.0
func DefaultRetryOpts() RetryOpts
DefaultRetryOpts returns sensible defaults for API retry behaviour. MaxRetries is taken from the --max-retries flag (default 3, set by cobra).
type TagListerFunc ¶ added in v0.5.1
TagListerFunc is a function that lists resource tags for a given UID.
type TagUpdaterFunc ¶ added in v0.5.1
TagUpdaterFunc is a function that updates resource tags for a given UID.
type UpdateTagsOptions ¶ added in v0.5.1
type UpdateTagsOptions struct {
ResourceType string
UID string
NoColor bool
Cmd *cobra.Command
ListFunc TagListerFunc
UpdateFunc TagUpdaterFunc
ExtraTagFlags bool // When true, also check --tags, --tags-file, --resource-tags flags
}
UpdateTagsOptions contains the options for UpdateResourceTags.