Documentation
¶
Overview ¶
Package cmdutil is the glue between cobra and the nvfleetint SDK that the resource command packages share: the common flags every command registers, the client those flags build, and the parsing, pagination, and error rendering that would otherwise be restated once per command.
It is deliberately the only shared internal package that imports both cobra and the SDK. Command packages may import both because they define cobra commands and execute SDK calls, but shared glue lives here. Formatting that needs neither belongs in internal/output; rules about what the API accepts belong in the SDK.
Index ¶
- Constants
- Variables
- func ApplyPagination(flags Resolved, setPage func(*int), setPageSize func(*int))
- func Confirm(in io.Reader, out io.Writer, summary string) error
- func CredentialWarnings(resolved config.Resolved) []string
- func ExitCode(err error) int
- func ExtractRawItems(data []byte, itemKey string) ([]json.RawMessage, error)
- func FixAPIURLHint(resolved config.Resolved) string
- func FormatLocation(location *nvfleetint.Location) string
- func FromResolved(resolved config.Resolved, common Resolved) (*nvfleetint.Client, error)
- func MissingAPIKeyError(resolved config.Resolved) error
- func New(common Resolved) (*nvfleetint.Client, error)
- func NormalizeWindowFlag(window string) (string, error)
- func OneIndexRawPage(data []byte) []byte
- func OptionalSingleArg(name string) cobra.PositionalArgs
- func OptionsHelpNote(command string, flags ...string) string
- func ParseCommaList(raw string) ([]string, error)
- func ParseIntList(flag, raw string) ([]int, error)
- func ParseTypedList[T ~string](flag, raw string) ([]T, error)
- func RegisterListFlags(cmd *cobra.Command, flags *Common)
- func RegisterOutputFlag(cmd *cobra.Command, flags *Common)
- func RegisterPaginationFlags(cmd *cobra.Command, flags *Common)
- func RegisterProfileFlag(cmd *cobra.Command, flags *Common)
- func RegisterReadFlags(cmd *cobra.Command, flags *Common)
- func RegisterTimeRangeFlags(cmd *cobra.Command, window, start, end *string)
- func RegisterTimeoutFlag(cmd *cobra.Command, flags *Common)
- func RejectUnknownSubcommands(cmd *cobra.Command)
- func RenderOptionError(err error, names map[string]OptionFlagName) error
- func RequireSingleArg(name string) cobra.PositionalArgs
- func ResolveCredentials(profile string) (config.Resolved, error)
- func ValidateListFlags(flags Resolved) error
- func ValidateOptionalTimeRangeFlags(window, start, end string) error
- func ValidateRFC3339Flag(name, value string) error
- func ValidateReadFlags(flags Resolved) error
- func ValidateStepFlag(step string) error
- func ValidateTimeRangeFlags(window, start, end string) error
- func ValueRows(values []string) [][]string
- func WantsJSONOutput(args []string) bool
- func Write(out io.Writer, args []string, err error)
- func WriteOptionSection(w io.Writer, heading string, rows [][]string) error
- func WritePaginatedListJSON(w io.Writer, rawJSON []byte, jsonValue any) error
- type Common
- type CredentialPrompt
- type MergedJSONResult
- type MergedPagination
- type OptionFlag
- type OptionFlagName
- type OptionSection
- type OptionsRenderer
- type RawPage
- type Resolved
Constants ¶
const ( // MinPageSize is the smallest page size accepted by list commands MinPageSize = 1 // MaxPageSize is the largest page size accepted by list commands MaxPageSize = 100 // MaxPages bounds all-page pagination when the API keeps reporting more data MaxPages = 10000 )
const OptionsPreamble = "Values are comma-separated; where two columns are shown, pass the left one."
OptionsPreamble states the two conventions once, so each section can be a bare flag name. Whether a flag matches an option's ID or its display value is load-bearing — the backend silently returns no rows for the wrong one — and an ID is always rendered as the left of two columns.
Variables ¶
var ErrAborted = errors.New("aborted")
ErrAborted reports a confirmation prompt the user declined. It exits 1 through main.go like any other command error.
Functions ¶
func ApplyPagination ¶
ApplyPagination applies explicitly supplied pagination flags to request options.
func Confirm ¶
Confirm prints summary and an "Are you sure? y/N" prompt to out and waits for an answer on in. Callers pass the command's stderr as out so `-o json` keeps stdout parseable. Anything other than an explicit yes returns ErrAborted, so the default is No.
It refuses to prompt when in is a non-terminal file, so a cron or CI run gets a clear "re-run with --yes" error instead of blocking forever or silently aborting on EOF.
func CredentialWarnings ¶
CredentialWarnings lists the conditions that did not stop credential resolution but changed its outcome. `auth status` exists to explain how credentials resolved, so these belong in its output rather than in a silently degraded result.
func ExtractRawItems ¶
func ExtractRawItems(data []byte, itemKey string) ([]json.RawMessage, error)
Extracts raw array items from an API response object
func FixAPIURLHint ¶
FixAPIURLHint names the place a rejected API URL came from.
func FormatLocation ¶
func FormatLocation(location *nvfleetint.Location) string
FormatLocation formats the most useful location label available.
func FromResolved ¶
FromResolved builds an SDK client from already-resolved credentials, for a command that has resolved them itself.
func MissingAPIKeyError ¶
MissingAPIKeyError explains which profile (if any) is missing an API key.
func New ¶
func New(common Resolved) (*nvfleetint.Client, error)
New builds an SDK client from the credentials selected by the common flags.
func NormalizeWindowFlag ¶
NormalizeWindowFlag trims a --window value and checks it against the SDK's rule, returning the value to send to the backend.
func OneIndexRawPage ¶
OneIndexRawPage rewrites the 0-indexed "page" field in a raw list payload to its 1-indexed equivalent so JSON consumers see the CLI's paging contract. When total and pageSize are available, the page is bounded to the available pages. The original bytes are returned unchanged when the payload has no usable page field.
func OptionalSingleArg ¶
func OptionalSingleArg(name string) cobra.PositionalArgs
OptionalSingleArg validates that at most one positional argument was given. The caller supplies the meaning of an omitted argument; only the too-many case is an error here, and it is worded exactly as in RequireSingleArg.
func OptionsHelpNote ¶
OptionsHelpNote builds the command-level help note for flags whose values are discoverable from an options endpoint. Keeping this out of every individual flag avoids noisy repeated help text while still surfacing the discovery path.
func ParseCommaList ¶
Splits a comma-separated flag value into trimmed values
func ParseIntList ¶
ParseIntList splits a comma-separated flag value into integers, rejecting negative values. flag names the flag in the error.
func ParseTypedList ¶
ParseTypedList splits a comma-separated flag value into a string-based API type. flag names the flag when the list itself is malformed.
It deliberately does not check the values: the SDK validates them, so the accepted values are stated in one place and the two layers cannot drift.
func RegisterListFlags ¶
RegisterListFlags registers output, pagination, and credential flags on a list command.
func RegisterOutputFlag ¶
RegisterOutputFlag registers the output flag on a command.
func RegisterPaginationFlags ¶
RegisterPaginationFlags registers pagination flags on a command.
func RegisterProfileFlag ¶
RegisterProfileFlag registers the credential profile selector on an API-backed command. The `auth` CRUD commands take the profile they change as a positional argument instead, so `--profile` only ever means "credentials for this invocation".
func RegisterReadFlags ¶
RegisterReadFlags registers output and credential flags on a read command.
func RegisterTimeRangeFlags ¶
RegisterTimeRangeFlags registers the shared relative/absolute time-range flags.
func RegisterTimeoutFlag ¶
RegisterTimeoutFlag registers the request timeout flag on a command.
func RejectUnknownSubcommands ¶
RejectUnknownSubcommands makes a resource group such as `node` reject an unknown subcommand instead of printing its help and exiting 0, so a typo'd command in a script fails loudly rather than reporting success having done nothing. Both fields are needed: cobra skips Args validation on a command that has no Run of its own.
Only groups need this. Cobra applies the same check to the root command automatically (where it also suggests near-misses), and every leaf command declares its own Args.
func RenderOptionError ¶
func RenderOptionError(err error, names map[string]OptionFlagName) error
RenderOptionError re-renders an SDK option error against the flag that carries the option, so that a message names what the user typed rather than the SDK field.
Validation itself lives in the SDK: this maps its vocabulary onto the CLI's instead of restating the rules, which is what let the two drift apart. Errors that are not about one option value pass through unchanged; their wording already reads as CLI prose.
func RequireSingleArg ¶
func RequireSingleArg(name string) cobra.PositionalArgs
RequireSingleArg validates that exactly one positional argument was given, naming it in errors.
func ResolveCredentials ¶
ResolveCredentials resolves credentials, adding CLI hints to the config package's errors.
func ValidateListFlags ¶
ValidateListFlags checks common flags for list-style commands.
func ValidateOptionalTimeRangeFlags ¶
ValidateOptionalTimeRangeFlags applies the same rules as ValidateTimeRangeFlags where the range is a filter rather than a requirement, so supplying none of the flags is allowed. A partial range is still an error.
func ValidateRFC3339Flag ¶
ValidateRFC3339Flag checks a timestamp flag value, naming the flag in the error. The SDK checks the same values on the way out; this runs first so the message names the flag the user typed.
func ValidateReadFlags ¶
ValidateReadFlags checks common flags for non-paginated read commands.
func ValidateStepFlag ¶
ValidateStepFlag trims a --step value and checks it against the SDK's rule.
func ValidateTimeRangeFlags ¶
ValidateTimeRangeFlags mirrors the SDK time-range rules at the CLI layer for early errors that name the flag the user typed.
func WantsJSONOutput ¶
WantsJSONOutput reports whether the raw arguments select JSON output. It reads the command line directly so an error raised before or during flag parsing is still rendered in the format the user asked for.
func Write ¶
Write reports a command failure on out, as JSON when the arguments asked for JSON output and as a plain line otherwise. args is the raw command line because the failure can predate flag parsing.
func WriteOptionSection ¶
WriteOptionSection writes one filter section: a blank line, a heading naming the flag, then the values indented beneath it.
func WritePaginatedListJSON ¶
WritePaginatedListJSON writes paginated list output as JSON, presenting the page number with the CLI's 1-based contract. rawJSON is a single API page; jsonValue is the merged result produced for --all.
Types ¶
type Common ¶
type Common struct {
Output string
All bool
Page int
PageSize int
Timeout time.Duration
Profile string
}
Common stores shared output, pagination, and credential flag values.
type CredentialPrompt ¶
type CredentialPrompt struct {
// contains filtered or unexported fields
}
CredentialPrompt reads credentials from stdin and writes its questions to out — the command's stderr, so prompts never mix into piped output.
func NewCredentialPrompt ¶
func NewCredentialPrompt(in io.Reader, out io.Writer) *CredentialPrompt
func (*CredentialPrompt) APIKey ¶
func (p *CredentialPrompt) APIKey(keepStored bool) (string, bool, error)
APIKey reads the API key. Empty input keeps the key already stored, so rotating an endpoint never has to re-enter — or even see — the current key. With none stored there is nothing to keep and the value is required.
func (*CredentialPrompt) APIURL ¶
func (p *CredentialPrompt) APIURL(current string) (string, error)
APIURL reads the API URL, offering current as the value to accept — the production endpoint for a new profile, the stored one for an existing profile, so pressing Enter is always the answer that changes nothing.
The offered value is named, not just printed: most people cannot tell the production endpoint from a typo by reading it, so an unlabeled URL makes pressing Enter a guess rather than a decision.
The answer is validated here rather than on the way to disk: at a terminal a rejected URL can simply be asked for again, which is the whole advantage of prompting over a flag.
func (*CredentialPrompt) Interactive ¶
func (p *CredentialPrompt) Interactive() bool
Interactive reports whether a person is answering, rather than input being piped in. It is what separates a warning the user saw and answered from one nobody read, so a caller can require explicit consent in the second case.
func (*CredentialPrompt) Note ¶
func (p *CredentialPrompt) Note(format string, args ...any)
Note writes a line of context above a prompt.
type MergedJSONResult ¶
type MergedJSONResult struct {
Items []json.RawMessage `json:"items"`
Pagination MergedPagination `json:"pagination"`
}
Represents normalized JSON for all-page output
func FetchAllPages ¶
func FetchAllPages[P nvfleetint.Paginated]( itemKey string, fetch func(page int) (P, error), collect func(P), ) (MergedJSONResult, error)
FetchAllPages fetches every page of a paginated SDK list response, handing each page to collect and merging the raw payloads into one JSON document. Commands use this rather than FetchAllRawPages so that the pagination envelope is read from the response itself instead of being restated, field by field, at every call site.
func FetchAllRawPages ¶
func FetchAllRawPages(itemKey string, startPage int, fetch func(page int) (RawPage, error)) (MergedJSONResult, error)
Fetches and merges raw API item payloads across pages
type MergedPagination ¶
type MergedPagination struct {
Page int `json:"page"`
PageSize int `json:"pageSize"`
Total int `json:"total"`
HasMore bool `json:"hasMore"`
PagesFetched int `json:"pagesFetched"`
}
Represents metadata for normalized all-page JSON
type OptionFlag ¶
type OptionFlag struct {
Name string
// promote names the flag that accepts this field's child options, if the
// backend nests any (a compute zone nests its node groups). Those children
// are lifted into a section of their own so that every section describes
// exactly one flag; `/v1/alert_timeline/filter_options` already returns the
// two lists flat, so this makes all four commands render alike.
Promote string
}
OptionFlag describes how one backend filter field is spelled on the command line.
type OptionFlagName ¶
type OptionFlagName struct {
Flag string
// Expected overrides the SDK's list of accepted values. It is set only
// where the CLI's vocabulary differs, as it does for the node sort field
// the CLI calls verificationCheck.
Expected string
}
OptionFlagName names the flag that carries an SDK option, and optionally the accepted values to list when the CLI spells them differently from the backend.
type OptionSection ¶
OptionSection groups the values one flag accepts under a heading that names it.
type OptionsRenderer ¶
type OptionsRenderer struct {
// consumers are the commands whose flags these options describe.
Consumers []string
// filters maps a backend filter field name to its flag. Fields missing from
// the map render under their backend name with no flag hint, so an endpoint
// that grows a new filter degrades to showing it rather than hiding it.
Filters map[string]OptionFlag
// sortFields renames backend sort fields the CLI spells differently.
SortFields map[string]string
// sortAccepted reports whether the CLI's --sort-by allowlist takes a field.
// Backends return sort fields for views the CLI cannot request, and those
// are called out rather than presented as usable.
SortAccepted func(field string) bool
// sortHidden reports whether a backend sort field should be left out of the
// listing altogether. It is for fields the API still advertises but has
// deprecated and is about to drop: unlike a field SortAccepted rejects,
// these do work today, so naming them at all would only invite scripts that
// break when the API removes them.
SortHidden func(field string) bool
// sortConsumers names the commands the endpoint's sorting block describes,
// when that is narrower than consumers. An endpoint can advertise the
// columns of one view while its filters apply to several.
SortConsumers []string
}
OptionsRenderer renders a shared options envelope grouped by the flag that consumes each filter, so the output reads as a list of things the user can type rather than a dump of backend field names.
func (OptionsRenderer) Write ¶
func (renderer OptionsRenderer) Write(w io.Writer, options nvfleetint.FilterOptions) error
Write renders the filter sections followed by the sorting flags.