{"modulePath":"github.com/hostinger/mail-api-cli","version":"v1.11.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package utils\n\n## Constants\n\n```go\nconst (\n\tConfigFileName = \".hostinger-mail.yaml\"\n\tEnvPrefix      = \"HOSTINGER_MAIL_\"\n)\n```\nConfigFileName is the YAML config file in the user's home directory and EnvPrefix the prefix of every environment variable the CLI reads.\n\n```go\nconst (\n\tExitOK         = 0\n\tExitError      = 1 // API, network or other runtime failure\n\tExitUsage      = 2 // bad arguments, flags or input\n\tExitAuth       = 3 // HTTP 401/403\n\tExitNotFound   = 4 // HTTP 404\n\tExitValidation = 5 // HTTP 422\n)\n```\nExit codes. Scripts can rely on these; keep README.md in sync.\n\n```go\nconst UsageTemplate = `Usage:{{if .Runnable}}\n  {{.UseLine}}{{end}}{{if .HasAvailableSubCommands}}\n  {{.CommandPath}} [command]{{end}}{{if gt (len .Aliases) 0}}\n\nAliases:\n  {{.NameAndAliases}}{{end}}{{if .HasExample}}\n\nExamples:\n{{.Example}}{{end}}{{if .HasAvailableSubCommands}}{{$cmds := .Commands}}{{if eq (len .Groups) 0}}\n\nAvailable Commands:{{range $cmds}}{{if (or .IsAvailableCommand (eq .Name \"help\"))}}\n  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{else}}{{range $group := .Groups}}\n\n{{.Title}}{{range $cmds}}{{if (and (eq .GroupID $group.ID) (or .IsAvailableCommand (eq .Name \"help\")))}}\n  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if not .AllChildCommandsHaveGroup}}\n\nAdditional Commands:{{range $cmds}}{{if (and (eq .GroupID \"\") (or .IsAvailableCommand (eq .Name \"help\")))}}\n  {{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}{{$required := requiredFlagUsages .}}{{if $required}}\n\nRequired Flags:\n{{$required}}{{end}}{{$optional := optionalFlagUsages .}}{{if $optional}}\n\nFlags:\n{{$optional}}{{end}}{{end}}{{if .HasAvailableInheritedFlags}}\n\nGlobal Flags:\n{{.InheritedFlags.FlagUsages | trimTrailingWhitespaces}}{{end}}{{if .HasHelpSubCommands}}\n\nAdditional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}\n  {{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}\n\nUse \"{{.CommandPath}} [command] --help\" for more information about a command.{{end}}\n`\n```\nUsageTemplate is cobra's default usage template with the local flags split into \"Required Flags\" and \"Flags\".\n\n## Variables\n\n```go\nvar (\n\tBuild string\n\tMajor string\n\tMinor string\n\tPatch string\n\n\tCLIVersion Version\n)\n```\n\n```go\nvar ErrAborted = fmt.Errorf(\"aborted\")\n```\nErrAborted is returned when the user declines a confirmation prompt.\n\n```go\nvar ErrActionFailed = errors.New(\"action failed\")\n```\nErrActionFailed is returned by Wait when the resource ends in a failed state.\n\n```go\nvar ErrDryRun = errors.New(\"dry run\")\n```\nErrDryRun is returned by the HTTP layer after --dry-run printed a request instead of sending it. It ends the command successfully.\n\n```go\nvar ErrNoCredentials = errors.New(\"no credentials configured\")\n```\nErrNoCredentials marks a request that could not be sent because no API token (or sign-in) is configured. It exits with ExitAuth.\n\n## Functions\n\n```go\nfunc ArgScope(cmd *cobra.Command) int\n```\n\n```go\nfunc BindLegacyEnv(w io.Writer)\n```\nBindLegacyEnv 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.\n\n```go\nfunc CompleteArgs(sources ...*ArgSource) cobra.CompletionFunc\n```\nCompleteArgs 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).\n\n```go\nfunc Confirm(cmd *cobra.Command, action string, args []string) error\n```\nConfirm 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.\n\n```go\nfunc ConfirmScoped(cmd *cobra.Command, action string, args []string, typed bool) error\n```\nConfirmScoped 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.\n\n```go\nfunc EnumCheck(cmd *cobra.Command, flag string, allowed []string) error\n```\nEnumCheck validates that a changed string flag holds one of the allowed values.\n\n```go\nfunc FitWidth(s string, width int) string\n```\nFitWidth 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.\n\n```go\nfunc FlagErrorf(format string, a ...any) error\n```\nFlagErrorf formats a FlagError.\n\n```go\nfunc FormatCheck(cmd *cobra.Command, flag, format string) error\n```\nFormatCheck validates that a changed string flag parses as format (\"date-time\", \"date\", \"uuid\" or \"email\") before it is converted.\n\n```go\nfunc GroupRunE(cmd *cobra.Command, args []string) error\n```\nGroupRunE 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.\n\n```go\nfunc HandleError(w io.Writer, cmd *cobra.Command, err error) int\n```\nHandleError 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.\n\n```go\nfunc IntPtrOrNil(i int) *int\n```\n\n```go\nfunc Interactive(cmd *cobra.Command) bool\n```\nInteractive reports whether the CLI may prompt: stdin and stderr are terminals and neither --no-input nor the no\\_input config/env key is set.\n\n```go\nfunc IsRequired(f *pflag.Flag) bool\n```\nIsRequired reports whether a flag was marked required with MarkFlagRequired.\n\n```go\nfunc JSONValue(raw, flag string) (any, error)\n```\nJSONValue 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.\n\n```go\nfunc MigrateLegacyConfig(home string, w io.Writer) (configPath string, migrated bool)\n```\nMigrateLegacyConfig 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.\n\n```go\nfunc ParseIntArg(s string) (int, error)\n```\nParseIntArg parses an integer argument where a bad value must not panic (shell completion of later arguments).\n\n```go\nfunc ParseUUIDArg(s string) (uuid.UUID, error)\n```\nParseUUIDArg parses a UUID argument where a bad value must not panic.\n\n```go\nfunc PromptMissing(cmd *cobra.Command, args []string) error\n```\nPromptMissing 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.\n\n```go\nfunc PromptedArgs(cmd *cobra.Command, args []string) []string\n```\nPromptedArgs returns args extended with any values prompted for interactively.\n\n```go\nfunc RegisterArgs(cmd *cobra.Command, specs ...ArgSpec)\n```\nRegisterArgs 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.\n\n```go\nfunc RegisterScopedArgs(cmd *cobra.Command, scope int, specs ...ArgSpec)\n```\nRegisterScopedArgs is RegisterArgs where the first scope args may be left out (the resolver supplies them); given args fill the specs from the end.\n\n```go\nfunc RegisterWaitFlags(cmd *cobra.Command)\n```\nRegisterWaitFlags adds --wait and --wait-timeout to cmd.\n\n```go\nfunc SafeLog(s string, keepColour bool) string\n```\nSafeLog makes remote build logs safe for a terminal: complete CSI and OSC sequences are removed, except SGR colours when keepColour is set, and the rest goes through SafeText. Carriage returns become line breaks.\n\n```go\nfunc SafeText(s string) string\n```\nSafeText replaces control characters other than \\\\n and \\\\t (C0 including ESC, BEL, CR and BS; DEL; C1 such as U+009B CSI) with U+FFFD, so remote text printed to a terminal cannot start escape sequences. Callers that must keep some sequences (e.g. SGR colours in build logs) can split those out and pass the text between them through SafeText.\n\n```go\nfunc ScopeInt(name, v string) (int, error)\n```\nScopeInt parses an id resolved from a flag, the environment or the link, which argument validation never saw.\n\n```go\nfunc StderrWidth() int\n```\nStderrWidth is the terminal width of stderr, or 0 when unknown.\n\n```go\nfunc StringArrayToIntArray(strArr []string) []int\n```\n\n```go\nfunc StringPtrOrNil(s string) *string\n```\n\n```go\nfunc StringToDate(dateStr string) openapi_types.Date\n```\n\n```go\nfunc StringToEmail(email string) openapi_types.Email\n```\nStringToEmail keeps format:email query params converting through utils like every other formatted kind, so generated commands need no extra import.\n\n```go\nfunc StringToInt(s string) int\n```\n\n```go\nfunc StringToTime(dateStr string) time.Time\n```\n\n```go\nfunc StringToUUID(s string) openapi_types.UUID\n```\n\n```go\nfunc Wait(cmd *cobra.Command, body []byte, spec WaitSpec, poll func(ctx context.Context, id string) ([]byte, int, error)) ([]byte, int, error)\n```\nWait 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).\n\n## Types\n\n```go\ntype APIError struct {\n\tStatus        int\n\tMessage       string\n\tErrors        map[string][]string\n\tCorrelationID string\n\tBody          []byte\n}\n```\nAPIError is an HTTP error response from the API.\n\n```go\nfunc NewAPIError(status int, body []byte) *APIError\n```\nNewAPIError decodes the API's error body ({message, errors, correlation\\_id}); an unexpected body is kept verbatim.\n\n```go\nfunc (e *APIError) Error() string\n```\n\n```go\nfunc (e *APIError) ExitCode() int\n```\nExitCode maps the HTTP status to the CLI exit code.\n\n```go\ntype ArgKind int\n```\nArgKind is the type a positional argument must parse as.\n\n```go\nconst (\n\tArgString ArgKind = iota\n\tArgInt\n\tArgUUID\n)\n```\n\n```go\ntype ArgSource struct {\n\tValue string\n\tFetch func(ctx context.Context, args []string) ([]byte, int, error)\n}\n```\nArgSource 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.\n\n```go\ntype ArgSpec struct {\n\tName string // e.g. \"virtual-machine-id\"\n\tKind ArgKind\n}\n```\nArgSpec describes one positional argument of a generated command.\n\n```go\nfunc ArgSpecs(cmd *cobra.Command) []ArgSpec\n```\nArgSpecs returns the positional arguments registered for cmd.\n\n```go\nfunc IntArg(name string) ArgSpec\n```\n\n```go\nfunc StringArg(name string) ArgSpec\n```\n\n```go\nfunc UUIDArg(name string) ArgSpec\n```\n\n```go\ntype Call func(ctx context.Context) ([]byte, int, error)\n```\nCall performs one API request and returns the raw body and status code.\n\n```go\nfunc AllPages(call Call, setPage func(int)) Call\n```\nAllPages 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.\n\n```go\ntype ExitCodeError struct {\n\tCode    int\n\tMessage string\n}\n```\nExitCodeError ends a command with a specific exit code. Message, when set, is printed as the error; a command that already reported the failure itself (for example as JSON on stdout) leaves it empty.\n\n```go\nfunc (e *ExitCodeError) Error() string\n```\n\n```go\ntype FlagError struct{ Err error }\n```\nFlagError is an input mistake (bad flag value, missing argument). The root command prints it with a pointer to --help and exits with ExitUsage.\n\n```go\nfunc (e *FlagError) Error() string\n```\n\n```go\nfunc (e *FlagError) Unwrap() error\n```\n\n```go\ntype Version struct {\n\tMajor, Minor, Patch int\n\tBuild               string\n}\n```\n\n```go\nfunc (v Version) String(withBuild bool) string\n```\n\n```go\ntype WaitSpec struct {\n\tIDField    string\n\tStateField string\n\tDone       []string\n\tFailed     []string\n}\n```\nWaitSpec describes how to recognise the end state of an asynchronous resource.\n\n","path":"github.com/hostinger/mail-api-cli/utils","name":"utils","synopsis":"","isRedistributable":true}
