Documentation
¶
Overview ¶
Package cmdutil is the one path from a command's result to stdout. A command returns its value; cmdutil applies --query and renders it in the format -o selected. stdout carries only that value: progress, hints and confirmations go to stderr.
Index ¶
- Constants
- Variables
- func AddPageFlags(cmd *cobra.Command, pf *PageFlags, defaultPageSize, defaultMaxItems int)
- func AddWaitFlags(cmd *cobra.Command, wf *WaitFlags, what string, defaultTimeout time.Duration)
- func Annotate(cmd *cobra.Command, key, value string) *cobra.Command
- func Cancelled(cmd *cobra.Command, err error) error
- func CheckQuery(cmd *cobra.Command) error
- func Confirm(prompt string, yes bool) (bool, error)
- func Deref[T any](p *T) T
- func DerefOr[T any](p *T, fallback T) T
- func EnumValues(f *pflag.Flag) []string
- func FlagEnum(cmd *cobra.Command, name string, values ...string)
- func Format(cmd *cobra.Command) string
- func Human(cmd *cobra.Command) bool
- func JobFailed(message string, job any) error
- func Local() map[string]string
- func ParseTimeArg(flag, v string, now time.Time) (time.Time, error)
- func Poll(ctx context.Context, opts PollOptions, ...) error
- func Print(cmd *cobra.Command, value any) error
- func ReadItems(src ItemSource) ([]string, error)
- func ReadText(stdin io.Reader, value, path, what string) (string, error)
- func Reads() map[string]string
- func Renamed(cmd *cobra.Command, newPath string) *cobra.Command
- func Run(fn RunFunc) func(*cobra.Command, []string) error
- func SleepContext(ctx context.Context, d time.Duration) error
- func Stderr(cmd *cobra.Command) io.Writer
- func Writes() map[string]string
- type Effect
- type FetchFunc
- type ItemSource
- type Page
- type PageFlags
- type PollOptions
- type RunFunc
- type SavedFile
- type WaitFlags
Constants ¶
const ( // AnnotationEffect holds the command's Effect. AnnotationEffect = "norcube/effect" // AnnotationService holds the registry key of the service a command // (and every command below it) talks to, for commands outside a // product group (sign-in, organizations). Product groups don't need // it: their name is the registry entry's `command`. AnnotationService = "norcube/service" // AnnotationNoResult marks a command that prints no result on stdout // (it hands the terminal to another program), so -o doesn't apply. AnnotationNoResult = "norcube/no-result" // AnnotationFlagEnum is the flag annotation listing a flag's allowed // values. AnnotationFlagEnum = "norcube/enum" )
Annotation keys. Values are part of the `norcube commands` schema, so they only ever gain new values.
const AnnotationRenamedTo = "norcube/renamed-to"
AnnotationRenamedTo records where a renamed command moved.
const EnvDeprecationWarnings = "NORCUBE_DEPRECATION_WARNINGS"
EnvDeprecationWarnings turns on notes about renamed commands. Off by default until v1.0, so renames don't add noise to existing scripts.
Variables ¶
var ErrCancelled = errors.New("cancelled by user")
ErrCancelled is returned by interactive helpers when the user dismisses a prompt. Commands report it as "Cancelled." instead of an error.
var ErrWaitTimeout error = &clierr.Error{ Code: clierr.CodeTimeout, Message: "stopped waiting: the job is still running on the server", Hint: "Check on it later, or wait longer with --wait-timeout.", }
ErrWaitTimeout is returned by Poll when Timeout passes before check reports done. The job is still running on the server.
Functions ¶
func AddPageFlags ¶
AddPageFlags registers --page-size (alias --limit), --cursor, --all-pages and --max-items. A defaultPageSize of 0 means the API picks the page size, and --page-size isn't offered.
func AddWaitFlags ¶ added in v0.19.0
AddWaitFlags registers --wait and --wait-timeout.
func Cancelled ¶ added in v0.20.0
Cancelled ends a command whose confirmation (Confirm) was declined or dismissed: "Cancelled." on stderr and a clean exit. Other errors pass through. Use it as `if err != nil || !ok { return nil, Cancelled(cmd, err) }`.
func CheckQuery ¶
CheckQuery fails with a usage error when --query doesn't parse, before the command does any work.
func Confirm ¶ added in v0.17.0
Confirm asks a yes/no question. yes answers it without prompting; without a terminal it fails with a usage error that asks for --yes, so a script never deletes anything by accident.
func Deref ¶ added in v0.17.0
func Deref[T any](p *T) T
Deref returns *p, or the zero value for nil (generated API models use pointers for optional fields).
func DerefOr ¶ added in v0.17.0
func DerefOr[T any](p *T, fallback T) T
DerefOr returns *p, or fallback for nil.
func EnumValues ¶ added in v0.22.0
EnumValues are the values FlagEnum recorded for f, or nil.
func FlagEnum ¶ added in v0.22.0
FlagEnum declares the only values a flag accepts: shell completion offers them, and the command tree lists them. The flag must already be defined on cmd (as a local or persistent flag); validating the value and naming the values in the description stay with the command.
func Human ¶
Human reports whether the output is for a person (table), so commands may add notes to stderr that a script wouldn't want.
func JobFailed ¶ added in v0.20.0
JobFailed is the error of a command that waited for a job (--wait) which ended unsuccessfully: exit 1 with code job_failed, so a script can tell "the backup failed" from "the CLI failed". job is the job as last seen, included in the JSON error as details.
func ParseTimeArg ¶ added in v0.19.0
ParseTimeArg reads a point in time from a flag such as --since: an RFC 3339 timestamp, a date (YYYY-MM-DD, midnight local time), or an age before now ("90m", "24h", "7d"). The result is UTC.
func Poll ¶ added in v0.19.0
func Poll(ctx context.Context, opts PollOptions, check func(ctx context.Context) (done bool, err error)) error
Poll calls check until it reports done, an error, the context ends (Ctrl-C), or the timeout passes. The delay between calls starts at Interval and grows by half each time up to MaxInterval, so a long job doesn't flood the API while a short one finishes promptly.
func Print ¶
Print renders value to the command's stdout. Tables page through $PAGER on a terminal unless --no-pager.
func ReadItems ¶ added in v0.19.0
func ReadItems(src ItemSource) ([]string, error)
ReadItems returns the items of src: one per argument or per line, with surrounding space trimmed, blank lines and lines starting with "#" skipped, and duplicates removed (first occurrence wins, order kept). Arguments and a file can't be combined.
func ReadText ¶ added in v0.20.0
ReadText returns value, or the contents of path when path is set ("-" is stdin). A single trailing newline is dropped, so `echo ... |` works. what names the text in errors ("the prompt").
func Reads ¶ added in v0.22.0
Reads, Writes and Local are the Annotations of a command with that Effect: `Annotations: cmdutil.Writes(),` in the command literal.
func Renamed ¶ added in v0.17.0
Renamed marks cmd as the old name of a command that moved to newPath (e.g. "norcube backup jobs list"). The old name keeps working but is hidden from help and the reference docs; with NORCUBE_DEPRECATION_WARNINGS=1 it prints a one-line note to stderr.
func SleepContext ¶ added in v0.19.0
SleepContext waits for d or until ctx ends, whichever is first.
Types ¶
type Effect ¶ added in v0.22.0
type Effect string
Effect says what running a command changes. Every visible command declares one (TestEveryCommandDeclaresAnEffect).
const ( // EffectRead changes nothing on the servers or in the CLI's own state. // It may create a new file the user asked for (a download, an export) // and refresh caches, but never overwrites anything. EffectRead Effect = "read" // EffectWrite changes state on a Norcube service (creates, updates, // deletes, starts a job, signs in or out). It may change local state // as well. EffectWrite Effect = "write" // EffectLocal changes only local state: the config file, stored // credentials, project files or the installed binary. EffectLocal Effect = "local" )
func CommandEffect ¶ added in v0.22.0
CommandEffect is the Effect cmd declares, or "" when it declares none.
type FetchFunc ¶
type FetchFunc[T any] func(ctx context.Context, cursor string, pageSize int) (items []T, next string, err error)
FetchFunc gets one page starting at cursor ("" for the first).
type ItemSource ¶ added in v0.19.0
type ItemSource struct {
Args []string
// File is the --file value; "-" reads standard input.
File string
// Stdin is the command's input stream (cmd.InOrStdin()).
Stdin io.Reader
// Max caps how many items are accepted (0 = no cap); more is a usage
// error naming the cap, so a script never sends a silently cut list.
Max int
// What names the items in messages ("domains").
What string
}
ItemSource says where a command reads a list of items (domains, names, keys) from: positional arguments, a file (--file), or standard input ("-" as the only argument or --file -).
type Page ¶
type Page[T any] struct { Items []T // NextCursor continues where Items stop; empty on the last page. NextCursor string // Truncated: --all-pages stopped at the --max-items cap. Truncated bool Cap int }
Page is what Paginate collected.
func Paginate ¶
Paginate fetches one page, or with --all-pages every page up to --max-items. Items is never nil, so an empty list prints as [].
type PageFlags ¶
type PageFlags struct {
PageSize int
Cursor string
AllPages bool
MaxItems int
// contains filtered or unexported fields
}
PageFlags are the pagination flags every list command takes.
Lists print as plain arrays (the JSON shape scripts already rely on); when more results exist the next cursor goes to stderr: a sentence on a table, `nextCursor=<cursor>` for json, yaml and text, so a script can capture it with 2>.
type PollOptions ¶ added in v0.19.0
type PollOptions struct {
// Interval is the first delay between checks (default 1s).
Interval time.Duration
// MaxInterval caps the growing delay (default 15s).
MaxInterval time.Duration
// Timeout ends the wait with ErrWaitTimeout (0 = no limit).
Timeout time.Duration
// Sleep waits between checks; tests replace it. It must return early
// with ctx.Err() when ctx ends.
Sleep func(ctx context.Context, d time.Duration) error
}
PollOptions controls Poll. Zero values pick sensible defaults.
type RunFunc ¶
RunFunc is a command body that returns its result instead of printing. A nil result prints nothing (and is not "null").
type SavedFile ¶ added in v0.19.0
type SavedFile struct {
Path string `json:"path" yaml:"path"`
Bytes int64 `json:"bytes" yaml:"bytes"`
SHA256 string `json:"sha256" yaml:"sha256"`
}
SavedFile is the result of a command that writes a file: what -o json prints and what its success message describes.
func SaveStream ¶ added in v0.19.0
func SaveStream(cmd *cobra.Command, src io.Reader, dest string, perm os.FileMode) (*SavedFile, error)
SaveStream writes src to dest and returns what was written.
dest "-" streams the bytes to the command's standard output, for piping: they are the command's whole result, so it returns (nil, nil) and the caller prints nothing else.
Otherwise dest is created (never overwritten: an existing file is a usage error) with mode perm, and the SHA-256 of the content is computed on the way. A failed or interrupted write removes the partial file, so a truncated download never looks like a complete one.