utils

package
v1.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 25 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

Index

Constants

View Source
const (
	ConfigFileName = ".hostinger-mail.yaml"
	EnvPrefix      = "HOSTINGER_MAIL_"
)

ConfigFileName is the YAML config file in the user's home directory and EnvPrefix the prefix of every environment variable the CLI reads.

View Source
const (
	ExitOK         = 0
	ExitError      = 1 // API, network or other runtime failure
	ExitUsage      = 2 // bad arguments, flags or input
	ExitAuth       = 3 // HTTP 401/403
	ExitNotFound   = 4 // HTTP 404
	ExitValidation = 5 // HTTP 422
)

Exit codes. Scripts can rely on these; keep README.md in sync.

View Source
const UsageTemplate = `` /* 1494-byte string literal not displayed */

UsageTemplate is cobra's default usage template with the local flags split into "Required Flags" and "Flags".

Variables

View Source
var (
	Build string
	Major string
	Minor string
	Patch string

	CLIVersion Version
)
View Source
var ErrAborted = fmt.Errorf("aborted")

ErrAborted is returned when the user declines a confirmation prompt.

View Source
var ErrActionFailed = errors.New("action failed")

ErrActionFailed is returned by Wait when the resource ends in a failed state.

View Source
var ErrDryRun = errors.New("dry run")

ErrDryRun is returned by the HTTP layer after --dry-run printed a request instead of sending it. It ends the command successfully.

View Source
var ErrNoCredentials = errors.New("no credentials configured")

ErrNoCredentials marks a request that could not be sent because no API token (or sign-in) is configured. It exits with ExitAuth.

Functions

func ArgScope added in v1.4.0

func ArgScope(cmd *cobra.Command) int

func BindLegacyEnv

func BindLegacyEnv(w io.Writer)

BindLegacyEnv binds config keys to their HOSTINGER_MAIL_* env var with a deprecated HAPI_* fallback on the global viper, emitting a one-time notice to w per key whose value comes from the legacy variable.

func CompleteArgs added in v1.3.0

func CompleteArgs(sources ...*ArgSource) cobra.CompletionFunc

CompleteArgs returns a ValidArgsFunction that completes the next positional argument from sources[len(args)]; a nil entry, an API error or a timeout yields no completions (and never falls back to file names).

func Confirm added in v1.3.0

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

Confirm asks before a destructive command runs. --yes and dry-run (flag, config or environment) skip the question; a non-interactive session must pass --yes explicitly.

func ConfirmScoped added in v1.4.0

func ConfirmScoped(cmd *cobra.Command, action string, args []string, typed bool) error

ConfirmScoped is Confirm for a command whose target can come from the link, the environment or the config. Such a target is acted on only after a question; with --yes or without a terminal it must be typed.

func EnumCheck

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

EnumCheck validates that a changed string flag holds one of the allowed values.

func FitWidth added in v1.5.0

func FitWidth(s string, width int) string

FitWidth shortens s to width columns, ending in "…". A line wider than the terminal wraps, and a spinner that redraws it with \r then adds a row per frame.

func FlagErrorf added in v1.3.0

func FlagErrorf(format string, a ...any) error

FlagErrorf formats a FlagError.

func FormatCheck added in v1.3.0

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

FormatCheck validates that a changed string flag parses as format ("date-time", "date", "uuid" or "email") before it is converted.

func GroupRunE added in v1.3.0

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

GroupRunE makes a command group fail on an unknown subcommand (with suggestions) instead of printing help and exiting 0. Without arguments it shows the group's help.

func HandleError added in v1.3.0

func HandleError(w io.Writer, cmd *cobra.Command, err error) int

HandleError prints err for the command that failed and returns the exit code. Usage mistakes get a pointer to --help; API errors list each invalid field against the flag that sets it.

func IntPtrOrNil

func IntPtrOrNil(i int) *int

func Interactive added in v1.3.0

func Interactive(cmd *cobra.Command) bool

Interactive reports whether the CLI may prompt: stdin and stderr are terminals and neither --no-input nor the no_input config/env key is set.

func IsRequired added in v1.3.0

func IsRequired(f *pflag.Flag) bool

IsRequired reports whether a flag was marked required with MarkFlagRequired.

func JSONValue

func JSONValue(raw, flag string) (any, error)

JSONValue parses a JSON flag value into a generic value. The value is either inline JSON, @path to read it from a file, or - to read it from stdin.

func MigrateLegacyConfig

func MigrateLegacyConfig(home string, w io.Writer) (configPath string, migrated bool)

MigrateLegacyConfig returns the YAML config path the CLI should read and whether a one-time migration (or legacy fallback) happened. When the new ~/.hostinger-mail.yaml is absent but a legacy ~/.hapi.yaml exists, it moves the old file to the new path. If the move fails, it falls back to the old path in place. Notices are written to w. With no legacy file, it is a no-op.

func ParseIntArg added in v1.3.0

func ParseIntArg(s string) (int, error)

ParseIntArg parses an integer argument where a bad value must not panic (shell completion of later arguments).

func ParseUUIDArg added in v1.3.0

func ParseUUIDArg(s string) (uuid.UUID, error)

ParseUUIDArg parses a UUID argument where a bad value must not panic.

func PromptMissing added in v1.3.0

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

PromptMissing asks for any missing positional arguments and required flags when the session is interactive. It runs from the root's PersistentPreRunE: after argument validation (which lets missing arguments through only when interactive) and before cobra's required-flag check.

func PromptedArgs added in v1.3.0

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

PromptedArgs returns args extended with any values prompted for interactively.

func RegisterArgs added in v1.3.0

func RegisterArgs(cmd *cobra.Command, specs ...ArgSpec)

RegisterArgs installs the positional-argument validator for cmd: exactly len(specs) arguments, each parsing as its kind. Missing trailing arguments are allowed in an interactive session; they are prompted for before RunE.

func RegisterScopedArgs added in v1.4.0

func RegisterScopedArgs(cmd *cobra.Command, scope int, specs ...ArgSpec)

RegisterScopedArgs is RegisterArgs where the first scope args may be left out (the resolver supplies them); given args fill the specs from the end.

func RegisterWaitFlags added in v1.3.0

func RegisterWaitFlags(cmd *cobra.Command)

RegisterWaitFlags adds --wait and --wait-timeout to cmd.

func ScopeInt added in v1.4.0

func ScopeInt(name, v string) (int, error)

ScopeInt parses an id resolved from a flag, the environment or the link, which argument validation never saw.

func StderrWidth added in v1.5.0

func StderrWidth() int

StderrWidth is the terminal width of stderr, or 0 when unknown.

func StringArrayToIntArray

func StringArrayToIntArray(strArr []string) []int

func StringPtrOrNil

func StringPtrOrNil(s string) *string

func StringToDate added in v1.1.2

func StringToDate(dateStr string) openapi_types.Date

func StringToEmail added in v1.1.2

func StringToEmail(email string) openapi_types.Email

StringToEmail keeps format:email query params converting through utils like every other formatted kind, so generated commands need no extra import.

func StringToInt

func StringToInt(s string) int

func StringToTime

func StringToTime(dateStr string) time.Time

func StringToUUID added in v1.1.4

func StringToUUID(s string) openapi_types.UUID

func Wait added in v1.3.0

func Wait(cmd *cobra.Command, body []byte, spec WaitSpec, poll func(ctx context.Context, id string) ([]byte, int, error)) ([]byte, int, error)

Wait polls an asynchronous resource until its state is one of spec.Done or spec.Failed. body is the response that started it; poll fetches the resource by the ID read from body. It returns the last fetched body; when the final state is a failure the error is ErrActionFailed (wrapped).

Types

type APIError added in v1.3.0

type APIError struct {
	Status        int
	Message       string
	Errors        map[string][]string
	CorrelationID string
	Body          []byte
}

APIError is an HTTP error response from the API.

func NewAPIError added in v1.3.0

func NewAPIError(status int, body []byte) *APIError

NewAPIError decodes the API's error body ({message, errors, correlation_id}); an unexpected body is kept verbatim.

func (*APIError) Error added in v1.3.0

func (e *APIError) Error() string

func (*APIError) ExitCode added in v1.3.0

func (e *APIError) ExitCode() int

ExitCode maps the HTTP status to the CLI exit code.

type ArgKind added in v1.3.0

type ArgKind int

ArgKind is the type a positional argument must parse as.

const (
	ArgString ArgKind = iota
	ArgInt
	ArgUUID
)

type ArgSource added in v1.3.0

type ArgSource struct {
	Value string
	Fetch func(ctx context.Context, args []string) ([]byte, int, error)
}

ArgSource supplies the completions of one positional argument: Fetch lists the candidates (it receives the arguments typed so far) and Value names the item field offered.

type ArgSpec added in v1.3.0

type ArgSpec struct {
	Name string // e.g. "virtual-machine-id"
	Kind ArgKind
}

ArgSpec describes one positional argument of a generated command.

func ArgSpecs added in v1.3.0

func ArgSpecs(cmd *cobra.Command) []ArgSpec

ArgSpecs returns the positional arguments registered for cmd.

func IntArg added in v1.3.0

func IntArg(name string) ArgSpec

func StringArg added in v1.3.0

func StringArg(name string) ArgSpec

func UUIDArg added in v1.3.0

func UUIDArg(name string) ArgSpec

type Call added in v1.3.0

type Call func(ctx context.Context) ([]byte, int, error)

Call performs one API request and returns the raw body and status code.

func AllPages added in v1.3.0

func AllPages(call Call, setPage func(int)) Call

AllPages wraps a paginated list call so it fetches every page (setPage selects the page before each request) and returns one {data, meta} envelope holding all items. A response that is not a {data: [...]} envelope, or an error status, is returned unchanged.

type FlagError added in v1.3.0

type FlagError struct{ Err error }

FlagError is an input mistake (bad flag value, missing argument). The root command prints it with a pointer to --help and exits with ExitUsage.

func (*FlagError) Error added in v1.3.0

func (e *FlagError) Error() string

func (*FlagError) Unwrap added in v1.3.0

func (e *FlagError) Unwrap() error

type Version

type Version struct {
	Major, Minor, Patch int
	Build               string
}

func (Version) String

func (v Version) String(withBuild bool) string

type WaitSpec added in v1.3.0

type WaitSpec struct {
	IDField    string
	StateField string
	Done       []string
	Failed     []string
}

WaitSpec describes how to recognise the end state of an asynchronous resource.

Jump to

Keyboard shortcuts

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