Documentation
¶
Overview ¶
Package cmdutil provides the shared Factory and error types used by every command.
Index ¶
- Constants
- Variables
- func Annotate(cmd *cobra.Command, kv map[string]string) *cobra.Command
- func Annotation(cmd *cobra.Command, key string) string
- func AssertCheckoutHost(rawURL, source string) error
- func AssertCredentialHost(env, rawURL, source, canonical string) error
- func AssertHubHost(env, rawURL, source string) error
- func AssertOAuthHost(rawURL, source string) error
- func BindListFlags(fs *pflag.FlagSet, flags map[string]string) func() url.Values
- func CompleteEnumFlags(root *cobra.Command)
- func CompleteFirstArg(fn cobra.CompletionFunc) cobra.CompletionFunc
- func CompleteProfiles(f *Factory) cobra.CompletionFunc
- func DisplayHost(host string) string
- func FirstArg(args []string) string
- func Fprintf(w io.Writer, format string, a ...any)
- func MarkRequired(cmd *cobra.Command, names ...string) *cobra.Command
- func MaskSecret(s string) string
- func MaximumNArgs(n int) cobra.PositionalArgs
- func NoArgs(cmd *cobra.Command, args []string) error
- func OAuthBaseURL(host string) string
- func OpenBrowser(rawURL string) bool
- func PathSegment(name, value string) (string, error)
- func RequiredFlags(cmd *cobra.Command) map[string]bool
- func ServerValueError(what string, err error) error
- func Stub(cmd *cobra.Command) *cobra.Command
- func StubRunE(cmd *cobra.Command, _ []string) error
- func UnknownProfileError(name string) error
- func ValidateAmounts(cmd *cobra.Command, flags ...string) error
- func ValidateChoice(cmd *cobra.Command, flag string, allowed []string) error
- func ValidateChoices(cmd *cobra.Command, enums map[string][]string) error
- func ValidateCredentialOrigin(rawURL string) error
- func ValidateDates(cmd *cobra.Command, flags ...string) error
- func ValidateDays(cmd *cobra.Command, flags ...string) error
- func ValidateDestinationURL(rawURL, name string) error
- func ValidatePaging(cmd *cobra.Command) error
- type AuthError
- type ExitCode
- type ExitCoder
- type Factory
- func (f *Factory) Account() string
- func (f *Factory) ActiveEnv() string
- func (f *Factory) AskYesNo(label string, def bool) (bool, error)
- func (f *Factory) AssertSandboxBase(env, baseURL, source, canonicalBase string) error
- func (f *Factory) AssertSandboxOnly(command string) error
- func (f *Factory) AssertSandboxTarget() error
- func (f *Factory) CanPrompt() bool
- func (f *Factory) CheckExplicitProfile() error
- func (f *Factory) Confirm(label string) (bool, error)
- func (f *Factory) ConfirmMutation(action string, destructive bool) error
- func (f *Factory) ConfirmProdWrite(action string) error
- func (f *Factory) ErrPrintf(format string, a ...any)
- func (f *Factory) IdempotencyKey() (string, error)
- func (f *Factory) Input(label string) (string, error)
- func (f *Factory) InputOrArg(val, noun, label string) (string, error)
- func (f *Factory) InputOrFlag(val, flag, label string) (string, error)
- func (f *Factory) InputWithDefault(label, def string) (string, error)
- func (f *Factory) MultiSelectChoicesOrFlag(vals []string, flag, label string, choices []PromptChoice) ([]string, error)
- func (f *Factory) NotLoggedInError() error
- func (f *Factory) Password(label string) (string, error)
- func (f *Factory) PrintPageInfo(p *api.Pagination, shown int)
- func (f *Factory) Printf(format string, a ...any)
- func (f *Factory) ProductStore() (*product.Store, error)
- func (f *Factory) ProfileName(hosts *config.Hosts) string
- func (f *Factory) RenderOutput(data any, renderTable func() error) error
- func (f *Factory) RenderTable(t *jsonfmt.Table) error
- func (f *Factory) SecretFromFlag(val, flag string) (string, error)
- func (f *Factory) SelectChoiceOrFlag(val, flag, label string, choices []PromptChoice) (string, error)
- func (f *Factory) SelectOrFlag(val, flag, label string, options []string) (string, error)
- func (f *Factory) StaleTokenRefresh() error
- func (f *Factory) SuccessIcon() string
- func (f *Factory) Target() string
- func (f *Factory) TokenForProfile(explicit string) (host, accessToken string, err error)
- func (f *Factory) UseSandbox(product string) error
- func (f *Factory) YesNo(on bool) string
- type FlagError
- type GlobalOptions
- type NotImplementedError
- type PromptChoice
- type ScopeError
- type SilentError
Constants ¶
const ( AnnImplemented = "sepay:implemented" // "no" when the command has no backend yet AnnEnvs = "sepay:envs" // "sandbox" when production is refused, else unset (both) // AnnDestructive marks a command whose effect no other command can undo. AnnDestructive = "sepay:destructive" // "irreversible", or unset // AnnConfirms marks a command that prompts even in sandbox, so it needs --yes unattended. AnnConfirms = "sepay:confirms" // "always" | "conditional", or unset AnnScope = "sepay:scope" // capability scope required on the production host AnnGuidance = "sepay:guidance" // extra [Agent guidance] line for this command // AnnRequired lists flags a non-interactive run needs; written only by MarkRequired. AnnRequired = "sepay:required" // AnnValueFlag names a flag taking the positional's value, for values that look like switch words. AnnValueFlag = "sepay:value-flag" )
Annotation keys read by help, `sepay --map` and `sepay docs capabilities`.
const ClientID = "sepay-cli"
ClientID identifies the CLI as the registered public OAuth client.
const MaxPerPage = 100
MaxPerPage is the largest page size; above it the API silently falls back to 20.
Variables ¶
var ErrInterrupted error = interruptedError{}
ErrInterrupted reports that the user pressed Ctrl+C.
var ErrSilent = errors.New("silent error")
ErrSilent signals "already printed": the caller only sets the exit code.
var ErrTokenRefreshUnreachable = errors.New("could not reach the OAuth host to refresh the access token")
ErrTokenRefreshUnreachable marks a refresh that never reached the OAuth host; the grant may still be valid.
Functions ¶
func Annotation ¶
Annotation returns cmd's value for key, falling back to the nearest ancestor.
func AssertCheckoutHost ¶
AssertCheckoutHost refuses to open a browser at a non-SePay checkout URL.
func AssertCredentialHost ¶
AssertCredentialHost refuses to send a credential anywhere but canonical's host for env, or loopback. Run after ValidateCredentialOrigin.
func AssertHubHost ¶
AssertHubHost refuses to send a listen_key anywhere but env's SSE hub or loopback.
func AssertOAuthHost ¶
AssertOAuthHost is AssertCredentialHost for the env-independent OAuth host.
func BindListFlags ¶
BindListFlags registers each flag plus --page/--per-page and returns a collector of the non-empty values. A flag's query param is its name with dashes as underscores.
func CompleteEnumFlags ¶
CompleteEnumFlags makes every flag whose help lists its values complete to exactly those values, so help and completion cannot drift. A flag with its own completion keeps it.
func CompleteFirstArg ¶
func CompleteFirstArg(fn cobra.CompletionFunc) cobra.CompletionFunc
CompleteFirstArg completes the first positional argument with fn and offers nothing after it.
func CompleteProfiles ¶
func CompleteProfiles(f *Factory) cobra.CompletionFunc
CompleteProfiles completes stored profile names.
func DisplayHost ¶
DisplayHost is the inverse of OAuthBaseURL: it drops an implicit https://.
func Fprintf ¶
Fprintf writes a human line to w, stripping terminal control sequences from string arguments. An escape in a server value could otherwise overwrite what the user reads.
func MarkRequired ¶
MarkRequired marks flags required when the command cannot prompt, in help and `--map=json`. Only for unconditionally required flags.
func MaskSecret ¶
MaskSecret reduces a secret to an idempotent ****last4 hint, in every output format.
func MaximumNArgs ¶
func MaximumNArgs(n int) cobra.PositionalArgs
MaximumNArgs is cobra.MaximumNArgs with the same switch-word reading, limited to the command's own flags because globals like --yes ride on every call.
func OAuthBaseURL ¶
OAuthBaseURL turns a bare host into an https base URL, keeping an explicit scheme.
func OpenBrowser ¶
OpenBrowser opens an http/https rawURL via a fixed launcher (never a shell) and reports whether it started. A false result makes the caller print the URL instead.
func PathSegment ¶
PathSegment escapes value as one URL path segment, refusing empty, ".", ".." or a slash, checked before and after percent-decoding since the server decodes before routing.
func RequiredFlags ¶
RequiredFlags returns the flags MarkRequired declared on cmd, as a set.
func ServerValueError ¶
ServerValueError re-reports a validator's FlagError on a server-supplied value as an ordinary error, so the caller is not blamed with exit 2.
func UnknownProfileError ¶
UnknownProfileError reports a named profile with no stored entry, as a usage error.
func ValidateAmounts ¶
ValidateAmounts rejects a money filter that is not a non-negative integer; the API ignores malformed ones.
func ValidateChoice ¶
ValidateChoice rejects a changed flag whose value is outside the allowed set.
func ValidateChoices ¶
ValidateChoices applies ValidateChoice to each flag/allowed-set pair.
func ValidateCredentialOrigin ¶
ValidateCredentialOrigin rejects an origin unsafe for a credential: no host, userinfo, a non-http(s) scheme, or http off loopback. Errors never echo rawURL, which may carry a secret; callers must not either.
func ValidateDates ¶
ValidateDates rejects a date filter matching none of dateLayouts; the API ignores malformed ones.
func ValidateDays ¶
ValidateDays is ValidateDates for endpoints that accept only a bare date or colon-less timestamp.
func ValidateDestinationURL ¶
ValidateDestinationURL rejects a delivery URL the API is certain to refuse: unparsable, hostless, or not http(s). It does no DNS checks.
func ValidatePaging ¶
ValidatePaging rejects an out-of-range --page or --per-page.
Types ¶
type AuthError ¶
type AuthError struct {
Err error
}
AuthError marks a failure caused by having no usable credential.
type ExitCode ¶
type ExitCode int
ExitCode is the process exit code, per command-reference.md (Exit codes).
const ( ExitOK ExitCode = 0 // success ExitError ExitCode = 1 // generic error ExitUsage ExitCode = 2 // usage / bad flags ExitNotImplemented ExitCode = 3 // command exists but has no backend yet ExitAuth ExitCode = 4 // not authenticated (run sepay login) ExitScope ExitCode = 5 // token lacks the scope; the caller can widen it ExitForward ExitCode = 6 // local handler forward failed ExitOTP ExitCode = 7 // OTP required / invalid ExitBlocked ExitCode = 8 // blocked by account config or in-app permission ExitInterrupted ExitCode = 130 // interrupted by Ctrl+C )
Exit codes returned by the CLI.
func ExitCodeForError ¶
ExitCodeForError classifies err into an ExitCode without printing anything.
func HandleError ¶
HandleError prints err to stderr (errorOutput under machine output) and returns its exit code.
type ExitCoder ¶
type ExitCoder interface {
ExitCode() ExitCode
}
ExitCoder lets an error declare its own exit code.
type Factory ¶
type Factory struct {
IOStreams *iostreams.IOStreams
Global *GlobalOptions
// RawArgs is os.Args[1:]; HandleError reads the output format from it when flag parsing stopped early.
RawArgs []string
// Config, Credentials and NewAPIClient are lazy.
Config func() (*config.Config, error)
Credentials func() (*auth.Manager, error)
NewAPIClient func() (*api.Client, error)
// ProductManager brokers product-native credentials (pg/einvoice/bankhub).
ProductManager func() (*product.Manager, error)
// NewPGClient, NewBankHubClient and NewEInvoiceClient build product v1 clients on broker-minted credentials.
NewPGClient func() (*pg.Client, error)
NewBankHubClient func() (*bankhub.Client, error)
NewEInvoiceClient func() (*einvoice.Client, error)
// NewOAuthClient builds a device-flow client for host; SEPAY_OAUTH_URL overrides it.
NewOAuthClient func(host string) *auth.Client
// contains filtered or unexported fields
}
Factory supplies each command's IO, config and API clients.
func (*Factory) Account ¶
Account identifies the authenticated account as email@host, falling back to the profile name.
func (*Factory) AskYesNo ¶
AskYesNo prompts for yes/no, returning def on Enter; --yes does not answer it. Call only after CanPrompt.
func (*Factory) AssertSandboxBase ¶
AssertSandboxBase is AssertSandboxTarget for a product client's own base URL.
func (*Factory) AssertSandboxOnly ¶
AssertSandboxOnly refuses a mutation with no production endpoint yet; it never rewrites the env.
func (*Factory) AssertSandboxTarget ¶
AssertSandboxTarget refuses a sandbox command whose resolved API host is not a sandbox host, since --api-base and SEPAY_SANDBOX_API_URL can point it at production.
func (*Factory) CheckExplicitProfile ¶
CheckExplicitProfile fails with "unknown profile" when a named profile has no entry.
func (*Factory) Confirm ¶
Confirm returns true under --yes, else prompts; unattended without --yes is a usage error.
func (*Factory) ConfirmMutation ¶
ConfirmMutation is the confirmation gate every mutating command calls.
func (*Factory) ConfirmProdWrite ¶
ConfirmProdWrite requires confirmation for a write on production; --yes skips the prompt, never OTP.
func (*Factory) IdempotencyKey ¶
IdempotencyKey returns the --idempotency-key value, validated against the server's charset, or a fresh key.
func (*Factory) InputOrArg ¶
InputOrArg is InputOrFlag for a positional argument; noun names it in the error.
func (*Factory) InputOrFlag ¶
InputOrFlag returns val, else prompts for free text, else a usage error naming flag.
func (*Factory) InputWithDefault ¶
InputWithDefault prompts for free text, returning def on Enter. Call only after CanPrompt.
func (*Factory) MultiSelectChoicesOrFlag ¶
func (f *Factory) MultiSelectChoicesOrFlag(vals []string, flag, label string, choices []PromptChoice) ([]string, error)
MultiSelectChoicesOrFlag returns vals, else prompts for choices, else a usage error naming flag.
func (*Factory) NotLoggedInError ¶
NotLoggedInError returns the error for a run with no usable credential.
func (*Factory) Password ¶
Password prompts for a secret without echoing it. Call only after CanPrompt.
func (*Factory) PrintPageInfo ¶
func (f *Factory) PrintPageInfo(p *api.Pagination, shown int)
PrintPageInfo writes a pagination summary to stderr. Machine output stays quiet unless rows were left behind: a bare array would otherwise read as the whole set.
func (*Factory) ProductStore ¶
ProductStore returns the product-credential cache, evicted on login/logout so a reused label can't leak a prior tenant's.
func (*Factory) ProfileName ¶
ProfileName returns the profile to act on: --profile > SEPAY_PROFILE > active profile.
func (*Factory) RenderOutput ¶
RenderOutput prints data as JSON/YAML for machine output, or calls renderTable.
func (*Factory) RenderTable ¶
RenderTable styles the header, fits the table to the terminal and writes it to stdout.
func (*Factory) SecretFromFlag ¶
SecretFromFlag reads the secret from stdin when val is "-", keeping it out of argv and shell history. An inline value still works but warns.
func (*Factory) SelectChoiceOrFlag ¶
func (f *Factory) SelectChoiceOrFlag(val, flag, label string, choices []PromptChoice) (string, error)
SelectChoiceOrFlag returns val, else prompts for one choice, else a usage error naming flag.
func (*Factory) SelectOrFlag ¶
SelectOrFlag returns val, else prompts for one of options, else a usage error listing them.
func (*Factory) StaleTokenRefresh ¶
StaleTokenRefresh reports whether the last client's token went out stale because refresh was unreachable.
func (*Factory) SuccessIcon ¶
SuccessIcon returns a check mark, green when color is on.
func (*Factory) TokenForProfile ¶
TokenForProfile returns the OAuth host and a valid access token for a profile, refreshing if lapsed.
func (*Factory) UseSandbox ¶
UseSandbox pins a sandbox-only product to sandbox, rejecting --env production and production hosts.
type FlagError ¶
type FlagError struct {
Err error
}
FlagError marks a misused flag/argument as a usage error.
type GlobalOptions ¶
type GlobalOptions struct {
Profile string // --profile/-p
Env string // --env: "" (use config), "sandbox" or "production"
Output string // --output/-o: table|json|yaml
Yes bool // --yes/-y
Quiet bool // --quiet/-q
Verbose bool // --verbose/-v
NoColor bool // --no-color
NoInput bool // --no-input
ConfigPath string // --config
APIBase string // --api-base
IdempotencyKey string // --idempotency-key: reuse one key across attempts of the same mutation
}
GlobalOptions holds persistent-flag values, read lazily by the Factory closures.
type NotImplementedError ¶
type NotImplementedError struct{ Path string }
NotImplementedError reports a command whose backend does not exist yet.
func (NotImplementedError) Error ¶
func (e NotImplementedError) Error() string
func (NotImplementedError) ExitCode ¶
func (e NotImplementedError) ExitCode() ExitCode
ExitCode returns ExitNotImplemented.
type PromptChoice ¶
PromptChoice is one option: Label is shown, Value is returned.
type ScopeError ¶
type ScopeError struct {
Err error
}
ScopeError marks a failure caused by the token's scopes.
func (ScopeError) Error ¶
func (e ScopeError) Error() string
func (ScopeError) Unwrap ¶
func (e ScopeError) Unwrap() error
type SilentError ¶
type SilentError struct{ Code ExitCode }
SilentError is an already-printed error carrying only its exit code.
func (SilentError) Error ¶
func (SilentError) Error() string
func (SilentError) ExitCode ¶
func (e SilentError) ExitCode() ExitCode
ExitCode returns the carried exit code.