Documentation
¶
Overview ¶
Package cmdutil provides the shared Factory and error types used by every command.
- factory.go: Factory, New, env and base URL resolution, production and mutation confirmations
- factory_token.go: token resolution, refresh and renewal of a rejected token
- errors.go, exitcode.go: error types, exit codes and HandleError
- allowlist.go, origin.go, sandbox_guard.go: credential hosts and the sandbox-only guard
- args.go, flagcheck.go, flagalias.go, annotations.go, query.go, segment.go: argument and flag validation, and hidden spellings of renamed flags
- prompt.go: interactive pickers and yes/no prompts
- render.go, complete.go, browser.go, stub.go: output helpers, completion, browser, stub commands
Index ¶
- Constants
- Variables
- func AddDryRunFlag(cmd *cobra.Command, f *Factory)
- func AliasFlag(fs *pflag.FlagSet, alias, name string)
- 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(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 CanOpenBrowser() bool
- func CompleteEnumFlags(root *cobra.Command)
- func CompleteFirstArg(fn cobra.CompletionFunc) cobra.CompletionFunc
- func CompleteProfiles(f *Factory) cobra.CompletionFunc
- func ConfirmsIn(cmd *cobra.Command, env string) string
- func ConfirmsValue(raw, env string) string
- func DisplayHost(host string) string
- func FirstArg(args []string) string
- func Fprintf(w io.Writer, format string, a ...any)
- func IncludeEndDay(cmd *cobra.Command, flags ...string) error
- 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 ReadScopeError(err error, scope, permission string) error
- func RenameFlag(fs *pflag.FlagSet, name, old, usage string)
- func RequiredFlags(cmd *cobra.Command) map[string]bool
- func ServerValueError(what string, err error) error
- func SpelledAs(cmd *cobra.Command, flag string) string
- func Stub(cmd *cobra.Command) *cobra.Command
- func StubRunE(cmd *cobra.Command, _ []string) error
- func UnknownProfileError(name string) error
- func ValidateAmountOrder(cmd *cobra.Command, minFlag, maxFlag 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 ValidateDateOnly(cmd *cobra.Command, flags ...string) error
- func ValidateDateOrder(cmd *cobra.Command, fromFlag, toFlag 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
- func ValidateRedirectURL(flag, value string) error
- type AuthError
- type DryRun
- type DryRunRequest
- type ExitCode
- type ExitCoder
- type Factory
- func (f *Factory) Account() string
- func (f *Factory) AccountsForm(label string, accounts []FormAccount) ([]FormAnswer, error)
- 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) BindCommand(cmd *cobra.Command)
- func (f *Factory) CanPrompt() bool
- func (f *Factory) CheckExplicitProfile() error
- func (f *Factory) CheckProdWrite(action, target string) error
- func (f *Factory) Confirm(label string) (bool, error)
- func (f *Factory) ConfirmByTyping(action, want string) error
- func (f *Factory) ConfirmMutation(action, target string, destructive bool) error
- func (f *Factory) ConfirmOut() io.Writer
- func (f *Factory) ConfirmProdWrite(action, target 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) InputCheckedOrFlag(val, flag, label string, check func(string) error) (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) IsProductionTarget() bool
- func (f *Factory) MultiSelectChoicesDefault(label string, choices []PromptChoice, picked []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) ReachTheConfirm() string
- func (f *Factory) RefuseUnlessDryRun(err error) error
- func (f *Factory) RenderChanges(before, after any, replaced ...string) error
- func (f *Factory) RenderDryRun(d DryRun, table func() error) error
- func (f *Factory) RenderDryRunRequest(req DryRunRequest) error
- func (f *Factory) RenderFields(v any) error
- 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) SelectChoiceDefault(label string, choices []PromptChoice, def string) (string, error)
- func (f *Factory) SelectChoiceOrFlag(val, flag, label string, choices []PromptChoice) (string, error)
- func (f *Factory) SelectDefault(label string, options []string, def string) (string, error)
- func (f *Factory) SelectOrFlag(val, flag, label string, options []string) (string, error)
- func (f *Factory) SetContext(ctx context.Context)
- 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) WaitDevice(ctx context.Context, w prompt.DeviceWait, poll func(context.Context) error) (shown bool, err error)
- func (f *Factory) WarnPlaintextStorage(subject, path string, keychainFailed bool)
- func (f *Factory) YesNo(on bool) string
- type FlagError
- type FormAccount
- type FormAnswer
- type FormMode
- type FormOption
- type GlobalOptions
- type NotImplementedError
- type PromptChoice
- type Prompter
- 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 states when a command prompts: one value for every env it runs in, or // comma-separated env=value pairs, e.g. "sandbox=always,production=terminal". Values are // "always" | "conditional" | ConfirmsTerminal; an env left out has none. Read it with ConfirmsIn. AnnConfirms = "sepay:confirms" 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" // AnnHost names the hosts a command under a product noun calls when they are not its noun's. AnnHost = "sepay:host" // HostAPI | HostPGCheckout, or unset )
Annotation keys read by help and `sepay --map`.
const ( HostAPI = "api" // the SePay API host only, e.g. the ipn commands HostPGCheckout = "pg-checkout" // the PG API host and the hosted-checkout host )
AnnHost values.
const AnnAliasOf = "sepay_alias_of"
AnnAliasOf marks a hidden flag kept as another spelling; its value names the visible flag.
const ClientID = "sepay-cli"
ClientID identifies the CLI as the registered public OAuth client.
const ConfirmsTerminal = "terminal"
ConfirmsTerminal is the AnnConfirms value for a production write: it runs only with --env production on the command line, and --yes confirms it only when it names one resource.
const DryRunNotChecked = "what the server normalises, derives or refuses; after the real run, get shows what it stored"
DryRunNotChecked is the first not_checked entry of every dry run: After is never a guess at what the server does with the values.
const DryRunNotice = "Dry run: nothing was sent."
DryRunNotice opens a dry run's table output. --quiet keeps it, so a preview is never mistaken for the real run.
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 run was stopped: Ctrl+C or Esc at a prompt, or SIGINT/SIGTERM.
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 AddDryRunFlag ¶ added in v0.1.8
AddDryRunFlag adds --dry-run to a production write. Only the api.Client from NewAPIClient refuses writes during a dry run; a command that writes through another client needs its own stop.
func AliasFlag ¶ added in v0.1.3
AliasFlag registers alias as a hidden second spelling of the existing flag name, under the same rules as RenameFlag.
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 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 CanOpenBrowser ¶ added in v0.1.4
func CanOpenBrowser() bool
CanOpenBrowser reports whether a launched browser would appear in front of the user. Over SSH or on a display-less server xdg-open may still start, open nothing, and report success.
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 ConfirmsIn ¶ added in v0.1.8
ConfirmsIn returns cmd's AnnConfirms value for env, inherited like Annotation.
func ConfirmsValue ¶ added in v0.1.8
ConfirmsValue resolves a raw AnnConfirms value for env.
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 IncludeEndDay ¶ added in v0.1.3
IncludeEndDay sends a bare end date as its last second. The API compares a datetime column with "<=", which reads "2026-10-20" as midnight and drops the rest of that day.
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 ReadScopeError ¶ added in v0.1.8
ReadScopeError gives a production insufficient_scope from a product read (pg, einvoice) its own exit-5 text. The server answers insufficient_scope for a missing "read" too; the consent screen offers the product scope only to a user holding the permission, and refresh cannot add a scope missing at login. The server error stays as Cause for its request id.
func RenameFlag ¶ added in v0.1.3
RenameFlag registers name as the visible spelling of the existing flag old, with usage as its help text. Both spellings write the same value, so whatever old sends to the API is unchanged; old stays accepted but hidden. Passing both is a usage error.
Changed is per spelling: code that tests fs.Changed must test both names.
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 SpelledAs ¶ added in v0.1.3
SpelledAs names a flag the way the user typed it: a hidden alias sharing its value (RenameFlag, AliasFlag) records which spelling was set.
func UnknownProfileError ¶
UnknownProfileError reports a named profile with no stored entry, as a usage error.
func ValidateAmountOrder ¶ added in v0.1.3
ValidateAmountOrder rejects a min/max money filter whose min is above its max.
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 ValidateDateOnly ¶ added in v0.1.8
ValidateDateOnly is ValidateDates for endpoints that take a bare date and nothing finer.
func ValidateDateOrder ¶ added in v0.1.3
ValidateDateOrder rejects a date range whose start is after its end. A bare end date covers its whole day, so "--from 2026-11-05 --to 2026-11-05" is one day, not an empty range. Run it after ValidateDates or ValidateDays, which leave the values in a layout it reads.
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.
func ValidateRedirectURL ¶ added in v0.1.3
ValidateRedirectURL accepts a URL a browser is sent back to: a scheme, no whitespace or control character, at most 2048 characters, and none of the schemes that run code in the page.
Types ¶
type AuthError ¶
type AuthError struct {
Err error
}
AuthError marks a failure caused by having no usable credential.
type DryRun ¶ added in v0.1.8
type DryRun struct {
DryRun bool `json:"dry_run" yaml:"dry_run"`
Request DryRunRequest `json:"request" yaml:"request"`
Before any `json:"before" yaml:"before"`
After any `json:"after" yaml:"after"`
NotChecked []string `json:"not_checked" yaml:"not_checked"`
WouldRefuse []string `json:"would_refuse" yaml:"would_refuse"`
}
DryRun is what a dry run prints instead of the write's result. Before is the resource as get shows it (a replay's delivery preview), null for a create; After is Before with the fields the write sends, as sent, in get's field names and values, null for a delete. NotChecked holds a command's own lines; RenderDryRun puts DryRunNotChecked before them and fills WouldRefuse with the CLI's confirm-gate refusal, if any.
type DryRunRequest ¶ added in v0.1.8
type DryRunRequest struct {
Method string `json:"method" yaml:"method"`
Path string `json:"path" yaml:"path"`
Query string `json:"query,omitempty" yaml:"query,omitempty"`
Headers []string `json:"headers,omitempty" yaml:"headers,omitempty"`
Body any `json:"body" yaml:"body"`
}
DryRunRequest is the write a dry run withholds; Path is relative to the API base and Query is the raw query string the request would carry.
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 ExitBlocked ExitCode = 8 // blocked by account config or in-app permission ExitInterrupted ExitCode = 130 // Ctrl+C or Esc at a prompt, or SIGINT/SIGTERM )
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
// Prompter answers interactive prompts; nil draws them on the terminal.
Prompter Prompter
// UsageCommand is the path of the command that failed (e.g. "sepay transaction get"), named in
// the usage hint; empty means the root.
UsageCommand 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) AccountsForm ¶ added in v0.1.3
func (f *Factory) AccountsForm(label string, accounts []FormAccount) ([]FormAnswer, error)
AccountsForm shows one form editing what each account notifies; server text in it is sanitised first. Call only after CanPrompt.
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 production for a command that runs on sandbox only: a mutation with no production endpoint yet, or a sandbox-only read such as listen. 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) BindCommand ¶ added in v0.1.3
BindCommand records which hosts cmd reaches, chosen by its top-level noun: Bank Hub, PG and E-Invoice resolve their own, local commands none. A command annotated AnnHost overrides its noun.
func (*Factory) CheckExplicitProfile ¶
CheckExplicitProfile fails with "unknown profile" when a named profile has no entry.
func (*Factory) CheckProdWrite ¶ added in v0.1.8
CheckProdWrite refuses a production write ConfirmProdWrite would refuse, without prompting, so a command can stop before the reads that precede its confirm. A dry run records the refusal instead.
func (*Factory) Confirm ¶
Confirm returns true under --yes, else prompts; unattended without --yes is a usage error.
func (*Factory) ConfirmByTyping ¶ added in v0.1.4
ConfirmByTyping makes the user type want back before action. --yes does not answer it and a run without a terminal is a usage error, so the action stays one a person takes by hand. A dry run asks nothing: it records that refusal for would_refuse and passes.
func (*Factory) ConfirmMutation ¶
ConfirmMutation is the confirmation gate every mutating command calls; target is as for ConfirmProdWrite. A dry run confirms nothing: it records what the real run would refuse.
func (*Factory) ConfirmOut ¶ added in v0.1.4
ConfirmOut is where a confirm's warning, and what a command shows ahead of it, is written: the prompt's own stream when a question will be asked (after the env line, so the warning stays next to its question), stderr otherwise.
func (*Factory) ConfirmProdWrite ¶
ConfirmProdWrite gates a write on production. target is the id of the one resource the command names, or "" when it names none (a create). Past CheckProdWrite's refusals, --yes confirms, else a terminal prompt defaulting to no. A dry run neither prompts nor refuses: it records the refusal for would_refuse, and its client refuses the write itself.
func (*Factory) IdempotencyKey ¶
IdempotencyKey returns the --idempotency-key value, validated against the server's charset, or a fresh key.
func (*Factory) InputCheckedOrFlag ¶ added in v0.1.3
func (f *Factory) InputCheckedOrFlag(val, flag, label string, check func(string) error) (string, error)
InputCheckedOrFlag is InputOrFlag for a value check accepts: on a terminal a rejected answer, empty included, is reported and asked again, so a bad value never reaches the request.
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) IsProductionTarget ¶ added in v0.1.4
IsProductionTarget reports whether the next API call may reach production; see isProductionTarget.
func (*Factory) MultiSelectChoicesDefault ¶ added in v0.1.3
func (f *Factory) MultiSelectChoicesDefault(label string, choices []PromptChoice, picked []string) ([]string, error)
MultiSelectChoicesDefault prompts for any number of choices, those whose Value is in picked already checked. 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) ReachTheConfirm ¶ added in v0.1.8
ReachTheConfirm tells a person at a terminal which flags keep the prompt away; without a terminal only the user can confirm.
func (*Factory) RefuseUnlessDryRun ¶ added in v0.1.8
RefuseUnlessDryRun returns a confirm refusal, or during a dry run passes and keeps the first one, the refusal the real run would stop at, for would_refuse.
func (*Factory) RenderChanges ¶ added in v0.1.8
RenderChanges prints a FIELD BEFORE AFTER table of the fields that differ, nested ones as dotted paths, so a key holding a dot would read as a nested one. Each path in replaced is a masked value the write sets: it is listed whatever both sides read. Values are never cut to the terminal width: a preview must show what the write sets in full.
func (*Factory) RenderDryRun ¶ added in v0.1.8
RenderDryRun prints d as one object under -o json/yaml. In table mode it prints the notice, then table, then a "! not checked" line for each not_checked entry and a "! the real run would refuse" line for each refusal.
func (*Factory) RenderDryRunRequest ¶ added in v0.1.8
func (f *Factory) RenderDryRunRequest(req DryRunRequest) error
RenderDryRunRequest prints the request of a raw `sepay api` dry run, as JSON in table mode too, like the response it stands in for; table mode writes each terminal control or invisible character as a \u escape, -o json keeps every byte.
func (*Factory) RenderFields ¶ added in v0.1.8
RenderFields prints v as a FIELD VALUE table, nested fields as dotted paths, never cut to width.
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) SelectChoiceDefault ¶ added in v0.1.3
func (f *Factory) SelectChoiceDefault(label string, choices []PromptChoice, def string) (string, error)
SelectChoiceDefault prompts for one choice with the cursor on the one whose Value is def. Call only after CanPrompt.
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) SelectDefault ¶ added in v0.1.3
SelectDefault prompts for one of options with the cursor on def, matched case-insensitively, so an edit that only presses Enter keeps the stored value. Call only after CanPrompt.
func (*Factory) SelectOrFlag ¶
SelectOrFlag returns val, else prompts for one of options, else a usage error listing them.
func (*Factory) SetContext ¶ added in v0.1.1
SetContext gives the factory the running command's context, for work started outside a command's own calls.
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.
func (*Factory) WaitDevice ¶ added in v0.1.4
func (f *Factory) WaitDevice(ctx context.Context, w prompt.DeviceWait, poll func(context.Context) error) (shown bool, err error)
WaitDevice draws the device-login wait screen while poll runs; shown is false, and poll has not run, when no prompt is possible. A Ctrl+C there returns ErrInterrupted.
func (*Factory) WarnPlaintextStorage ¶ added in v0.1.1
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.
type FlagError ¶
type FlagError struct {
Err error
}
FlagError marks a misused flag/argument as a usage error.
type FormAccount ¶ added in v0.1.3
FormAccount is one bank account in AccountsForm.
type FormAnswer ¶ added in v0.1.3
type FormAnswer = prompt.AccountAnswer
FormAnswer is what one FormAccount was set to.
type FormOption ¶ added in v0.1.3
FormOption is one virtual account a FormAccount can check.
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
DryRun bool // --dry-run, a local flag of the production writes (AddDryRunFlag)
}
GlobalOptions holds the global flags, and --dry-run of the production writes, 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 Prompter ¶ added in v0.1.3
type Prompter interface {
Select(label string, options []string, def int) (int, error)
MultiSelect(label string, options []string, picked []int) ([]int, error)
Input(label, def string) (string, error)
Password(label string) (string, error)
Confirm(label string, def bool) (bool, error)
Accounts(label string, accounts []FormAccount) ([]FormAnswer, error)
}
Prompter asks the interactive questions once canPrompt allows them. Labels and options arrive sanitised; Select and MultiSelect answer with indexes, Input with the text typed ("" keeps def).
type ScopeError ¶
ScopeError marks a failure caused by the token's scopes. Err is what the user reads; Cause, when set, is the server error it replaces, kept for its request id and error code.
func (ScopeError) Error ¶
func (e ScopeError) Error() string
func (ScopeError) Unwrap ¶
func (e ScopeError) Unwrap() []error
Unwrap exposes Cause too, so errors.As still finds the server 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.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package prompttest scripts the answers to a command's interactive prompts in tests.
|
Package prompttest scripts the answers to a command's interactive prompts in tests. |