cmdutil

package
v2.18.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 32 Imported by: 0

Documentation

Index

Constants

View Source
const ClearDescriptionHint = `To clear the description, pass --description "" explicitly.`

ClearDescriptionHint is the RejectEmptyTextFile hint for --description-file.

View Source
const DeprecationDateLayout = "2006-01-02"

DeprecationDateLayout is the layout of the removeAfter date passed to DeprecateFlag.

View Source
const DeprecationMarker = "DEPRECATED(remove-after: "

DeprecationMarker is the prefix of the comment that must accompany every DeprecateFlag call so deprecated code can be found with a single grep.

Variables

This section is empty.

Functions

func AddCustomFieldFlag added in v2.17.0

func AddCustomFieldFlag(cmd *cobra.Command, f *Factory, target *[]string, label, customizedType string)

AddCustomFieldFlag registers the repeatable --custom-field flag on cmd, with shell completion for fields of customizedType. label names the kind of field in the help text, for example "Version custom field".

func AddForceFlag

func AddForceFlag(cmd *cobra.Command, force *bool)

AddForceFlag adds the --force/-f flag to a command.

func AddOutputFlag

func AddOutputFlag(cmd *cobra.Command, format *string)

AddOutputFlag registers --output/-o as a local flag on the given command.

The root command also registers --output/-o as a persistent flag, so every leaf command accepts it automatically. This helper is retained for backward compatibility with command handlers that want the flag's value bound to a local variable (and for unit tests that instantiate leaf commands in isolation, without the root). Local flags shadow the inherited persistent flag, so the end-user behavior is identical.

func AddPaginationFlags

func AddPaginationFlags(cmd *cobra.Command, limit, offset *int)

AddPaginationFlags adds --limit and --offset flags to a command.

func AddTextFileFlag added in v2.14.0

func AddTextFileFlag(cmd *cobra.Command, inlineFlag, fileFlag, shorthand string)

AddTextFileFlag registers fileFlag as the file counterpart of the existing long-text flag inlineFlag (for example --description-file for --description). The value is a path, or "-" to read from standard input. The two flags are mutually exclusive.

Call ReadTextFileFlag in RunE to resolve the value.

func ApplyGlobalFlags added in v2.15.0

func ApplyGlobalFlags(f *Factory, cmd *cobra.Command) error

ApplyGlobalFlags copies the root command's persistent flags (--config, --profile, --server, --api-key, --api-key-file, --no-color, --verbose, --output, --read-only and --header) onto f. The root command calls it from PersistentPreRunE. Completion functions call it too: cobra parses those flags for `redmine __complete`, but never runs PersistentPreRunE for the command being completed, so without it completion would ignore e.g. --config and --profile. Flags the root command does not define are skipped. An invalid --header is an error, so a typo fails before any interactive prompt.

func AttachmentFilename added in v2.15.0

func AttachmentFilename(att *models.Attachment) string

AttachmentFilename returns the server-supplied filename of att reduced to its base component, so a malicious or malformed name (e.g. one containing "../") cannot escape the destination directory.

func BuildErrorEnvelope

func BuildErrorEnvelope(err error) output.ErrorEnvelope

BuildErrorEnvelope produces a structured error payload suitable for JSON rendering. It reuses FormatError's human-readable message (without the hint line), derives a stable code from the underlying api.APIError classification, and carries ErrorHint in the separate hint field.

func CheckDownloadTarget added in v2.15.0

func CheckDownloadTarget(path string, clobber bool) error

CheckDownloadTarget reports whether path may be used as a download destination. A directory or other non-regular file (FIFO, device, socket) is always rejected; an existing file or symlink (dangling or not) is rejected unless clobber is set. A missing path is fine.

func CheckHiddenFilename added in v2.15.0

func CheckHiddenFilename(dir, name string, allowHidden bool) error

CheckHiddenFilename returns a *HiddenFilenameError when name, the sanitized filename an attachment would be saved under in dir, starts with "." and allowHidden is false.

func CheckOutputFlag added in v2.15.0

func CheckOutputFlag(cmd *cobra.Command) error

CheckOutputFlag rejects an explicit --output csv (in any letter case) on cmd, the persistent flag or a leaf command's local one, before any request is made.

func CompleteActivities

func CompleteActivities(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteActivities returns a completion function for the --activity flag.

func CompleteAssignees added in v2.14.0

func CompleteAssignees(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteAssignees returns a completion function for --assignee flags. "me" and "none" are always offered. When the project is known (--project, the default project, or the issue in the first positional argument) the candidates are all of the project's members, users and groups alike, from the memberships endpoint, which non-admins can read. Otherwise it falls back to CompleteUsers.

func CompleteCategories

func CompleteCategories(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteCategories returns a completion function for the --category flag. Requires --project to be set (or a default project in config).

func CompleteCustomFieldValues added in v2.17.0

func CompleteCustomFieldValues(f *Factory, customizedType string) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteCustomFieldValues returns a completion function for --custom-field. Before the '=' it offers "Name=" for the custom fields of customizedType; after "Name=" (or "<id>=") of a list field it offers the possible values. Hits the admin-only /custom_fields.json endpoint, so it silently returns no candidates when the authenticated user lacks access.

func CompleteCustomFields added in v2.6.0

func CompleteCustomFields(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteCustomFields returns a completion function for the custom-fields command argument. Hits the admin-only /custom_fields.json endpoint, so it silently returns no candidates when the authenticated user lacks access.

func CompleteGroups

func CompleteGroups(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteGroups returns a completion function for the --group flag. Returns empty completions gracefully if the user lacks admin privileges.

func CompleteIncludes added in v2.17.0

func CompleteIncludes(allowed map[string]struct{}) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective)

CompleteIncludes returns a shell completion function offering the allowed --include values.

func CompleteIssueListStatus

func CompleteIssueListStatus(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteIssueListStatus returns a completion function for the --status flag on the issues list command, which also accepts special values.

func CompleteOpenVersions

func CompleteOpenVersions(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteOpenVersions returns a completion function for the --version flag that only shows open and locked versions (excludes closed). Useful for create/update commands where closed versions aren't valid targets.

func CompleteOutputFormat

func CompleteOutputFormat(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteOutputFormat provides static completions for the --output flag.

func CompletePriorities

func CompletePriorities(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompletePriorities returns a completion function for the --priority flag.

func CompleteProjects

func CompleteProjects(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteProjects returns a completion function for the --project flag.

func CompleteRoles added in v2.6.0

func CompleteRoles(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteRoles returns a completion function for role-related flags.

func CompleteStatuses

func CompleteStatuses(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteStatuses returns a completion function for the --status flag.

func CompleteTrackers

func CompleteTrackers(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteTrackers returns a completion function for the --tracker flag.

func CompleteUserStatus

func CompleteUserStatus(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteUserStatus provides static completions for user --status flag.

func CompleteUsers

func CompleteUsers(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteUsers returns a completion function for user-related flags. "me" is always offered because the resolver handles it without listing users; the rest of the list comes from /users.json, which requires admin. Non-admin sessions degrade gracefully to just the "me" candidate.

func CompleteVersionSharing added in v2.4.0

func CompleteVersionSharing(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteVersionSharing provides static completions for version --sharing flag.

func CompleteVersionStatus

func CompleteVersionStatus(_ *cobra.Command, _ []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteVersionStatus provides static completions for version --status flag.

func CompleteVersions

func CompleteVersions(f *Factory) func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective)

CompleteVersions returns a completion function for the --version flag that shows all versions including closed ones. Requires --project to be set (or a default project in config).

func ConfirmAction

func ConfirmAction(in io.Reader, errOut io.Writer, message string) bool

ConfirmAction prompts the user to confirm a destructive action. Returns true if the user confirms with "y" or "yes". If in is not interactive or the user declines, returns false.

func Context added in v2.15.0

func Context(cmd *cobra.Command) context.Context

Context returns the context a command runs under: the one main passes to ExecuteContext, which is cancelled on the first SIGINT/SIGTERM. A command whose RunE is invoked without Execute has none, so this falls back to context.Background().

func CustomFieldValidationHint added in v2.17.0

func CustomFieldValidationHint(raws []string) string

CustomFieldValidationHint explains the usual cause of a validation failure when a field was passed several times, and is empty otherwise.

func DefaultProject

func DefaultProject(f *Factory, project string) string

DefaultProject returns the given project string if non-empty, otherwise falls back to the configured default project. If the config cannot be loaded the original (empty) value is returned.

func DefaultProjectID

func DefaultProjectID(ctx context.Context, f *Factory, project string) (string, error)

DefaultProjectID applies the default-project fallback and resolves to a numeric ID string. Returns ("", nil) when no project is specified.

func DefaultProjectIdentifier

func DefaultProjectIdentifier(ctx context.Context, f *Factory, project string) (string, error)

DefaultProjectIdentifier applies the default-project fallback and resolves to the canonical identifier. Returns ("", nil) when no project is specified.

func DeprecateFlag added in v2.17.0

func DeprecateFlag(cmd *cobra.Command, name, replacement, removeAfter string)

DeprecateFlag marks the flag name on cmd as deprecated in favour of replacement (for example "--include users"). Cobra hides the flag from help and prints a warning to stderr when it is used, so machine-readable stdout stays clean. removeAfter is the last day (YYYY-MM-DD) the flag may still exist; the deprecation test in internal/cmd fails after that date.

Every call site must carry a marker comment that names the flag as --name, so the code to delete can be found with `grep -rn "DEPRECATED(remove-after" . --exclude-dir=node_modules`:

// DEPRECATED(remove-after: 2027-01-31): --include-users alias; delete the flag, the code reading it and its tests
cmdutil.DeprecateFlag(cmd, "include-users", "--include users", "2027-01-31")

Tests that reference a deprecated flag carry the same marker, so the grep also lists everything that goes stale. The expiry test only scans non-test .go call sites. Deprecated flags are not documented in user-facing docs.

To remove a deprecated flag, delete the flag definition, the code that reads it, its tests, and every marker comment.

func DetectContentType added in v2.6.0

func DetectContentType(f *os.File, path string) string

DetectContentType resolves a MIME type from the file extension, falling back to sniffing the first 512 bytes. The file position is left unspecified; the caller must seek before reading the file for upload.

func ErrorHint added in v2.14.0

func ErrorHint(err error) string

ErrorHint returns the actionable hint for err, or "" when there is none. An explicit hint attached via WithHint wins over generic, status-based hints.

func FormatError

func FormatError(err error) string

FormatError converts an API error into a user-friendly message, followed by a "Hint:" line when ErrorHint has a next step for it.

func FormatErrorMessage added in v2.14.0

func FormatErrorMessage(err error) string

FormatErrorMessage renders the human-readable description of err without any hint. Use it when the error is printed inline and also returned, so the hint is shown once by the top-level error path.

func HandleEmpty

func HandleEmpty[T any](p output.Printer, items []T, noun string) bool

HandleEmpty checks whether items is empty. For empty slices it emits an empty JSON array (when the output format is JSON) or a warning (for other formats) and returns true. The caller should return nil when true.

func HasNoJSONOutput added in v2.14.0

func HasNoJSONOutput(cmd *cobra.Command) bool

HasNoJSONOutput reports whether cmd was marked with MarkNoJSONOutput.

func HasRepeatedCustomFieldKey added in v2.17.0

func HasRepeatedCustomFieldKey(raws []string) bool

HasRepeatedCustomFieldKey reports whether a field key occurs more than once in raws. Malformed entries report false.

func MarkNoJSONOutput added in v2.14.0

func MarkNoJSONOutput(cmd *cobra.Command)

MarkNoJSONOutput declares that cmd never prints JSON to stdout.

func MergeIncludes added in v2.17.0

func MergeIncludes(includes []string, extra ...string) []string

MergeIncludes appends extra to includes, trimming whitespace and dropping blanks and duplicates while preserving first-seen order.

func OpsLimit added in v2.5.0

func OpsLimit(cliLimit int) int

OpsLimit translates a CLI --limit value to the convention used by the ops layer. The CLI treats --limit 0 as "no limit" while ops applies an MCP-safety default of 50 for zero. Any caller that wants to honor the CLI semantics passes its raw flag value through OpsLimit before constructing an ops input.

func ParseCustomFieldValues added in v2.6.0

func ParseCustomFieldValues(ctx context.Context, client *api.Client, raws []string, customizedType string) (models.CustomFieldValues, error)

ParseCustomFieldValues parses repeated --custom-field key=value entries into the custom_field_values payload keyed by custom field ID.

Numeric keys are used as IDs without a lookup. Other keys are resolved by name against /custom_fields.json (admin-only) in a single request, limited to fields of customizedType. A field given several times collects its values in flag order, which is how multi-value fields are written. A lone "key=" clears the field.

func ParseKeyValuePairs added in v2.6.0

func ParseKeyValuePairs(raws []string, flagName string) (map[string]string, error)

ParseKeyValuePairs parses repeated `key=value` flag inputs into a map. The flagName is used to build clear error messages ("--filter %q must be key=value"). Empty keys and missing `=` are rejected.

func PrepareInteractiveCommand

func PrepareInteractiveCommand(cmd *cobra.Command, f *Factory) error

PrepareInteractiveCommand opts a command out of structured output modes. It rejects an explicitly requested --output or --jq flag and otherwise forces the command to render using the default interactive/table path, ignoring any configured output_format.

The rejection is checked before the format is reset, so the factory still carries the requested format and the error is rendered accordingly: as the JSON error envelope for --jq or --output json, as text otherwise.

func ReadSecretFile added in v2.15.0

func ReadSecretFile(flagName, path string, stdin io.Reader) (string, error)

ReadSecretFile reads the secret named by a file flag such as --api-key-file from path, or from stdin when path is "-", so the secret never appears in argv. Surrounding whitespace (such as the trailing newline of `echo` or an editor) is trimmed. An empty path, an empty secret and a file larger than 64 KiB are errors; flagName prefixes every message.

func ReadTextFile added in v2.14.0

func ReadTextFile(path string, stdin io.Reader) (string, error)

ReadTextFile reads a UTF-8 text file, or standard input when path is "-". The content is returned as read, except that a leading UTF-8 byte-order mark is dropped. Line endings (including CRLF) and surrounding whitespace are preserved.

func ReadTextFileFlag added in v2.14.0

func ReadTextFileFlag(cmd *cobra.Command, stdin io.Reader, inlineFlag, fileFlag string, dst *string) (bool, error)

ReadTextFileFlag resolves a long-text flag pair registered with AddTextFileFlag. When fileFlag was given, the file (or stdin for "-") is read and stored in *dst without trimming, so trailing newlines and whitespace survive (see ReadTextFile). It reports whether either flag was set, which is what callers should use instead of cmd.Flags().Changed(inlineFlag).

func RejectEmptyTextFile added in v2.14.0

func RejectEmptyTextFile(cmd *cobra.Command, fileFlag, content, hint string) error

RejectEmptyTextFile returns an error when fileFlag was given but its file (or stdin) was empty or held only whitespace. An empty file is almost always a mistake (a failed redirect, the wrong path): for notes and comments it would be a silent no-op, for descriptions it would silently wipe the existing text. Clearing a field stays possible through the inline flag (for example --description ""). hint, when not empty, is attached as the error's recovery hint. The check never alters content.

func RejectMultipleStdinFlags added in v2.14.0

func RejectMultipleStdinFlags(cmd *cobra.Command, fileFlags ...string) error

RejectMultipleStdinFlags returns an error when more than one of the given file flags reads from standard input ("-"); stdin can only be consumed once.

func RenderCollection

func RenderCollection[T any](printer output.Printer, items []T, headers []string, rowBuilder RowBuilder[T])

RenderCollection renders a simple collection in JSON or table form. It is intended for list-style commands whose table rows map one-to-one to items.

func RequireProjectIdentifier

func RequireProjectIdentifier(ctx context.Context, f *Factory, project string) (string, error)

RequireProjectIdentifier applies the default-project fallback, ensures a project was provided, and resolves to the canonical identifier.

func ResolveDateKeyword added in v2.4.0

func ResolveDateKeyword(input string) string

ResolveDateKeyword expands the `today` keyword to today's date in the YYYY-MM-DD format the Redmine API expects. Any other input (including the empty string and a plain ISO date) is returned unchanged so callers can keep their existing defaulting logic.

func ResolveProjectID

func ResolveProjectID(ctx context.Context, f *Factory, input string) (string, error)

ResolveProjectID resolves a project input to its numeric ID string.

func ResolveProjectIdentifier

func ResolveProjectIdentifier(ctx context.Context, f *Factory, input string) (string, error)

ResolveProjectIdentifier resolves a project input to its canonical identifier.

func SaveAttachmentToDir added in v2.8.0

func SaveAttachmentToDir(ctx context.Context, client *api.Client, att *models.Attachment, dir string, opts SaveOptions) (string, int64, error)

SaveAttachmentToDir streams an attachment into dir using its sanitized real filename (see AttachmentFilename) and returns the path written and the number of bytes streamed. The directory is created if it does not exist.

func SaveAttachmentToDirAs added in v2.15.0

func SaveAttachmentToDirAs(ctx context.Context, client *api.Client, att *models.Attachment, dir, name string, opts SaveOptions) (string, int64, error)

SaveAttachmentToDirAs is SaveAttachmentToDir with an explicit filename, which must already be a sanitized base name (see AttachmentFilename and UniqueAttachmentFilenames). A name starting with "." is refused unless opts.AllowHidden is set (see CheckHiddenFilename).

func SaveAttachmentToFile added in v2.8.0

func SaveAttachmentToFile(ctx context.Context, client *api.Client, att *models.Attachment, path string, opts SaveOptions) (int64, error)

SaveAttachmentToFile streams an attachment to the exact path given and returns the number of bytes written. The parent directory must already exist. A new file gets the permissions os.Create would give it (0o644 under the usual umask); with opts.Clobber a replaced regular file keeps its previous permissions.

The bytes are streamed into a temporary file in the destination directory, fsynced, and only then moved into place, so a failed download never touches an existing file and never leaves a partial one behind. Cancelling ctx (the first Ctrl-C) fails the download and removes the temporary file; only a process killed outright (SIGKILL, a second Ctrl-C) may leave a hidden .redmine-download-*.tmp. The move replaces the directory entry itself: a symlink at path is replaced, never written through.

Without opts.Clobber an existing path is an error. The final move then uses a hard link, which fails atomically if path appeared during the download; only where hard links are unsupported (some filesystems, cross-device mounts) does it fall back to a re-check followed by a rename, which leaves a small window between the check and the rename.

The exception is a path that is, or is a symlink to, a character device or a FIFO, such as /dev/null, /dev/stdout or a named pipe: there is no file to replace, so the bytes are written into it directly, with or without opts.Clobber. Other non-regular files, such as directories, are still an error.

func SaveStreamToFile added in v2.17.0

func SaveStreamToFile(ctx context.Context, path string, opts SaveOptions, fetch StreamFunc) (int64, error)

SaveStreamToFile is SaveAttachmentToFile for any streamed payload (such as an attachment thumbnail): fetch writes into a temporary file that is moved into place on success, with the same no-clobber, atomic-replace and device/FIFO behaviour documented on SaveAttachmentToFile.

func SortedIncludeKeys added in v2.17.0

func SortedIncludeKeys(m map[string]struct{}) string

SortedIncludeKeys renders the allowed include keys alphabetically so error messages stay stable.

func UniqueAttachmentFilenames added in v2.15.0

func UniqueAttachmentFilenames(atts []models.Attachment) []string

UniqueAttachmentFilenames returns one sanitized filename per attachment, deduplicated so a bulk download never writes two attachments to the same path. Of the attachments sharing a name, the newest (highest ID) keeps it, since a corrected file is usually re-uploaded under the same name; older ones become "<stem> (attachment-<id>)<ext>". An attachment whose own name is unique keeps it even if it looks like such a suffixed name. Names are compared case-insensitively, whatever the destination filesystem, because the common desktop filesystems (APFS, NTFS) are case-insensitive.

func UploadAttachments

func UploadAttachments(ctx context.Context, client *api.Client, paths []string) ([]models.Upload, error)

UploadAttachments uploads each given file path and returns Upload references suitable for inclusion in an issue create/update payload.

func ValidateIncludes added in v2.17.0

func ValidateIncludes(values []string, allowed map[string]struct{}) error

ValidateIncludes rejects any --include value that is not in allowed. Blank entries are ignored.

func WarnPagination

func WarnPagination(p output.Printer, r PaginationResult)

WarnPagination emits a pagination warning when there are more results than shown. No warning is emitted when limit is 0 (all results requested) or when the output format is JSON.

func WithHint added in v2.14.0

func WithHint(err error, hint string) error

WithHint attaches hint to err. It returns err unchanged when err is nil or hint is empty.

func WithValidationHint added in v2.17.0

func WithValidationHint(err error, hints ...string) error

WithValidationHint attaches the non-empty hints, joined by a space, to a validation (422) API error. Other errors pass through unchanged.

Types

type CodedError added in v2.14.0

type CodedError struct {
	Code    string
	Message string
	Details []string
	// Err is the underlying error, kept for errors.As/errors.Is.
	Err error
}

CodedError is a command failure that carries its own stable JSON error code (see the output.ErrCode* constants) and optional details. The normal error path renders it like any other error: Error() in text mode, and an error envelope with Code, Message and Details in JSON mode.

func (*CodedError) Error added in v2.14.0

func (e *CodedError) Error() string

Error renders the message followed by the details, one per line, in the same style FormatError uses for validation errors.

func (*CodedError) Unwrap added in v2.14.0

func (e *CodedError) Unwrap() error

type CustomFieldPair added in v2.17.0

type CustomFieldPair struct {
	Key   string
	Value string
}

CustomFieldPair is one --custom-field entry, in flag order.

func ParseCustomFieldPairs added in v2.17.0

func ParseCustomFieldPairs(raws []string) ([]CustomFieldPair, error)

ParseCustomFieldPairs splits repeated --custom-field entries at the first '='. The key is trimmed; the value is kept verbatim, so spaces and further '=' characters survive. A missing '=' and an empty key are rejected.

type DeprecatedFlag added in v2.17.0

type DeprecatedFlag struct {
	Command     string
	Name        string
	RemoveAfter string
}

DeprecatedFlag describes a flag registered through DeprecateFlag.

func DeprecatedFlags added in v2.17.0

func DeprecatedFlags(cmd *cobra.Command) []DeprecatedFlag

DeprecatedFlags returns every flag on cmd and its subcommands that was registered through DeprecateFlag.

type DestinationExistsError added in v2.15.0

type DestinationExistsError struct {
	Path string
}

DestinationExistsError reports that a download target already exists and --clobber was not given. It unwraps to fs.ErrExist.

func (*DestinationExistsError) Error added in v2.15.0

func (e *DestinationExistsError) Error() string

func (*DestinationExistsError) Unwrap added in v2.15.0

func (e *DestinationExistsError) Unwrap() error

type Factory

type Factory struct {
	ConfigPath string
	Verbose    bool

	// Runtime overrides from CLI flags (highest precedence).
	ProfileOverride string
	ServerOverride  string
	APIKeyOverride  string
	NoColorOverride bool

	// APIKeyFile is the --api-key-file path ("-" reads stdin). Its contents
	// are used like APIKeyOverride, without exposing the key in argv.
	APIKeyFile string

	// ReadOnly, when non-nil, is the --read-only flag value and overrides
	// both REDMINE_READ_ONLY and the per-profile config (highest precedence).
	ReadOnly *bool

	// Headers holds the repeatable --header flag values ("Name: value"). They
	// are merged over the profile's configured headers, replacing any entry
	// with the same name.
	Headers []string

	// OutputFormat is set by the root persistent --output/-o flag and used
	// as the default format when commands call Printer("").
	OutputFormat string

	// JQ is the compiled root --jq expression. When set, every JSON
	// document a Printer emits is filtered through it.
	JQ *output.JQFilter

	IOStreams *IOStreams
	// contains filtered or unexported fields
}

Factory provides lazy access to configuration, API client, and output printer.

func NewFactory

func NewFactory() *Factory

NewFactory creates a new Factory with default I/O streams.

func (*Factory) APIKeyFromFlags added in v2.18.0

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

APIKeyFromFlags returns the API key given by --api-key or --api-key-file ("" when neither is set). It shares the cached read with Config, so a key read from stdin is available to both.

func (*Factory) ApiClient

func (f *Factory) ApiClient() (*api.Client, error)

ApiClient returns an API client (cached after first call).

func (*Factory) Config

func (f *Factory) Config() (*config.Config, error)

Config returns the loaded configuration (cached after first call). CLI flag overrides carry the highest precedence: ServerOverride and APIKeyOverride (or the contents of APIKeyFile) are resolved inside Load (before any keyring lookup), while NoColorOverride is applied afterward.

func (*Factory) DebugLogger

func (f *Factory) DebugLogger() *debug.Logger

DebugLogger returns the debug logger, creating it on first call.

func (*Factory) JQError added in v2.14.0

func (f *Factory) JQError() error

JQError returns the first runtime error raised while applying --jq to a command's output, or nil.

func (*Factory) Printer

func (f *Factory) Printer(format string) output.Printer

Printer creates and returns a new output printer for the given format.

func (*Factory) Warn added in v2.15.0

func (f *Factory) Warn(msg string)

Warn prints msg as a warning to stderr, once per distinct message for the lifetime of the Factory. It is safe for concurrent use.

type HiddenFilenameError added in v2.15.0

type HiddenFilenameError struct {
	Name string
	Path string
}

HiddenFilenameError reports that an attachment would be saved under its server-supplied filename, that name starts with "." and --allow-hidden was not given. A server could otherwise plant a dotfile such as .bashrc, .envrc or .npmrc in the destination directory.

func (*HiddenFilenameError) Error added in v2.15.0

func (e *HiddenFilenameError) Error() string

type HintError added in v2.14.0

type HintError struct {
	Err  error
	Hint string
}

HintError decorates an error with a short, actionable next step (e.g. the command that lists valid values). FormatError renders the hint on its own "Hint:" line and BuildErrorEnvelope exposes it as error.hint, so both human and JSON consumers learn how to recover without parsing the message.

func (*HintError) Error added in v2.14.0

func (e *HintError) Error() string

func (*HintError) Unwrap added in v2.14.0

func (e *HintError) Unwrap() error

type IOStreams

type IOStreams struct {
	In     io.Reader
	Out    io.Writer
	ErrOut io.Writer
	IsTTY  bool
}

IOStreams holds the standard I/O streams.

type PaginationResult

type PaginationResult struct {
	Shown  int    // Number of items displayed
	Total  int    // Total count from the API
	Limit  int    // The --limit value used
	Offset int    // The --offset value used
	Noun   string // Plural noun for the message, e.g. "issues"
}

PaginationResult holds the information needed to emit a pagination warning.

type RowBuilder

type RowBuilder[T any] func(item T) []string

RowBuilder builds one table row for an item; it may apply ANSI/color formatting.

type SaveOptions added in v2.15.0

type SaveOptions struct {
	// Clobber allows replacing a file that already exists at the destination.
	// Without it, an existing entry (including a dangling symlink) is an error.
	Clobber bool
	// AllowHidden allows saving an attachment under its own filename when
	// that name starts with "." (--allow-hidden). Without it such a name is
	// an error; see CheckHiddenFilename.
	AllowHidden bool
}

SaveOptions controls how an attachment download is written to disk.

type SilentError

type SilentError struct{ Code int }

SilentError is returned when the error message has already been printed or should be suppressed. main.go will still exit with the given code.

func (*SilentError) Error

func (e *SilentError) Error() string

type StreamFunc added in v2.17.0

type StreamFunc func(ctx context.Context, w io.Writer) (int64, error)

StreamFunc writes a remote payload to w and returns the bytes written.

Jump to

Keyboard shortcuts

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