Help us shape the future of Go! Take the 2026 Go Developer Survey

cmdutil

package
v2.17.1 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: BSD-3-Clause Imports: 30 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ShowAllLimit requests every item without the server pagination clamp.
	ShowAllLimit = -1

	// AllFlagUsage is the shared help text for the --all flag on list commands.
	AllFlagUsage = "Return every item, ignoring pagination"

	// StartFlagUsage documents offset rounding for database-backed resources.
	StartFlagUsage = "Offset for pagination (rounded down to a multiple of --limit on database-backed resources)"
)
View Source
const (
	ScopeRead        = "read"
	ScopeMerged      = "merged"
	ScopeFleet       = "fleet"
	ScopeDestination = "destination"
	ScopeResource    = "resource"
	ScopeGlobal      = "global"
)
View Source
const MaxPromptOptions = 20

MaxPromptOptions caps how many search matches the resolver offers interactively before asking the user to refine the query instead.

Variables

This section is empty.

Functions

func AbortUploadSession added in v2.9.0

func AbortUploadSession(ctx context.Context, c *client.Client, kind, sessionID string)

AbortUploadSession deletes a chunked upload session, ignoring errors. Use it when the consume step after a completed upload fails.

func AllowPrompt added in v2.16.0

func AllowPrompt(cmd *cobra.Command) bool

AllowPrompt reports whether interactive prompts are allowed for this command.

func AppendQuery added in v2.6.0

func AppendQuery(path string, extra url.Values) string

AppendQuery merges extra query parameters into a path, preserving any that are already present.

func ApplyPaginationParams

func ApplyPaginationParams(cmd *cobra.Command, path string, p ListParams) (string, error)

ApplyPaginationParams appends limit and start query params to a list path. It preserves any existing query parameters on the path.

func AssumeYes

func AssumeYes(cmd *cobra.Command) bool

AssumeYes reads the global --yes flag or invocation consent.

func ClientFromCommand

func ClientFromCommand(cmd *cobra.Command) (*client.Client, error)

ClientFromCommand returns a configured authenticated client for the command.

func Confirm

func Confirm(cmd *cobra.Command, label string) (bool, error)

Confirm prompts through ConfirmOrCancel unless invocation consent is already present.

func ConfirmOrCancel added in v2.16.0

func ConfirmOrCancel(cmd *cobra.Command, force bool, label string) (bool, error)

ConfirmOrCancel accepts force, --yes, or fleet consent; otherwise it requires text mode and terminal input. Declining prints Cancelled to stderr and returns false without an error.

func DecodeJSON

func DecodeJSON(resp *http.Response, out any) error

DecodeJSON decodes into out; callers must first enforce HTTP success with EnsureSuccessStatus.

func EffectiveLimit

func EffectiveLimit(cmd *cobra.Command, resource, flagName string, flagValue, fallbackDefault int) int

EffectiveLimit resolves explicit flag, resource config, global config, then fallback. ShowAllLimit passes through unchanged.

func EnsureSuccessStatus

func EnsureSuccessStatus(resp *http.Response) error

EnsureSuccessStatus returns an error for non-2xx responses.

func EnumVarP added in v2.16.0

func EnumVarP[T ~string](cmd *cobra.Command, flags *pflag.FlagSet, p *T, name, shorthand string, value T, usage string, allowed ...T)

EnumVarP registers a validated enum flag with shell completion and appends the choices to usage. The empty value is always allowed as unset; invalid nonempty defaults panic.

func ExclusiveFlags added in v2.16.0

func ExclusiveFlags(cmd *cobra.Command, names ...string) error

ExclusiveFlags rejects more than one changed flag set to a non-zero value for its type.

func JSONOutputEnabled

func JSONOutputEnabled(cmd *cobra.Command) bool

JSONOutputEnabled reads the parsed local or inherited --json flag, then runtime output mode. Runtime JSON mode includes --output json, even when --json is explicitly false.

func LooksLikeIDPrefix added in v2.10.0

func LooksLikeIDPrefix(identifierLower string) bool

LooksLikeIDPrefix reports whether identifier could be a hex ID prefix worth scanning the full list for.

func PrintJSON

func PrintJSON(v any) error

PrintJSON prints indented JSON to stdout.

func PrintRawJSON added in v2.6.0

func PrintRawJSON(body []byte) error

PrintRawJSON pretty-prints a raw JSON document, falling back to the bytes as-is.

func PrintTable added in v2.16.0

func PrintTable(cmd *cobra.Command, headers []string, rows [][]string, summaries ...TableSummary) error

PrintTable renders rows and an optional summary, collecting them during an environment preview.

func ReadJSONBody added in v2.6.0

func ReadJSONBody(resp *http.Response) ([]byte, error)

ReadJSONBody enforces HTTP and API success while retaining every response field.

func Run added in v2.16.0

func Run[T any](cmd *cobra.Command, c *client.Client, spec Spec[T]) error

Run enforces a success envelope and prints raw data in JSON mode or invokes Render in text mode.

func RunDelete added in v2.16.0

func RunDelete(cmd *cobra.Command, c *client.Client, spec DeleteSpec) error

RunDelete returns nil on cancellation, otherwise printing raw data in JSON mode or SuccessMessage in text mode.

func RunEnvironments added in v2.16.0

func RunEnvironments(cmd *cobra.Command, args []string, run func(*cobra.Command, []string) error, mutation bool) error

RunEnvironments executes a command sequentially and reports each environment's result.

func RunList added in v2.10.0

func RunList[T any](cmd *cobra.Command, c *client.Client, spec ListSpec[T]) error

RunList executes one standard list command as described by spec.

func RunMerged added in v2.16.1

func RunMerged(cmd *cobra.Command, args []string, run func(*cobra.Command, []string) error) error

func RunScoped added in v2.16.0

func RunScoped(cmd *cobra.Command, args []string, run func(*cobra.Command, []string) error) error

RunScoped reuses the command's requests and rendering for each selected environment.

func SetResource added in v2.16.0

func SetResource[D, S any](ref ResourceRef[D, S], commands ...*cobra.Command)

SetResource binds raw identifiers through a command-owned closure; call after assigning RunE.

func SetScope added in v2.16.0

func SetScope(scope string, commands ...*cobra.Command)

SetScope declares how commands behave when all-environments preview is enabled.

func UnauthClientFromCommand

func UnauthClientFromCommand(cmd *cobra.Command) (*client.Client, error)

UnauthClientFromCommand returns a configured unauthenticated client for the command.

func UploadFileInChunks added in v2.9.0

func UploadFileInChunks(ctx context.Context, c *client.Client, kind, filePath string, showProgress bool) (string, error)

UploadFileInChunks sends retried chunks with optional progress and aborts the session on failure. It returns the completed upload session ID.

Types

type DeleteSpec added in v2.16.0

type DeleteSpec struct {
	Force                                        bool
	Prompt, Path, FailureMessage, SuccessMessage string
	Body                                         any
}

DeleteSpec describes a confirmed DELETE with optional body and human-readable success output.

type EnumValue added in v2.16.0

type EnumValue[T ~string] struct {
	// contains filtered or unexported fields
}

EnumValue implements a string flag restricted to the choices registered by EnumVarP.

func (*EnumValue[T]) Set added in v2.16.0

func (v *EnumValue[T]) Set(value string) error

Set matches the allowed choices case-insensitively and rejects others without changing the destination.

func (*EnumValue[T]) String added in v2.16.0

func (v *EnumValue[T]) String() string

String returns the current flag value.

func (*EnumValue[T]) Type added in v2.16.0

func (v *EnumValue[T]) Type() string

Type keeps enum flags compatible with pflag's GetString accessor.

type HTTPStatusError

type HTTPStatusError struct {
	StatusCode int
	Body       string
}

HTTPStatusError represents a non-2xx HTTP response.

func (*HTTPStatusError) Error

func (e *HTTPStatusError) Error() string

type ListParams added in v2.6.0

type ListParams struct {
	// Resource is the canonical resource name used to look up a configured
	// per-resource limit.
	Resource string
	// Limit is the value of the command's --limit flag.
	Limit int
	// FallbackDefault applies when neither the flag nor config supplies a limit.
	FallbackDefault int
	// Start is the value of the command's --start flag.
	Start int
	// All requests every item, ignoring pagination entirely.
	All bool
}

ListParams describes how a list command wants its results paginated.

type ListSpec added in v2.10.0

type ListSpec[T any] struct {
	// Resource names the collection in error messages and the trailing
	// "Showing x of y <resource>" line.
	Resource string
	// Endpoint is the list path (environment already applied).
	Endpoint string
	// Params configures pagination from the command's flags.
	Params ListParams
	// Query holds extra query parameters, applied after pagination.
	Query url.Values

	Headers []string
	Row     func(T) []string
}

ListSpec describes a paginated list with raw JSON passthrough or table rendering.

type ResourceRef added in v2.10.0

type ResourceRef[D any, S any] struct {
	EnvironmentScoped bool
	// Singular and Plural name the resource in prompts and error messages
	// ("container", "containers").
	Singular string
	Plural   string
	// IDHint completes "use <IDHint> or run `<ListCmd>`" guidance
	// ("the container ID", "the volume name").
	IDHint  string
	ListCmd string

	// GetPath builds the GET-by-identifier path; ListPath the list endpoint
	// that Resolve queries with ?search=<identifier>&limit=-1.
	GetPath  func(envID, identifier string) string
	ListPath func(envID string) string
	// SearchCandidates replaces the standard list search for resources with
	// specialized matching rules.
	SearchCandidates func(context.Context, *client.Client, string) ([]S, error)
	// SelectCandidate replaces the standard ambiguity handling while keeping
	// direct lookup and not-found behavior in Resolve.
	SelectCandidate func([]S, string, bool) (*S, error)
	// Validate checks a successful direct lookup before Resolve returns it.
	Validate func(D, string) error

	// Matches reports whether a listed item matches the identifier.
	Matches func(item S, identifierLower, original string) bool
	// Label renders one match as an interactive prompt option.
	Label func(S) string
	// Promote converts a selected summary into the detail shape.
	Promote func(S) *D

	// IDOf enables an ID-prefix scan over the full list. Leave nil for resources without opaque IDs.
	IDOf func(S) string
	// IdentifierOf supplies the canonical identifier for commands accepting raw IDs.
	IdentifierOf func(D) string

	// Exact identifies exact matches so a unique exact search result wins over substring matches.
	Exact func(item S, identifierLower, original string) bool
}

ResourceRef resolves a resource from a name, ID, or prefix. D is the detail shape and S is the list summary.

func (ResourceRef[D, S]) Fetch added in v2.16.0

func (ref ResourceRef[D, S]) Fetch(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*D, error)

Fetch resolves an identifier and retrieves full detail when resolution returned only a summary.

func (ResourceRef[D, S]) Resolve added in v2.10.0

func (ref ResourceRef[D, S]) Resolve(ctx context.Context, c *client.Client, identifier string, allowPrompt bool) (*D, bool, error)

Resolve finds one resource and pins its environment for subsequent requests.

type Spec added in v2.16.0

type Spec[T any] struct {
	Method, Path, FailureMessage string
	Body                         any
	Timeout                      time.Duration
	Render                       func(T) error
}

Spec describes a request with raw JSON data output or typed text rendering. Render is required in text mode; a nil Render returns a programmer error before requesting.

type TableSummary added in v2.16.0

type TableSummary struct {
	Resource  string
	Total     int64
	Paginated bool
}

Jump to

Keyboard shortcuts

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