cmdutil

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: May 11, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CloneValues

func CloneValues(values url.Values) url.Values

CloneValues copies URL values so callers can safely mutate request params.

func ConfirmAction

func ConfirmAction(opts Options, message string) (bool, error)

func DecodeJSON

func DecodeJSON[T any](data json.RawMessage) (T, error)

DecodeJSON decodes a Gumroad JSON response into a typed value with the shared human-facing parse error wrapper.

func ExactArgs

func ExactArgs(n int) cobra.PositionalArgs

ExactArgs validates an exact number of positional arguments with usage help.

func FetchPage

func FetchPage[T any](client *api.Client, path string, params url.Values) (T, error)

FetchPage fetches and decodes a single Gumroad page response.

func FormatMoney

func FormatMoney(cents int, currency string) string

FormatMoney converts a minor-unit amount back to a user-friendly string (e.g. 1099 → "10.99", 1000 → "10.00", -150 → "-1.50"). For single-unit currencies like JPY, returns the amount as-is (e.g. 1000 → "1000").

func IsSingleUnitCurrency

func IsSingleUnitCurrency(currency string) bool

IsSingleUnitCurrency reports whether the given currency code has no minor unit (e.g. JPY where ¥1 = 1 minor unit).

func JoinPath

func JoinPath(segments ...string) string

JoinPath escapes path segments and joins them into an absolute API path.

func MissingFlagError

func MissingFlagError(cmd *cobra.Command, flag string) error

MissingFlagError returns a usage error for a missing required flag.

func NewAPIClient

func NewAPIClient(opts Options, token string) *api.Client

NewAPIClient builds an API client that respects the command's context, version, debug setting, and stderr writer.

func NewUsageError

func NewUsageError(cmd *cobra.Command, message string) error

NewUsageError returns a human-facing usage error with concise help.

func ParseMoney

func ParseMoney(flag, value, noun, currency string) (int, error)

ParseMoney converts a user-friendly price string to minor units using integer math (no floats). The scaling factor depends on the currency: ×100 for most currencies, ×1 for single-unit currencies like JPY.

If currency is empty, defaults to ×100 (standard behavior). Rejects negative values — use ParseSignedMoney for those.

func ParseSignedMoney

func ParseSignedMoney(flag, value, noun, currency string) (int, error)

ParseSignedMoney is like ParseMoney but allows negative values.

func PrintCancelledAction

func PrintCancelledAction(opts Options, action, id string) error

func PrintDryRunAction

func PrintDryRunAction(opts Options, action string) error

func PrintDryRunRequest

func PrintDryRunRequest(opts Options, method, path string, params url.Values) error

func PrintInfo

func PrintInfo(opts Options, message string) error

PrintInfo writes a non-essential informational message unless quiet mode is enabled.

func PrintJSONResponse added in v0.2.0

func PrintJSONResponse(opts Options, data json.RawMessage) error

PrintJSONResponse renders a raw API response using the command's JSON/JQ settings while preserving the shared empty-body normalization.

func PrintMutationSuccess added in v0.2.0

func PrintMutationSuccess(opts Options, data json.RawMessage, id, successMessage string) error

PrintMutationSuccess renders a successful mutating command with the shared human/plain/JSON envelope used across the CLI.

func PrintSuccess

func PrintSuccess(opts Options, message string) error

PrintSuccess writes a success message unless quiet mode is enabled.

func PropagateExamples

func PropagateExamples(cmd *cobra.Command)

PropagateExamples fills empty command examples from the nearest ancestor.

func ReplayCommand

func ReplayCommand(base string, args ...CommandArg) string

ReplayCommand formats a copy-pasteable command hint that preserves active flags. Valued args are included when Value is non-empty. Boolean args are included when Boolean is true.

func RequireAnyFlagChanged

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

RequireAnyFlagChanged returns a usage error when none of the supplied flags were set.

func RequireDateFlag

func RequireDateFlag(cmd *cobra.Command, flag, value string) error

RequireDateFlag rejects explicitly provided date flags that are not strict YYYY-MM-DD values.

func RequireHTTPURLFlag

func RequireHTTPURLFlag(cmd *cobra.Command, flag, value string) error

RequireHTTPURLFlag rejects explicitly provided URL flags that are not absolute http(s) URLs.

func RequireNonNegativeDurationFlag

func RequireNonNegativeDurationFlag(cmd *cobra.Command, flag string, value time.Duration) error

RequireNonNegativeDurationFlag rejects explicitly provided duration flags that must be >= 0.

func RequireNonNegativeIntFlag

func RequireNonNegativeIntFlag(cmd *cobra.Command, flag string, value int) error

RequireNonNegativeIntFlag rejects explicitly provided integer flags that must be >= 0.

func RequirePercentFlag

func RequirePercentFlag(cmd *cobra.Command, flag string, value int) error

RequirePercentFlag rejects explicitly provided percentage flags that must be between 1 and 100 inclusive.

func RequirePositiveIntFlag

func RequirePositiveIntFlag(cmd *cobra.Command, flag string, value int) error

RequirePositiveIntFlag rejects explicitly provided integer flags that must be > 0.

func Run

func Run(opts Options, spinnerMessage string, run ClientRunner, render func(json.RawMessage) error) error

Run executes a caller-provided authenticated client operation and preserves the shared JSON/JQ fast-path.

func RunDecoded

func RunDecoded[T any](opts Options, spinnerMessage string, run ClientRunner, render func(T) error) error

RunDecoded executes an authenticated client operation and decodes the response for human/plain rendering while preserving the shared JSON/JQ fast-path.

func RunRequest

func RunRequest(opts Options, spinnerMessage, method, path string, params url.Values, render func(json.RawMessage) error) error

RunRequest executes an authenticated API request and preserves the shared JSON/JQ fast-path.

func RunRequestDecoded

func RunRequestDecoded[T any](opts Options, spinnerMessage, method, path string, params url.Values, render func(T) error) error

RunRequestDecoded executes an authenticated API request and decodes the response for human/plain rendering while preserving the shared JSON/JQ fast-path.

func RunRequestWithSuccess

func RunRequestWithSuccess(opts Options, spinnerMessage, method, path string, params url.Values, id, successMessage string) error

RunRequestWithSuccess executes a mutating API request and prints a success message in human mode. The id identifies the affected resource in JSON output.

func RunWithToken

func RunWithToken(opts Options, token, spinnerMessage string, run ClientRunner, render func(json.RawMessage) error) error

RunWithToken executes a caller-provided client operation with a caller-supplied token.

func RunWithTokenData added in v0.2.0

func RunWithTokenData(opts Options, token, spinnerMessage string, run ClientRunner) (json.RawMessage, error)

RunWithTokenData executes a caller-provided client operation with a caller-supplied token and returns the raw response body without rendering it.

func ShouldShowSpinner

func ShouldShowSpinner(opts Options) bool

ShouldShowSpinner reports whether transient spinner output should be shown. Debug mode disables the spinner so structured stderr diagnostics stay readable.

func StreamPaginatedPages

func StreamPaginatedPages[T any](opts Options, cfg PaginatedPageOutputConfig[T]) error

StreamPaginatedPages coordinates output-mode specific rendering for `--all` style paginated commands while preserving atomic JSON/JQ output.

func UsageErrorf

func UsageErrorf(cmd *cobra.Command, format string, args ...any) error

UsageErrorf returns a human-facing usage error with concise help.

func WalkPages

func WalkPages[T any](client *api.Client, path string, params url.Values, nextPageKey func(T) string, visit PageVisitor[T]) error

WalkPages follows Gumroad-style next_page_key pagination and decodes each response into T before visiting it.

func WalkPagesWithDelay

func WalkPagesWithDelay[T any](ctx context.Context, delay time.Duration, client *api.Client, path string, params url.Values, nextPageKey func(T) string, visit PageVisitor[T]) error

WalkPagesWithDelay follows Gumroad-style next_page_key pagination, pausing between follow-up page requests when delay > 0.

func WithOptions

func WithOptions(ctx context.Context, opts Options) context.Context

Types

type ClientRunner

type ClientRunner func(*api.Client) (json.RawMessage, error)

type CommandArg

type CommandArg struct {
	Flag    string
	Value   string
	Boolean bool // true for valueless flags like --no-upcoming
}

type Options

type Options struct {
	Context        context.Context
	Stdin          io.Reader
	Stdout         io.Writer
	Stderr         io.Writer
	JSONOutput     bool
	PlainOutput    bool
	JQExpr         string
	Quiet          bool
	DryRun         bool
	NoColor        bool
	NoInput        bool
	NonInteractive bool
	Yes            bool
	NoImage        bool
	PageDelay      time.Duration
	Debug          bool
	Version        string
}

func DefaultOptions

func DefaultOptions() Options

func OptionsFrom

func OptionsFrom(cmd *cobra.Command) Options

func (Options) DebugEnabled

func (o Options) DebugEnabled() bool

DebugEnabled reports whether debug logging should be enabled.

func (Options) Err

func (o Options) Err() io.Writer

func (Options) In

func (o Options) In() io.Reader

func (Options) Out

func (o Options) Out() io.Writer

func (Options) Style

func (o Options) Style() output.Styler

func (Options) UsesJSONOutput

func (o Options) UsesJSONOutput() bool

UsesJSONOutput reports whether the command should emit JSON output.

type PageVisitor

type PageVisitor[T any] func(T) (stop bool, err error)

type PaginatedPageOutputConfig

type PaginatedPageOutputConfig[T any] struct {
	JSONKey        string
	EmptyMessage   string
	Walk           func(PageVisitor[T]) error
	HasItems       func(T) bool
	WriteItems     func(T, func(any) error) error
	WritePlainPage func(io.Writer, T) error
	WriteTablePage func(io.Writer, T) error
}

PaginatedPageOutputConfig describes how a paginated command should render pages across machine-readable and human output modes.

type UsageError

type UsageError struct {
	Message string
}

func (*UsageError) Error

func (e *UsageError) Error() string

Jump to

Keyboard shortcuts

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