cmdutil

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: Apache-2.0 Imports: 30 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package cmdutil provides the shared Factory and error types used by every command.

Index

Constants

View Source
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`.

View Source
const ClientID = "sepay-cli"

ClientID identifies the CLI as the registered public OAuth client.

View Source
const MaxPerPage = 100

MaxPerPage is the largest page size; above it the API silently falls back to 20.

Variables

View Source
var ErrInterrupted error = interruptedError{}

ErrInterrupted reports that the user pressed Ctrl+C.

View Source
var ErrSilent = errors.New("silent error")

ErrSilent signals "already printed": the caller only sets the exit code.

View Source
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 Annotate

func Annotate(cmd *cobra.Command, kv map[string]string) *cobra.Command

Annotate merges kv into cmd's annotations and returns cmd.

func Annotation

func Annotation(cmd *cobra.Command, key string) string

Annotation returns cmd's value for key, falling back to the nearest ancestor.

func AssertCheckoutHost

func AssertCheckoutHost(rawURL, source string) error

AssertCheckoutHost refuses to open a browser at a non-SePay checkout URL.

func AssertCredentialHost

func AssertCredentialHost(env, rawURL, source, canonical string) error

AssertCredentialHost refuses to send a credential anywhere but canonical's host for env, or loopback. Run after ValidateCredentialOrigin.

func AssertHubHost

func AssertHubHost(env, rawURL, source string) error

AssertHubHost refuses to send a listen_key anywhere but env's SSE hub or loopback.

func AssertOAuthHost

func AssertOAuthHost(rawURL, source string) error

AssertOAuthHost is AssertCredentialHost for the env-independent OAuth host.

func BindListFlags

func BindListFlags(fs *pflag.FlagSet, flags map[string]string) func() url.Values

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

func CompleteEnumFlags(root *cobra.Command)

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

func DisplayHost(host string) string

DisplayHost is the inverse of OAuthBaseURL: it drops an implicit https://.

func FirstArg

func FirstArg(args []string) string

FirstArg returns args[0], or "".

func Fprintf

func Fprintf(w io.Writer, format string, a ...any)

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

func MarkRequired(cmd *cobra.Command, names ...string) *cobra.Command

MarkRequired marks flags required when the command cannot prompt, in help and `--map=json`. Only for unconditionally required flags.

func MaskSecret

func MaskSecret(s string) string

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 NoArgs

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

NoArgs is cobra.NoArgs but reports a stray "on"/"off" as bool-flag syntax.

func OAuthBaseURL

func OAuthBaseURL(host string) string

OAuthBaseURL turns a bare host into an https base URL, keeping an explicit scheme.

func OpenBrowser

func OpenBrowser(rawURL string) bool

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

func PathSegment(name, value string) (string, error)

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

func RequiredFlags(cmd *cobra.Command) map[string]bool

RequiredFlags returns the flags MarkRequired declared on cmd, as a set.

func ServerValueError

func ServerValueError(what string, err error) error

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 Stub

func Stub(cmd *cobra.Command) *cobra.Command

Stub hides cmd from help but keeps it invocable (exit 3) and visible in `--map`.

func StubRunE

func StubRunE(cmd *cobra.Command, _ []string) error

StubRunE is the RunE for a not-yet-built command.

func UnknownProfileError

func UnknownProfileError(name string) error

UnknownProfileError reports a named profile with no stored entry, as a usage error.

func ValidateAmounts

func ValidateAmounts(cmd *cobra.Command, flags ...string) error

ValidateAmounts rejects a money filter that is not a non-negative integer; the API ignores malformed ones.

func ValidateChoice

func ValidateChoice(cmd *cobra.Command, flag string, allowed []string) error

ValidateChoice rejects a changed flag whose value is outside the allowed set.

func ValidateChoices

func ValidateChoices(cmd *cobra.Command, enums map[string][]string) error

ValidateChoices applies ValidateChoice to each flag/allowed-set pair.

func ValidateCredentialOrigin

func ValidateCredentialOrigin(rawURL string) error

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

func ValidateDates(cmd *cobra.Command, flags ...string) error

ValidateDates rejects a date filter matching none of dateLayouts; the API ignores malformed ones.

func ValidateDays

func ValidateDays(cmd *cobra.Command, flags ...string) error

ValidateDays is ValidateDates for endpoints that accept only a bare date or colon-less timestamp.

func ValidateDestinationURL

func ValidateDestinationURL(rawURL, name string) error

ValidateDestinationURL rejects a delivery URL the API is certain to refuse: unparsable, hostless, or not http(s). It does no DNS checks.

func ValidatePaging

func ValidatePaging(cmd *cobra.Command) error

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.

func (AuthError) Error

func (e AuthError) Error() string

func (AuthError) ExitCode

func (e AuthError) ExitCode() ExitCode

ExitCode returns ExitAuth.

func (AuthError) Unwrap

func (e AuthError) Unwrap() error

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

func ExitCodeForError(err error) ExitCode

ExitCodeForError classifies err into an ExitCode without printing anything.

func HandleError

func HandleError(f *Factory, err error) ExitCode

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 New

func New() *Factory

New builds the real Factory wired to the OS environment.

func (*Factory) Account

func (f *Factory) Account() string

Account identifies the authenticated account as email@host, falling back to the profile name.

func (*Factory) ActiveEnv

func (f *Factory) ActiveEnv() string

ActiveEnv returns the environment the next API call targets.

func (*Factory) AskYesNo

func (f *Factory) AskYesNo(label string, def bool) (bool, error)

AskYesNo prompts for yes/no, returning def on Enter; --yes does not answer it. Call only after CanPrompt.

func (*Factory) AssertSandboxBase

func (f *Factory) AssertSandboxBase(env, baseURL, source, canonicalBase string) error

AssertSandboxBase is AssertSandboxTarget for a product client's own base URL.

func (*Factory) AssertSandboxOnly

func (f *Factory) AssertSandboxOnly(command string) error

AssertSandboxOnly refuses a mutation with no production endpoint yet; it never rewrites the env.

func (*Factory) AssertSandboxTarget

func (f *Factory) AssertSandboxTarget() error

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) CanPrompt

func (f *Factory) CanPrompt() bool

CanPrompt reports whether an interactive prompt is possible.

func (*Factory) CheckExplicitProfile

func (f *Factory) CheckExplicitProfile() error

CheckExplicitProfile fails with "unknown profile" when a named profile has no entry.

func (*Factory) Confirm

func (f *Factory) Confirm(label string) (bool, error)

Confirm returns true under --yes, else prompts; unattended without --yes is a usage error.

func (*Factory) ConfirmMutation

func (f *Factory) ConfirmMutation(action string, destructive bool) error

ConfirmMutation is the confirmation gate every mutating command calls.

func (*Factory) ConfirmProdWrite

func (f *Factory) ConfirmProdWrite(action string) error

ConfirmProdWrite requires confirmation for a write on production; --yes skips the prompt, never OTP.

func (*Factory) ErrPrintf

func (f *Factory) ErrPrintf(format string, a ...any)

ErrPrintf is Fprintf to stderr.

func (*Factory) IdempotencyKey

func (f *Factory) IdempotencyKey() (string, error)

IdempotencyKey returns the --idempotency-key value, validated against the server's charset, or a fresh key.

func (*Factory) Input

func (f *Factory) Input(label string) (string, error)

Input prompts for optional free text. Call only after CanPrompt.

func (*Factory) InputOrArg

func (f *Factory) InputOrArg(val, noun, label string) (string, error)

InputOrArg is InputOrFlag for a positional argument; noun names it in the error.

func (*Factory) InputOrFlag

func (f *Factory) InputOrFlag(val, flag, label string) (string, error)

InputOrFlag returns val, else prompts for free text, else a usage error naming flag.

func (*Factory) InputWithDefault

func (f *Factory) InputWithDefault(label, def string) (string, error)

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

func (f *Factory) NotLoggedInError() error

NotLoggedInError returns the error for a run with no usable credential.

func (*Factory) Password

func (f *Factory) Password(label string) (string, error)

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) Printf

func (f *Factory) Printf(format string, a ...any)

Printf is Fprintf to stdout.

func (*Factory) ProductStore

func (f *Factory) ProductStore() (*product.Store, error)

ProductStore returns the product-credential cache, evicted on login/logout so a reused label can't leak a prior tenant's.

func (*Factory) ProfileName

func (f *Factory) ProfileName(hosts *config.Hosts) string

ProfileName returns the profile to act on: --profile > SEPAY_PROFILE > active profile.

func (*Factory) RenderOutput

func (f *Factory) RenderOutput(data any, renderTable func() error) error

RenderOutput prints data as JSON/YAML for machine output, or calls renderTable.

func (*Factory) RenderTable

func (f *Factory) RenderTable(t *jsonfmt.Table) error

RenderTable styles the header, fits the table to the terminal and writes it to stdout.

func (*Factory) SecretFromFlag

func (f *Factory) SecretFromFlag(val, flag string) (string, error)

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

func (f *Factory) SelectOrFlag(val, flag, label string, options []string) (string, error)

SelectOrFlag returns val, else prompts for one of options, else a usage error listing them.

func (*Factory) SetContext added in v0.1.1

func (f *Factory) SetContext(ctx context.Context)

SetContext gives the factory the running command's context, for work started outside a command's own calls.

func (*Factory) StaleTokenRefresh

func (f *Factory) StaleTokenRefresh() error

StaleTokenRefresh reports whether the last client's token went out stale because refresh was unreachable.

func (*Factory) SuccessIcon

func (f *Factory) SuccessIcon() string

SuccessIcon returns a check mark, green when color is on.

func (*Factory) Target

func (f *Factory) Target() string

Target returns a "host (env)" summary of the next API call's destination.

func (*Factory) TokenForProfile

func (f *Factory) TokenForProfile(explicit string) (host, accessToken string, err error)

TokenForProfile returns the OAuth host and a valid access token for a profile, refreshing if lapsed.

func (*Factory) UseSandbox

func (f *Factory) UseSandbox(product string) error

UseSandbox pins a sandbox-only product to sandbox, rejecting --env production and production hosts.

func (*Factory) WarnPlaintextStorage added in v0.1.1

func (f *Factory) WarnPlaintextStorage(subject, path string, keychainFailed bool)

WarnPlaintextStorage tells the user, in plain words and in yellow, that subject landed in the 0600 file at path. keychainFailed is set only by the login that just fell back to the file; a file chosen earlier (--insecure-storage, or the profile's stored choice) gets the one-line form.

func (*Factory) YesNo

func (f *Factory) YesNo(on bool) string

YesNo renders a boolean as colored "yes"/"no".

type FlagError

type FlagError struct {
	Err error
}

FlagError marks a misused flag/argument as a usage error.

func (*FlagError) Error

func (e *FlagError) Error() string

func (*FlagError) ExitCode

func (e *FlagError) ExitCode() ExitCode

ExitCode returns ExitUsage.

func (*FlagError) Unwrap

func (e *FlagError) Unwrap() 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

type PromptChoice struct {
	Label string
	Value string
}

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) ExitCode

func (e ScopeError) ExitCode() ExitCode

ExitCode returns ExitScope.

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.

Jump to

Keyboard shortcuts

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