cmdutil

package
v1.0.44892-pre Latest Latest
Warning

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

Go to latest
Published: Jul 15, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package cmdutil provides shared helpers used by command packages. Business logic belongs in internal/<domain>/; this package is for command-layer plumbing that would otherwise be copy-pasted.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIErr

func APIErr(err error, subject, notFoundCode, notFoundMsg string, notFoundSuggestions ...string) *clierrors.CLIError

APIErr converts an apiclient error into a structured CLIError.

notFoundCode and notFoundMsg customise the 404 case for the calling resource (e.g. "run.not_found", "No run found for %q"). notFoundMsg is passed through fmt.Sprintf with subject as the single argument.

Optional notFoundSuggestions are appended to the 404 error (useful for pointing users toward a list command, for example).

func AddGroup

func AddGroup(parent *cobra.Command, title string, cmds ...*cobra.Command)

func AddJQFlag

func AddJQFlag(cmd *cobra.Command)

AddJQFlag registers --jq on cmd and binds it to out.

func AddJSONFlag

func AddJSONFlag(cmd *cobra.Command, out *bool)

AddJSONFlag registers --json on cmd and binds it to out.

func AddOrgFlag

func AddOrgFlag(cmd *cobra.Command, org *string, opts OrgFlag)

AddOrgFlag registers the canonical --org flag on cmd, binding it to org and marking it required when opts.Required is set. It is the single source of the flag name and help wording shared by every org-scoped command; pair it with ResolveOrgSlugOrID to turn the value into an org UUID.

func AddOutputFlag

func AddOutputFlag(cmd *cobra.Command, out *string, what string)

AddOutputFlag registers --output/-o on cmd, binding it to out. The what argument names the content being written, e.g. "the manpage", and is used in the flag description: "Write <what> to this file instead of stdout".

func AppURL

func AppURL(ctx context.Context) (string, error)

func CheckTelemetry

func CheckTelemetry(ctx context.Context) bool

func CodeFence

func CodeFence(s string) string

CodeFence returns a backtick fence long enough to wrap s verbatim: at least three backticks, and always one more than the longest run of backticks inside s, so a run of backticks in the content cannot prematurely close the block (the CommonMark fencing rule). Use it when embedding arbitrary captured output — step logs, test messages — in a markdown code block.

func ConfigPath

func ConfigPath(cmd *cobra.Command) string

func ConfirmOrForce

func ConfirmOrForce(ctx context.Context, streams iostream.Streams, force bool, prompt string, abortErr, requireForceErr *clierrors.CLIError) error

ConfirmOrForce requires user confirmation of a destructive operation.

  • If force is true, returns nil immediately (scripting / non-interactive path).
  • In a TTY, shows prompt and returns abortErr if the user declines.
  • Outside a TTY, returns requireForceErr with the standard --force suggestion appended so callers don't have to repeat it.

Construct abortErr and requireForceErr with domain-specific codes and messages; the standard suggestion text is added automatically to requireForceErr.

func ContextsURL

func ContextsURL(appURL, orgSlug string) (string, error)

ContextsURL returns the CircleCI contexts settings page URL for the given org slug.

func DeployURL

func DeployURL(appURL string, proj *apiclient.ProjectInfo) string

DeployURL returns the CircleCI deploys page URL for the given project.

func DisableEverything

func DisableEverything(cmd *cobra.Command)

func DisableTelemetry

func DisableTelemetry(cmd *cobra.Command)

func DisableTelemetryForSubcommands

func DisableTelemetryForSubcommands(cmd *cobra.Command)

func GetAgentName

func GetAgentName(ctx context.Context) string

func GetConfig

func GetConfig(ctx context.Context) *config.Config

func GetTelemetry

func GetTelemetry(ctx context.Context) *telemetry.Sender

func GetVersion

func GetVersion(ctx context.Context) string

func GitDetectErr

func GitDetectErr(err error, suggestions ...string) *clierrors.CLIError

GitDetectErr wraps a gitremote.Detect error into a structured CLIError.

The standard "run from inside a git repository" suggestion is always included as the first suggestion. Pass additional command-specific suggestions as variadic args (e.g. "Or specify the project with --project gh/org/repo").

func GroupRunE

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

GroupRunE is the RunE for group (parent) commands that have no action of their own. It shows help when invoked with no arguments and returns a structured error for unknown subcommands.

func InferOrgID

func InferOrgID(ctx context.Context, client *apiclient.Client) string

InferOrgID best-effort resolves the org UUID for the current directory's CircleCI project. Detection follows gitremote.Detect's resolution order — a `circleci project link` binding (.circleci/info.yml) takes precedence over the git remote, so an explicit link wins when the remote is not the right answer (repository renames, forks, standalone projects). When the link recorded the org as a UUID it is used directly; otherwise the resolved project is looked up through the API to recover its owning org.

It is the lenient counterpart to ResolveOrgSlugOrID, for commands where the org is an optional convenience rather than required — e.g. config compilation passes it so private and namespaced orbs resolve without an explicit --org. It returns "" (with no error) whenever the org cannot be determined — not a git checkout, an unrecognised remote, or a failed project lookup — so callers fall back to public-only behaviour instead of failing.

func IsEverythingDisabled

func IsEverythingDisabled(cmd *cobra.Command) bool

func IsSecureStorage

func IsSecureStorage(cmd *cobra.Command) bool

IsSecureStorage reports whether the API token should be stored in (and read from) the OS keyring rather than the plaintext config file.

It is the single decision point feeding both the load path (root PreRun) and every write path (auth, setting set, setup). Secure storage requires both that the user did not opt out via --insecure-storage and that the keyring backend is actually reachable. The latter check keeps headless/CI Linux hosts — which have no D-Bus session bus — from hitting a confusing `exec: "dbus-launch": executable file not found` failure; instead they transparently fall back to the config file, exactly as --insecure-storage does.

func IsTelemetryDisabled

func IsTelemetryDisabled(cmd *cobra.Command) bool

IsTelemetryDisabled reports whether telemetry has been disabled for this specific command via DisableTelemetry (independent of the user's global telemetry preference).

func JobURL

func JobURL(appURL string, workflowID, jobID uuid.UUID) string

func KeyringConnectHint

func KeyringConnectHint(keyringErr error) string

KeyringConnectHint returns a one-line, actionable suggestion when secure storage was requested but the keyring could not be reached for a reason the user can fix. It returns "" when there is nothing actionable to suggest.

The only such case today is a strict snap whose password-manager-service interface is not connected: the session bus exists but the sandbox denies the connection (keyring.ErrAccessDenied). We detect the snap via the SNAP_* environment variables snapd injects, and use the running instance name so the suggested command is correct even for a parallel install.

func LoadClient

func LoadClient(ctx context.Context) (*apiclient.Client, error)

LoadClient reads the CLI config, validates that a token is present, and returns an authenticated API client. On failure it returns a structured CLIError ready to be returned directly from a RunE handler.

Honors a --config path set by the root PersistentPreRunE via WithConfigPath.

func OpenOutput

func OpenOutput(path string, def io.Writer) (io.Writer, func() error, error)

OpenOutput resolves the destination for a command supporting --output. When path is empty it returns def (the command's normal stdout) with a no-op closer; otherwise it creates the file (along with any missing parent directories) and returns it with its Close method. Callers should always defer the returned closer.

func ParseSlug

func ParseSlug(slug string) (vcs, org, repo string, err error)

ParseSlug splits a project slug "vcs/org/repo" into its three components.

func ProjectURL

func ProjectURL(appURL, slug string) (string, error)

ProjectURL returns the CircleCI project page URL for the given project slug.

func RecordTelemetry

func RecordTelemetry(cmd *cobra.Command)

func RecordTelemetryForSubcommands

func RecordTelemetryForSubcommands(cmd *cobra.Command)

func RecordTelemetryNow

func RecordTelemetryNow(cmd *cobra.Command)

func RepoSlug

func RepoSlug(repoURL string) string

RepoSlug reduces a repository URL to its "org/repo" form, e.g. "https://github.com/acme/web" → "acme/web". It returns "" for an empty URL and the input unchanged if it cannot be parsed. Used to label cross-project run listings ("my runs" and the run picker's my-runs scope) from each run's repository URL. (When only a project UUID is known, apiclient.GetProjectByID can resolve a name, but the run listings do not currently do so.)

func RequireArgs

func RequireArgs(args []string, names ...string) error

RequireArgs returns a structured CLIError if args contains fewer elements than the number of names provided. Each name describes an expected positional argument (e.g. "workflow-id", "resource-class") and appears in the error message as <name>.

Use alongside cobra.MaximumNArgs(N) so that too many args are still rejected by Cobra, while the missing-arg case produces a structured error from RunE.

func RequireFlag

func RequireFlag(name string) error

RequireFlag returns a structured CLIError reporting that a required flag was not set. name is the long flag name without the leading dashes (e.g. "org-id").

func ResolveOrgSlug

func ResolveOrgSlug(orgSlug, cmdName string) (string, error)

ResolveOrgSlug returns orgSlug as-is when non-empty. Otherwise it derives the organization slug (vcs/org, e.g. gh/myorg) from the current git remote. It makes no API call — use this for endpoints keyed on an owner slug rather than an org UUID (see ResolveOrgSlugOrID for the UUID case).

cmdName is included in the GitDetectErr suggestion text so users see the exact override flag for the command they invoked, e.g. "circleci context list".

func ResolveOrgSlugOrID

func ResolveOrgSlugOrID(ctx context.Context, client *apiclient.Client, ref, cmdName string) (uuid.UUID, error)

ResolveOrgSlugOrID resolves an organization reference to its UUID. The reference may be:

  • an org UUID (e.g. f22b6566-597d-46d5-ba74-99ef5bb3d85c), used as-is;
  • an org slug (e.g. gh/myorg), looked up through the API;
  • empty, in which case the org is inferred from the current git remote.

cmdName is included in the GitDetectErr suggestion text so users see the exact override flag for the command they invoked, e.g. "circleci runner instance list".

func ResolveProjectID

func ResolveProjectID(ctx context.Context, client *apiclient.Client, projectSlug, projectID string) (string, error)

ResolveProjectID returns projectID as-is when non-empty. Otherwise it resolves the project from the slug (--project flag or git remote) to recover its UUID.

func ResolveProjectSlug

func ResolveProjectSlug(projectSlug string) (string, error)

ResolveProjectSlug returns projectSlug as-is when non-empty. Otherwise it detects the slug from the git remote. Unlike ResolveProjectID this does not make an API call and does not return a UUID — use it for endpoints that require a slug in the path (e.g. POST /project/{vcs}/{org}/{repo}/pipeline/run).

func RunSlugURL

func RunSlugURL(appURL string, slug string) (string, error)

func RunURL

func RunURL(appURL string, id uuid.UUID) string

RunURL returns the CircleCI pipelines page URL for the given project slug.

func RunnersURL

func RunnersURL(appURL, orgSlug string) (string, error)

RunnersURL returns the CircleCI runners inventory page URL for the given org slug.

func VCSSlug

func VCSSlug(provider string) string

VCSSlug maps API provider strings to the slug prefix used in CircleCI URLs (e.g. "GitHub" → "gh").

func WithAgentName

func WithAgentName(ctx context.Context, name string) context.Context

func WithConfig

func WithConfig(ctx context.Context, cfg *config.Config) context.Context

WithConfig returns a copy of ctx carrying the given config file path. The path is read by LoadClient to locate the config file.

func WithTelemetry

func WithTelemetry(ctx context.Context, tc *telemetry.Sender) context.Context

func WithVersion

func WithVersion(ctx context.Context, version string) context.Context

func WorkflowURL

func WorkflowURL(appURL string, id uuid.UUID) string

func WriteJSON

func WriteJSON(w io.Writer, v any) error

WriteJSON encodes v as indented JSON to w. Use streams.Out as the writer. Returns the encoder error, if any.

Types

type OrgFlag

type OrgFlag struct {
	// Purpose, when set, is appended to describe what the organization scopes,
	// e.g. "for private orb resolution" or "to claim the namespace for". Omit
	// the leading space.
	Purpose string
	// Required marks --org required and appends "(required)" to its
	// description. Use it for commands with no git-remote fallback. It is
	// mutually exclusive with DefaultsToGitRemote.
	Required bool
	// DefaultsToGitRemote appends "; defaults to git remote" to the description.
	// Set it for commands that infer the org from the current repository when
	// --org is omitted. Ignored when Required is true.
	DefaultsToGitRemote bool
}

OrgFlag configures the canonical --org flag added by AddOrgFlag. The flag always accepts an organization slug (e.g. gh/myorg) or a UUID; resolve its value to a UUID with ResolveOrgSlugOrID.

Jump to

Keyboard shortcuts

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