cli

package
v0.14.2 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 51 Imported by: 0

Documentation

Overview

Package cli is the cobra-free presentation and error layer the command packages share. It owns the JSON envelope and its byte-clean writers, the human/plain renderers, output-mode detection, terminal sanitization, the verb and output-schema registries, and the errtax-backed error mapping. Staying free of any cobra dependency lets the command packages under internal/cli/* and cmdutil build on it without an import cycle.

Index

Constants

View Source
const (
	ErrorTypeAuth       = errtax.TypeAuth
	ErrorTypeNotFound   = errtax.TypeNotFound
	ErrorTypeValidation = errtax.TypeValidation
	ErrorTypeRateLimit  = errtax.TypeRateLimit
	ErrorTypeServer     = errtax.TypeServer
)

The taxonomy types, re-exported under cli's historical names.

View Source
const LevelSuccess clog.Level = clog.LevelDry + 1

LevelSuccess is the custom clog level for completion lines of Jira mutations that actually succeeded — visually distinct from the INF lines informational reads emit, so a scan of scrollback separates "changed something" from "looked at something". It sits between Dry (2) and Warn (5), mirroring clog's own custom-level example, and registration makes it round-trip through ParseLevel/MarshalText so level filtering keeps working.

Variables

View Source
var ClassifyUntypedProbe func(error)

ClassifyUntypedProbe is a test seam: when non-nil, classifyUntyped reports every error that reaches the legacy substring classifier, so a test can prove an intentional command error is typed rather than substring-guessed. Nil in production; exported because the probing tests drive real commands from outside this package. Tests that set it must not run in parallel.

View Source
var OutputModeValues = []string{"auto", "human", "json", "compact"}

OutputModeValues lists the accepted --output values for help text and shell completion.

Functions

func AggregateCode added in v0.10.1

func AggregateCode(top Error) errtax.Code

AggregateCode is the errtax code a multi-key partial-failure should carry, derived from the worst already-classified per-key failure rather than re-guessed from the summary string. Falls back to the type's default code, then to validation, so the aggregate is never uncoded.

func ClearJQProgram added in v0.11.0

func ClearJQProgram()

ClearJQProgram removes any active filter — the fresh-invocation reset, and the disarm writeJQ performs before reporting a runtime failure so the resulting error envelope prints unfiltered.

func CompileJQ added in v0.11.0

func CompileJQ(expr string) (*gojq.Code, error)

CompileJQ parses and compiles a --jq expression. Failures come back as the typed input error (exit 3, code jq_expression_invalid) with gojq's position-carrying message.

func ExitCode

func ExitCode(err Error) int

ExitCode maps a structured Error to its process exit code: a registered code's pinned exit (canceled=6 and timeout=7 live in the registry as per-code rows), else the type's default.

func ForeignFlagSuggestions added in v0.9.0

func ForeignFlagSuggestions(flag string) []string

ForeignFlagSuggestions resolves a flag name against the foreign-CLI table, tolerating leading dashes and case drift in how the parser reported it. It returns a fresh slice, or nil for a flag with no known equivalent.

func Hyperlink(url, text string) string

Hyperlink builds an OSC 8 terminal hyperlink for url displayed as text. Both the URL and the display text are sanitized first so a control byte in Jira-supplied text cannot break the span open/close pair or smuggle a second hyperlink.

func HyperlinkPreStyled added in v0.7.4

func HyperlinkPreStyled(url, styledText string) string

HyperlinkPreStyled links display text that already carries ANSI styling (which sanitization would strip). Callers sanitize the raw content BEFORE styling; the URL must already be sanitized too. Honors the user-level hyperlink switch on the default logger and emits through clog's primitive — no logger construction per link.

func JQEnabled added in v0.11.0

func JQEnabled() bool

JQEnabled reports whether a --jq filter is active for this invocation.

func KnownTotal added in v0.7.5

func KnownTotal(total int) *int

KnownTotal wraps an authoritative total for Pagination.Total. Only call it with a value the endpoint actually reported.

func NewRequestID

func NewRequestID() string

NewRequestID returns a 32-character hex request id. crypto/rand is the source; on the practically-impossible read failure it falls back to a timestamp seed, still hex-encoded and zero-padded so the id keeps its fixed 32-char shape for any consumer that parses it.

func OpMutating added in v0.10.14

func OpMutating(op string) bool

OpMutating reports whether an operation writes to Jira (see mutatingOps).

func OperationNames added in v0.13.1

func OperationNames() []string

OperationNames returns every registered operation name, sorted — the inventory the typed-output exhaustiveness guardrail walks so an operation cannot exist without a typed envelope output.

func ResolvedColorMode added in v0.10.12

func ResolvedColorMode() clog.ColorMode

ResolvedColorMode reports the currently published --color decision.

func RouteWarnings

func RouteWarnings(opts RouteOptions) error

RouteWarnings is the single entry point that splits data vs warnings across stdout/stderr. Commands with structured warnings call this instead of WriteEnvelope/WriteCommandPlain directly.

func SanitizeCompletionField

func SanitizeCompletionField(s string) string

SanitizeCompletionField makes a single shell-completion candidate field safe. Shell completion is one tab-separated record per line, so an embedded tab, newline or carriage return in a candidate field would corrupt the grammar; those are collapsed to single spaces. Control bytes are stripped as in SanitizeTerminalText.

func SanitizeTerminalBlock added in v0.9.2

func SanitizeTerminalBlock(s string) string

SanitizeTerminalBlock makes multi-line display text safe for a terminal: ANSI escape sequences are stripped and control bytes dropped exactly as in SanitizeTerminalText, but tab and newline survive so legitimate multi-line Jira content (descriptions, comment bodies) keeps its layout. A CRLF is normalized to a newline and any bare carriage return is dropped, so Jira text cannot use a lone CR to overwrite earlier output on the line.

func SanitizeTerminalText

func SanitizeTerminalText(s string) string

SanitizeTerminalText makes a string safe to write to a terminal at an output boundary. It first strips any ANSI escape sequences, then drops the remaining C0/C1 control bytes (including bare ESC, BEL and NUL) that Jira-controlled text could carry to corrupt the terminal or an OSC 8 hyperlink span. Printable text — including non-ASCII runes — is preserved unchanged.

func SentenceCase added in v0.4.0

func SentenceCase(s string) string

SentenceCase upper-cases the first rune of s, leaving the rest untouched, so a lower-case verb phrase reads as user-facing UI text ("listed issues" -> "Listed issues") while an acronym already at the front survives ("JQL reference" stays). The verb registry stores lower-case forms for structured logs; the spinner, progress bar, and completion line apply this at render so the surfaces the user reads are Sentence-cased, matching git / cargo / docker and clog's own spinner examples.

func SetJQProgram added in v0.11.0

func SetJQProgram(ctx context.Context, code *gojq.Code)

SetJQProgram installs the invocation's compiled --jq filter and the context it runs under.

func SetResolvedColorMode added in v0.10.12

func SetResolvedColorMode(mode clog.ColorMode)

SetResolvedColorMode publishes the --color decision root resolved to the stdout human surfaces. clog.Default carries the mode for stderr; this carries it for everything package cli writes to stdout.

func StyleEnabled added in v0.10.12

func StyleEnabled(tty bool) bool

StyleEnabled reports whether ANSI styling and OSC 8 hyperlinks should be emitted on a human stdout surface whose raw TTY state is tty. It folds the resolved --color mode over TTY detection: ColorAlways forces styling even off a TTY (and past NO_COLOR), ColorNever suppresses it even on one, and ColorAuto styles only a TTY the environment does not suppress (NO_COLOR per its spec, TERM=dumb) — the signals clog's own auto detection kills color for. The decision governs styling and hyperlinks only; TTY-only behaviors that are not color (spinner silence, pagination) keep reading raw terminal detection.

func Suggest

func Suggest(input string, candidates []string) []string

Suggest returns up to suggestionLimit candidates within suggestionMaxDistance edit distance of input, closest first. Candidates shorter than suggestionMinNameLen are skipped. The returned names are the raw candidate strings — the caller adds any "--" prefix.

This deliberately stays off xstrings.Closest: Suggestions is a multi-valued field fed by Cobra's own SuggestionsFor on the unknown-command path, and this helper keeps unknown-flag suggestions on the same contract — plain Levenshtein at Cobra's fixed distance-2 default, up to two candidates. Closest returns a single best match under a length-proportional Damerau threshold, which would change the error payload shape and break that parity.

func ValidateIssueColumns added in v0.3.0

func ValidateIssueColumns(selected []string) error

ValidateIssueColumns reports whether every requested column name is known, so a command can fail fast before calling Jira.

func WriteAliasListPlain added in v0.8.3

func WriteAliasListPlain(w io.Writer, command string, data any, opts ...PlainOption) error

WriteAliasListPlain renders the `alias.list` envelope data — the config's alias name→expansion map — for human consumption. An empty map says so explicitly, so "no aliases" is distinguishable from broken output.

func WriteAttachmentListPlain

func WriteAttachmentListPlain(w io.Writer, command string, data any, opts ...PlainOption) error

WriteAttachmentListPlain renders the `issue.attachment.list` envelope for human consumption. Layout: a header line with the attachment count, followed by one row per attachment with id, filename, human bytes, uploader displayName, and a relative-time created marker.

Mirrors the plain_watcher / plain_link signature so the dispatcher in plain.go can wire it with the same `(w, command, data, opts)` shape.

func WriteBoardListPlain

func WriteBoardListPlain(w io.Writer, command string, data any, opts ...PlainOption) error

WriteBoardListPlain renders the `boards.list` envelope's data block for human consumption. Layout: a header line with the board count, followed by a four-column table — id (right-aligned), name, type, projects (comma-joined with `+N` overflow at 3+ keys ). Empty list surfaces a single advisory line directing the user at the cache primer (the affordance).

Mirrors the plain_link / plain_watcher signature so the dispatcher in plain.go can wire it with the same `(w, command, data, opts)` shape.

func WriteCommandPlain

func WriteCommandPlain(w io.Writer, command string, data any, opts ...PlainOption) error

WriteCommandPlain routes a command's data to the plain renderer that owns its human output. Per-command renderers in the plain_*.go files own the field order, human-size and time formatting for one command group; writeGenericPlain remains the fallback for low-risk internal data that has no dedicated renderer. The command set is closed, so an explicit switch is the whole dispatch — there is deliberately no parallel renderer registry.

func WriteCommentListPlain

func WriteCommentListPlain(w io.Writer, command string, data any, opts ...PlainOption) error

WriteCommentListPlain renders the `data` payload from `comment list` as a TTY-friendly clog table. Designed to be wired into WriteCommandPlain's dispatcher (lead's integration commit handles the wiring).

Expected data shape (from cmd/jira/issue_comment.go's runCommentList):

{
  "comments": [
    {
      "id": "100",
      "body": "...markdown...",
      "author": {"account_id": "...", "display_name": "Alice"},
      "update_author": {...} | null,
      "created": "2026-04-01T10:00:00.000+0000",
      "updated": "2026-04-01T10:00:00.000+0000",
      "visibility": {"type": "role", "value": "Developers"} | null
    }, ...
  ]
}

The renderer prints one line per comment with:

  • id (bold)
  • author display_name
  • created (raw, no relative-time math — Atlassian's RFC 3339 is enough)
  • "(edited)" marker when updated > created
  • visibility tag when set
  • body preview (first ~80 runes, newlines flattened)

Lossy-conversion warnings travel through the envelope's warnings[] array; the renderer doesn't repeat them inline (they're routed to stderr).

func WriteCompact

func WriteCompact(w io.Writer, data any) error

WriteCompact serializes the JSON data payload to w without the envelope wrapper, with null-valued keys dropped recursively so the agent-facing payload stays lean. json and human modes keep the full, stable schema; compact is the deliberately lossy, token-economical view, so in compact an absent key means the value was null. A clog encode or write failure is surfaced to the caller rather than silently dropped.

func WriteEnvelope

func WriteEnvelope(w io.Writer, env Envelope) error

WriteEnvelope serializes a full JSON envelope to w. A clog encode or write failure is surfaced to the caller rather than silently dropped.

func WriteEnvelopeDocument added in v0.10.3

func WriteEnvelopeDocument(w io.Writer, doc any) error

WriteEnvelopeDocument serializes a pre-built envelope document (a value that already carries the ok/meta/data/errors/warnings shape — typically a map) through the same clog flat path cli.WriteEnvelope uses, so a broken-pipe or quota write failure surfaces via errWriter instead of being swallowed. It exists for the raw-warning path, whose warnings carry arbitrary structured fields the typed Warning struct does not model, so the document cannot be funneled through the typed Envelope without dropping data.

func WriteHumanJSON added in v0.1.1

func WriteHumanJSON(w io.Writer, data any, printTheme *clogtheme.Theme) error

WriteHumanJSON serializes JSON through clog's pretty printer for endpoints whose human mode still has a structured JSON contract. printTheme, when non-nil, retints the syntax highlighting to match the user's resolved theme and terminal background, so highlighted JSON stays readable on a light terminal just as entity colors do; nil keeps clog's built-in dark palette.

Color follows the resolved --color mode (resolvedColorMode): never strips the syntax highlighting, always forces it even when stdout is piped. The machine modes stay byte-clean because they encode through WriteEnvelope/WriteCompact, which force ColorNever — only this human-mode JSON path is mode-aware.

func WriteHumanTOML added in v0.10.14

func WriteHumanTOML(w io.Writer, data any, printTheme *clogtheme.Theme) error

WriteHumanTOML renders data as syntax-highlighted TOML through clog's printer — the TOML counterpart of WriteHumanJSON, for endpoints whose human mode shows config-file-shaped content. The same retinting and color-mode rules apply: printTheme (when non-nil) matches the highlight palette to the user's resolved theme, and color follows the resolved --color mode while machine modes stay byte-clean via WriteEnvelope.

func WriteIssueTransitionsPlain

func WriteIssueTransitionsPlain(w io.Writer, command string, data any, opts ...PlainOption) error

WriteIssueTransitionsPlain renders the `issue.transitions` envelope data as a header plus one "id name" line per available transition, or an explicit "no transitions available" line when the workflow offers none.

func WriteIssueViewFailureDiagnostics added in v0.2.0

func WriteIssueViewFailureDiagnostics(w io.Writer, data any, errorsOut []Error) error

WriteIssueViewFailureDiagnostics mirrors multi-key issue-view failures to stderr for human mode. stdout stays reserved for successful rows.

func WriteIssueViewPlain

func WriteIssueViewPlain(w io.Writer, command string, data any, opts ...PlainOption) error

WriteIssueViewPlain renders the `issue.view` envelope data as a human issue card — header, the key summary fields, and the rendered description — and fans out to the multi-issue layout when the payload carries keyed results.

func WriteKeyedResultsFailureDiagnostics added in v0.2.0

func WriteKeyedResultsFailureDiagnostics(w io.Writer, data any, errorsOut []Error) error

WriteKeyedResultsFailureDiagnostics writes the bounded failed-key summary for shared multi-key commands.

func WriteKeyedResultsPlain added in v0.2.0

func WriteKeyedResultsPlain(w io.Writer, command string, data any, opts ...PlainOption) error

WriteKeyedResultsPlain renders the shared multi-key envelope. It keeps stdout focused on the successful per-key payloads; failed keys are mirrored to stderr by WriteKeyedResultsFailureDiagnostics.

func WriteLinkListPlain

func WriteLinkListPlain(w io.Writer, command string, data any, opts ...PlainOption) error

WriteLinkListPlain renders the `issue.link.list` envelope data: a header counting the links on the issue, then one direction-arrowed line per link (verb, other key, truncated summary, status). An empty set says "no links".

func WriteLinkTypesPlain

func WriteLinkTypesPlain(w io.Writer, command string, data any, opts ...PlainOption) error

WriteLinkTypesPlain renders the `issue.link.types` envelope data: a header noting the cache source and fetch time, then one name-sorted line per configured link type with its outward and inward verbs.

func WritePlain

func WritePlain(w io.Writer, data any) error

WritePlain renders arbitrary data through the generic field renderer, the fallback for internal payloads with no command-specific renderer in WriteCommandPlain.

func WriteWatcherListPlain

func WriteWatcherListPlain(w io.Writer, command string, data any, opts ...PlainOption) error

WriteWatcherListPlain renders the `issue.watchers.list` envelope for human consumption. Layout: a header line with the watcher count and a "(you are watching)" affordance when `is_watching: true`, followed by one row per watcher with displayName, truncated accountId, email (or `(hidden)` when the token can't surface it), and an active marker.

Mirrors the `plain_link.go` renderer's shape so the dispatcher in plain.go can wire it with the same `command/data/opts` signature.

Types

type CLIInputError

type CLIInputError struct {
	Kind        CLIInputKind
	Message     string   // diagnosis: what failed
	Flag        string   // offending flag name (no dashes), when flag-scoped
	Suggestions []string // "did you mean" candidates, pre-formatted (e.g. "--output")
}

CLIInputError is the typed error every command-line input failure is wrapped in before it leaves the command layer — a bad flag, a missing required flag, the wrong positional-argument count, or an unknown command. It exists so MapError classifies the failure via errors.As instead of letting the substring classifier guess at an untyped Cobra string. Every CLIInputError is an exit-3 validation failure; the Kind supplies the specific code, and the errtax registry supplies the hint.

The struct carries only plain strings: the pflag/cobra inspection that produces it happens in the command layer, so internal/cli stays free of any Cobra dependency.

func NewCLIInputError

func NewCLIInputError(kind CLIInputKind, message string) *CLIInputError

NewCLIInputError builds a CLIInputError of the given kind. Callers set Flag and Suggestions afterward when the failure is flag-scoped.

func (*CLIInputError) Code added in v0.9.0

func (e *CLIInputError) Code() errtax.Code

Code is the stable snake_case envelope code for an input-failure kind.

func (*CLIInputError) Error

func (e *CLIInputError) Error() string

func (*CLIInputError) FlagName added in v0.9.0

func (e *CLIInputError) FlagName() string

FlagName names the offending flag when the failure is flag-scoped. The method is FlagName (not Flag) because Flag is a field.

type CLIInputKind

type CLIInputKind int

CLIInputKind names which class of command-line input a CLIInputError reports. Each kind maps 1:1 to a stable snake_case envelope code, so an agent branches on Error.Code without parsing the message.

const (
	// InputFlagUnknown is an unrecognized --flag.
	InputFlagUnknown CLIInputKind = iota
	// InputFlagValueMissing is a flag that requires a value but got none.
	InputFlagValueMissing
	// InputFlagValueInvalid is a flag value that failed type or range parsing.
	InputFlagValueInvalid
	// InputFlagSyntaxInvalid is a malformed flag token.
	InputFlagSyntaxInvalid
	// InputRequiredFlagMissing is a required flag that was not set.
	InputRequiredFlagMissing
	// InputArgCountInvalid is the wrong number of positional arguments.
	InputArgCountInvalid
	// InputCommandUnknown is an unrecognized subcommand.
	InputCommandUnknown
	// InputArgValueInvalid is a positional argument value outside the accepted set.
	InputArgValueInvalid
	// InputIssueTypeUnknown is a --type value naming no issue type on the
	// project's create screen — resolved against the fetched list in-code, so a
	// miss is validation, not a Jira 404.
	InputIssueTypeUnknown
	// InputSavedQueryUnknown is a `search saved NAME` value that matches no
	// saved query in the queries directory — a local-file lookup, so its hint
	// points at that directory rather than at --help.
	InputSavedQueryUnknown
	// InputForceRequired is a destructive or state-wiping run refused
	// because it needs explicit --force consent: headless / agent /
	// --no-input contexts for gates with an interactive confirm fallback,
	// every context for clobber guards that never prompt.
	InputForceRequired
	// InputJQExpressionInvalid is a --jq expression gojq could not parse or
	// compile.
	InputJQExpressionInvalid
	// InputJQOutputConflict is --jq combined with an explicit
	// --output=human — the filter runs over JSON output.
	InputJQOutputConflict
)

type CodedError added in v0.10.1

type CodedError struct {
	// contains filtered or unexported fields
}

CodedError attaches an explicit errtax.Code to a plain message. A site that already knows the correct classification — e.g. a multi-key runner that has each failure's typed code in hand — emits the code directly instead of leaving MapError to guess it from the message text. It wraps an optional cause so errors.Is/As still walk the chain.

func NewCodedError added in v0.10.1

func NewCodedError(code errtax.Code, msg string) *CodedError

NewCodedError builds a typed error carrying code and message.

func WrapCoded added in v0.10.1

func WrapCoded(code errtax.Code, msg string, cause error) *CodedError

WrapCoded is NewCodedError that also retains cause for errors.Is/As.

func (*CodedError) Code added in v0.10.1

func (e *CodedError) Code() errtax.Code

Code is the classification the constructing site attached directly, used by MapError instead of guessing one from the message.

func (*CodedError) Error added in v0.10.1

func (e *CodedError) Error() string

func (*CodedError) Unwrap added in v0.10.1

func (e *CodedError) Unwrap() error

type CommandSchema

type CommandSchema struct {
	Command      string         `json:"command"`
	Flags        []FlagSchema   `json:"flags,omitempty"`
	OutputSchema map[string]any `json:"output_schema,omitempty"`
}

CommandSchema is one command's machine-readable description: its dotted command name, its flags, and the JSON Schema for its envelope data payload.

type Detection

type Detection struct {
	Mode  Mode
	IsTTY bool
	Agent bool
	// AgentName is the hosting agent's name as reported by x/agent.Detect
	// (e.g. "claude", "codex"), or empty when the agent cannot be named —
	// which can happen even when Agent is true (a bare `AGENT=1` opt-in).
	AgentName string
	// StdinPiped reports that stdin is NOT an interactive terminal (a pipe,
	// redirect, or /dev/null). It is deliberately negative so the zero value
	// means "interactive" — the safe default for code that builds a Detection
	// without a real stdin. Set from the runtime's stdin in PersistentPreRunE.
	StdinPiped bool
}

Detection is the resolved output environment for one invocation: the mode auto-detection chose plus the signals it derived it from, seeded into the command context by root's PersistentPreRunE.

func Detect

func Detect(stdout *os.File) Detection

Detect resolves the output environment from stdout: a detected agent yields compact, a non-TTY yields json, and an interactive terminal yields plain. Agent detection is delegated to x/agent: the cross-tool `AGENT`/`AI_AGENT` convention first (a falsy value is an explicit opt-out), then per-vendor marker variables (`CLAUDECODE`, `CODEX_SANDBOX`, ...).

func RequireTTY

func RequireTTY(stdout *os.File) (Detection, error)

RequireTTY is Detect with the added precondition that stdout is interactive, for commands (the dashboard) that cannot run otherwise. It returns the Detection alongside the error so a caller can still inspect the environment.

type Envelope

type Envelope struct {
	OK       bool      `json:"ok"`
	Meta     Meta      `json:"meta"`
	Data     any       `json:"data"`
	Errors   []Error   `json:"errors"`
	Warnings []Warning `json:"warnings"`
}

Envelope is the machine-readable JSON output contract. ok is always emitted; a successful command sets ok:true and a failed command sets ok:false with data:null and a populated errors slice.

func ErrorEnvelope

func ErrorEnvelope(command string, err error) Envelope

ErrorEnvelope builds a failure envelope: ok:false, data:null, meta.exit_code set, and a single structured error. Machine envelopes omit meta.profile entirely.

type Error

type Error struct {
	Type      string `json:"type"`
	Code      string `json:"code"`
	Message   string `json:"message"`
	Hint      string `json:"hint"`
	Retryable bool   `json:"retryable"`

	// Flag / Field / Path scope a validation failure to an input;
	// Suggestions carries "did you mean" candidates for it, pre-formatted
	// as the caller would type them (e.g. "--output").
	Flag        string   `json:"flag,omitempty"`
	Field       string   `json:"field,omitempty"`
	Path        string   `json:"path,omitempty"`
	Suggestions []string `json:"suggestions,omitempty"`

	// HTTPStatus / RetryAfterSeconds carry transport metadata.
	HTTPStatus         int `json:"http_status,omitempty"`
	RetryAfterSeconds  int `json:"retry_after_seconds,omitempty"`
	RateLimitRemaining int `json:"rate_limit_remaining,omitempty"`

	// Provider / UpstreamCode / UpstreamStatus preserve a backend's own
	// failure identity. UpstreamCode stays empty when the provider
	// exposes no stable machine code (Jira does not).
	Provider       string `json:"provider,omitempty"`
	UpstreamCode   string `json:"upstream_code,omitempty"`
	UpstreamStatus int    `json:"upstream_status,omitempty"`
	// UpstreamRequestID is Jira's trace id for the failed exchange
	// (Atl-Traceid / X-ARequestId) — the value Atlassian support can
	// correlate, unlike the locally generated meta.request_id.
	UpstreamRequestID string `json:"upstream_request_id,omitempty"`

	// UpstreamMessages / UpstreamFieldErrors preserve Jira's
	// ErrorCollection body verbatim. Wording is not contractual; these
	// are diagnostic context, never a branch target.
	UpstreamMessages    []string          `json:"upstream_messages,omitempty"`
	UpstreamFieldErrors map[string]string `json:"upstream_field_errors,omitempty"`

	// Candidates carries structured disambiguation context — populated by
	// the watcher resolver when /user/search returns 2+ matches.
	Candidates []map[string]any `json:"candidates,omitempty"`
}

Error is one structured failure entry in the envelope errors slice. type, code, message, hint, and retryable are always present; agents branch on code (stable snake_case), never on message. The remaining fields are optional context, omitted when empty.

message and hint are disjoint. message states what failed — a diagnosis, not a wording contract; it may carry summarized upstream text. hint states what to do next — remediation; it may name commands, fields, or retry behavior. Remediation never belongs in message, and a diagnosis never belongs in hint.

func MapError

func MapError(err error) Error

MapError is the central error mapper. Typed source errors describe themselves with an errtax.Code; the registry supplies everything derivable from it, and the capability interfaces layer per-instance context on top. Classification runs in tiers — never substring matching where a typed error exists:

tier 1: prompt identity beats a wrapped cancellation — a canceled
        prompt is prompt_canceled, not canceled.
tier 2: bare or wrapped stdlib context sentinels. errors.Is walks the
        chain, so a Coded error wrapping a cancellation (an APIError
        whose Cause is a canceled body read, a CredentialError whose
        Wrapped is a keyring deadline) still classifies as
        canceled/timeout, preserving the pre-registry adapter order.
tier 3: every other Coded error; the outermost one in the chain wins.

A bare error falls back to a best-effort substring classifier for legacy untyped error strings; that tier is strictly terminal.

type ErrorType

type ErrorType = errtax.Type

ErrorType aliases the shared taxonomy type; the historical cli names remain for the command layer.

type FlagSchema

type FlagSchema struct {
	Name string `json:"name"`
	Type string `json:"type"`
}

FlagSchema names one flag and its type for a CommandSchema.

type JQEvalError added in v0.11.0

type JQEvalError struct {
	Err error
}

JQEvalError is a --jq expression that compiled but failed while running against the emitted document — a type error, an error/1 call, a halt_error. It is validation (exit 3): the document was produced fine, the filter did not fit it.

func (*JQEvalError) Code added in v0.11.0

func (e *JQEvalError) Code() errtax.Code

func (*JQEvalError) Error added in v0.11.0

func (e *JQEvalError) Error() string

func (*JQEvalError) Unwrap added in v0.11.0

func (e *JQEvalError) Unwrap() error

type Meta

type Meta struct {
	Command           string      `json:"command"`
	ExitCode          *int        `json:"exit_code,omitempty"`
	Timestamp         string      `json:"timestamp"`
	RequestID         string      `json:"request_id,omitempty"`
	UpstreamRequestID string      `json:"upstream_request_id,omitempty"`
	Pagination        *Pagination `json:"pagination,omitempty"`
}

Meta is the envelope's command-context block. Machine envelopes omit profile entirely — a command that must report a profile puts it in command-specific data. ExitCode is present only on failure envelopes.

RequestID is a locally generated correlation id; UpstreamRequestID is Jira's own trace id (Atl-Traceid / X-ARequestId) for the exchange — the value to quote to Atlassian support — present whenever the command had a Jira response to read it from.

type Mode

type Mode string

Mode is the concrete rendering the output machinery resolves to, after the --output flag and auto-detection are folded together (ResolveOutputMode).

const (
	// ModePlain is the human-facing renderer: styled tables and status lines.
	ModePlain Mode = "plain"
	// ModeTUI is the full-screen dashboard; only the tui command produces it.
	ModeTUI Mode = "tui"
	// ModeJSON is the full JSON envelope (ok/meta/data/warnings/errors).
	ModeJSON Mode = "json"
	// ModeCompact is the JSON data payload without the envelope wrapper.
	ModeCompact Mode = "compact"
)

func ResolveOutputMode

func ResolveOutputMode(out OutputMode, det Detection) Mode

ResolveOutputMode turns the --output flag value plus auto-detection into the concrete rendering Mode. An explicit value overrides detection; OutputAuto follows the Detection.Mode produced by Detect.

type NotFoundError added in v0.10.1

type NotFoundError struct {
	// Message is the user-facing diagnosis; when empty the wrapped
	// error's text is used verbatim.
	Message string
	Err     error
}

NotFoundError is the typed not_found (exit 2) wrapper for a resource the command proved absent — e.g. a live /user/search that returned zero matches. It wraps the cause so errors.Is still recognizes sentinels like jira.ErrUserNotFound, and carries the stable code so MapError never falls back to the substring classifier.

func NewNotFoundError added in v0.10.1

func NewNotFoundError(message string, err error) *NotFoundError

NewNotFoundError wraps err as a typed not_found failure. An empty message keeps the wrapped error's text.

func (*NotFoundError) Code added in v0.10.1

func (e *NotFoundError) Code() errtax.Code

Code is the stable not_found envelope code (exit 2).

func (*NotFoundError) Error added in v0.10.1

func (e *NotFoundError) Error() string

func (*NotFoundError) Unwrap added in v0.10.1

func (e *NotFoundError) Unwrap() error

type OperationVerb added in v0.4.0

type OperationVerb struct {
	Gerund     string // "caching", "creating", "deleting"
	Past       string // "cached", "created", "deleted"
	Infinitive string // "cache", "create", "delete"
	Noun       string // "boards", "issue", "worklog"
}

OperationVerb carries an operation's verb in the three forms status output needs: a present-progressive gerund while the work runs ("caching"), a past-tense confirmation on success ("cached"), and an infinitive for failures ("failed to cache …"). Noun names the object acted on.

Forms are lower case to match the house log style — clog's own lines and the plain completion messages are lower case. The message is a terse event string; the variable detail (issue key, elapsed time, failure reason) travels as structured fields (key=, time=, reason=), never baked into these phrases.

func VerbFor added in v0.4.0

func VerbFor(op string) OperationVerb

VerbFor returns the verb forms for an operation. An unknown operation falls back to a generic "processing" set so callers always get usable phrases.

func (OperationVerb) Conditionalf added in v0.10.9

func (v OperationVerb) Conditionalf() string

Conditionalf returns the dry-run preview phrase, "would create issue" — the past-tense confirmation would overstate a preview that submitted nothing.

func (OperationVerb) Failuref added in v0.4.0

func (v OperationVerb) Failuref() string

Failuref returns the failure phrase, "failed to create issue".

func (OperationVerb) GerundPlural added in v0.4.0

func (v OperationVerb) GerundPlural() string

GerundPlural returns the in-progress batch phrase, "listing issues".

func (OperationVerb) Gerundf added in v0.4.0

func (v OperationVerb) Gerundf() string

Gerundf returns the in-progress phrase, "creating issue".

func (OperationVerb) NounPlural added in v0.4.0

func (v OperationVerb) NounPlural() string

NounPlural returns the object noun in plural form for batch phrases — naive pluralisation (append s unless already plural) that covers the operations' nouns: issue -> issues, transition -> transitions, web link -> web links.

func (OperationVerb) PastPlural added in v0.4.0

func (v OperationVerb) PastPlural() string

PastPlural returns the success batch phrase, "viewed issues" — the plural counterpart of Pastf for multi-key summaries.

func (OperationVerb) Pastf added in v0.4.0

func (v OperationVerb) Pastf() string

Pastf returns the success phrase, "created issue".

func (OperationVerb) Preview added in v0.10.11

func (v OperationVerb) Preview() OperationVerb

Preview reworks the verb for a dry-run lifecycle: the operation is not performed, only previewed, so every phrase speaks about the preview itself — "previewing issue edit", "previewed issue edit", "failed to preview issue edit" — instead of claiming the mutation. The original noun and infinitive collapse into a compound noun, which reads cleanly for transitive verbs with plain nouns (edit/delete/clone/move/ transition + issue). Particle infinitives ("comment on") and prepositional nouns ("issues to epic") would garble — rework the registry entry before adopting Preview for such an op.

type OutputMode

type OutputMode string

OutputMode is the value of the canonical --output flag. It is the ONLY output-mode selector: the legacy --json/--compact/--plain/--raw booleans are removed and there is no raw REST passthrough mode.

const (
	// OutputAuto defers to terminal/agent detection: TTY -> human,
	// non-TTY -> json, detected agent -> compact.
	OutputAuto OutputMode = "auto"
	// OutputHuman forces the rich clog/table renderer.
	OutputHuman OutputMode = "human"
	// OutputJSON forces the full JSON envelope (ok/meta/data/warnings/errors).
	OutputJSON OutputMode = "json"
	// OutputCompact forces the JSON data payload without the envelope
	// wrapper (no ok/meta/warnings/errors).
	OutputCompact OutputMode = "compact"
)

func ParseOutputMode

func ParseOutputMode(v string) (OutputMode, error)

ParseOutputMode validates a raw --output flag value. An empty string resolves to OutputAuto. Any other unrecognized value — including the removed "raw"/"plain"/"tui" names — is rejected.

type Pagination

type Pagination = envelope.Pagination

Pagination is the JSON envelope's output-shape descriptor for paginated responses. The startAt/nextPageToken fields here describe the SHAPE the CLI emits — they are not cursor-management state in command code. pagination-exempt: output-shape only, not consumer-side cursor management.

This is the ONE pagination shape and it lives in ONE place: meta.pagination on single-target reads, and results[].data.pagination (same shape) inside keyed multi-key results. isLast and nextCursor are the authoritative walk signals; total appears only when the endpoint reports a real total — token-paged endpoints (enhanced search) never do, so a fabricated 0 is never emitted.

type PlainOption

type PlainOption func(*plainConfig)

PlainOption configures one aspect of a plain-text render; the WithPlain* constructors below build them, and WriteCommandPlain applies them in order.

func WithPlainBaseURL

func WithPlainBaseURL(baseURL string) PlainOption

WithPlainBaseURL sets the profile base URL the renderer needs to turn issue keys into browse hyperlinks; an empty value leaves keys as plain text.

func WithPlainColumns added in v0.3.0

func WithPlainColumns(columns []string) PlainOption

WithPlainColumns selects and orders the issue-list columns for human and TSV output. An empty slice keeps the default column set.

func WithPlainDebug added in v0.2.0

func WithPlainDebug(debug bool) PlainOption

WithPlainDebug restores the operational diagnostics (raw JQL, timing) that the preview and count renderers otherwise suppress.

func WithPlainElapsed added in v0.10.14

func WithPlainElapsed(elapsed time.Duration) PlainOption

WithPlainElapsed carries the command's measured blocking time (Spin, the fanout executor) into the completion line. Renderers attach it without a minimum override, so clog's default 1s DurationMinimum keeps fast calls clean and only genuinely slow round-trips grow an elapsed field.

func WithPlainGraphemeWidth added in v0.7.6

func WithPlainGraphemeWidth(grapheme bool) PlainOption

WithPlainGraphemeWidth selects grapheme-cluster width measurement for table alignment, for terminals that draw grapheme clusters (mode 2027) as single glyphs. The default per-rune wcwidth measurement misaligns rows containing ZWJ or VS16 emoji sequences on such terminals.

func WithPlainPager added in v0.10.14

func WithPlainPager(pager bool) PlainOption

WithPlainPager permits paging long document output. Callers pass the resolved policy gate; the renderer adds the only check that belongs to it — whether the rendered document overflows the terminal.

func WithPlainParallel added in v0.2.0

func WithPlainParallel(parallel bool) PlainOption

WithPlainParallel marks the render as running under the fan-out executor, defaulting the reported thread count when the caller set none.

func WithPlainResultKey added in v0.7.5

func WithPlainResultKey(key string) PlainOption

WithPlainResultKey names the multi-key entry the rendered data belongs to, making identification the child renderer's job instead of a duplicated heading above it.

func WithPlainTSV added in v0.3.0

func WithPlainTSV(tsv bool) PlainOption

WithPlainTSV renders the issue list as tab-separated values instead of the styled table — one header line plus one line per issue, no ANSI or box.

func WithPlainTTY

func WithPlainTTY(tty bool) PlainOption

WithPlainTTY sets the resolved styling switch — whether the renderer emits ANSI styles and OSC 8 hyperlinks. Callers pass the --color decision folded over TTY detection (cli.StyleEnabled), not raw terminal state.

func WithPlainTermWidth

func WithPlainTermWidth(width int) PlainOption

WithPlainTermWidth sets the terminal width the issue-list table wraps to.

func WithPlainTheme

func WithPlainTheme(theme *clibtheme.Theme) PlainOption

WithPlainTheme sets the color theme for styled output; a nil theme renders bare.

func WithPlainThreads added in v0.2.0

func WithPlainThreads(threads int) PlainOption

WithPlainThreads sets the fan-out thread count surfaced on the completion line.

type PromptError

type PromptError struct {
	Kind   PromptKind
	Prompt string // the prompt that failed, e.g. "auth login"
	Err    error  // the underlying cause (huh.ErrUserAborted, context.Canceled, …)
}

PromptError is the typed error every interactive-prompt failure is wrapped in before it leaves a command handler. It exists so MapError classifies prompt outcomes via errors.As instead of letting the substring classifier misread "auth login aborted" as an auth failure.

func NewPromptError

func NewPromptError(kind PromptKind, prompt string, err error) *PromptError

NewPromptError builds a PromptError for the given prompt and cause.

func (*PromptError) Code added in v0.9.0

func (e *PromptError) Code() errtax.Code

Code is the stable snake_case envelope code for a prompt kind.

func (*PromptError) Error

func (e *PromptError) Error() string

func (*PromptError) Unwrap

func (e *PromptError) Unwrap() error

type PromptKind

type PromptKind int

PromptKind names why an interactive prompt did not yield a value.

const (
	// PromptAborted means the user dismissed the prompt (Esc / Ctrl-C in
	// the form) before submitting.
	PromptAborted PromptKind = iota
	// PromptCanceled means the prompt was canceled by the command
	// context — a SIGINT or an elapsed --timeout.
	PromptCanceled
	// PromptUnavailable means a prompt was required but could not be
	// shown — no TTY, or --no-input was set.
	PromptUnavailable
)

type ReleaseNotesResult added in v0.8.0

type ReleaseNotesResult struct {
	Releases []changelog.Release `json:"releases"`
	// Markdown is the notes to display in human output; excluded from JSON,
	// where Releases is the structured form.
	Markdown string `json:"-"`
}

ReleaseNotesResult is the envelope payload for `jira release-notes`: jira-cli's own embedded changelog. Releases carries the structured notes (newest first, or a single release when one is requested) and is what JSON consumers read — for a single release or --latest it holds one entry, so `.releases[0]` is that release. Markdown drives the human renderer and is excluded from JSON. It is shared with the releasenotes command package, which builds it, so the JSON envelope and the human renderer agree on one shape.

type RouteMode

type RouteMode int

RouteMode selects how RouteWarnings emits data + warnings.

const (
	// RouteJSON emits the full Envelope (data + warnings) on stdout. Stderr
	// stays untouched.
	RouteJSON RouteMode = iota
	// RoutePlain emits human-readable data on stdout and mirrors each
	// warning to stderr as a clog WRN line. Warning text MUST NOT
	// leak into stdout.
	RoutePlain
	// RouteCompact is JSON without the envelope wrapper; warnings still go
	// in the data via the caller's contract since there is no envelope.
	RouteCompact
)

type RouteOptions

type RouteOptions struct {
	Stdout   io.Writer
	Stderr   io.Writer
	Mode     RouteMode
	Envelope Envelope      // used when Mode == RouteJSON
	Command  string        // used when Mode == RoutePlain
	Data     any           // used when Mode == RoutePlain
	Warnings []Warning     // used when Mode == RoutePlain (and may be empty)
	Plain    []PlainOption // optional plain renderer hints
}

RouteOptions describes a single envelope routing call.

type SchemaRegistry

type SchemaRegistry struct {
	// contains filtered or unexported fields
}

SchemaRegistry maps a command name to its CommandSchema.

func NewSchemaRegistry

func NewSchemaRegistry() *SchemaRegistry

NewSchemaRegistry returns an empty registry ready for Register.

func (*SchemaRegistry) Commands

func (r *SchemaRegistry) Commands() []string

Commands returns the registered command names in sorted order.

func (*SchemaRegistry) Get

func (r *SchemaRegistry) Get(command string) (CommandSchema, bool)

Get returns the schema registered for command and whether one exists.

func (*SchemaRegistry) Register

func (r *SchemaRegistry) Register(schema CommandSchema)

Register stores schema under its Command name, replacing any prior entry.

type Warning

type Warning struct {
	Type     string `json:"type"`
	Message  string `json:"message"`
	Field    string `json:"field,omitempty"`
	Path     string `json:"path,omitempty"`
	NodeType string `json:"node_type,omitempty"`
	MarkType string `json:"mark_type,omitempty"`
	Lossy    bool   `json:"lossy"`
}

Warning is a non-fatal best-effort diagnostic emitted alongside data. lossy is mandatory and serialized even when false; consumers branch on it without nil checks. field/path/node_type/mark_type are optional context fields.

func WarningFrom

func WarningFrom(src WarningSource) Warning

WarningFrom adapts any WarningSource into a cli.Warning ready for the envelope. Used by command code converting pkg/adf warnings.

type WarningSource

type WarningSource interface {
	WarningType() string
	WarningMessage() string
	WarningField() string
	WarningPath() string
	WarningNodeType() string
	WarningMarkType() string
	WarningIsLossy() bool
}

WarningSource is anything that can describe itself as a cli.Warning. The pkg/adf Warning satisfies this; we keep cli ignorant of pkg/adf to avoid the import cycle (pkg/adf -> cli -> pkg/adf via the plain renderer).

Directories

Path Synopsis
Package adfcmd implements the `jira adf` command group: standalone Markdown→ADF conversion and linting, plus the explicitly-lossy ADF→Markdown projection.
Package adfcmd implements the `jira adf` command group: standalone Markdown→ADF conversion and linting, plus the explicitly-lossy ADF→Markdown projection.
Package adfmode resolves the strict vs best-effort ADF mode for a given CLI invocation, applying both the precedence ladder and per-path defaults.
Package adfmode resolves the strict vs best-effort ADF mode for a given CLI invocation, applying both the precedence ladder and per-path defaults.
Package agent hosts the registry commands mounted under docent's `jira agent` group — adf-matrix and fieldtypes, the machine-readable ADF and custom-field support registries.
Package agent hosts the registry commands mounted under docent's `jira agent` group — adf-matrix and fieldtypes, the machine-readable ADF and custom-field support registries.
Package alias hosts the `jira alias` command group for managing the user-defined command aliases stored in the config file.
Package alias hosts the `jira alias` command group for managing the user-defined command aliases stored in the config file.
Package auth hosts the `jira auth` command group for managing Jira credentials and the active profile.
Package auth hosts the `jira auth` command group for managing Jira credentials and the active profile.
Package boards hosts the `jira boards` command tree.
Package boards hosts the `jira boards` command tree.
Package boardscope resolves the `--board NAME` / `--board-id N` flag pair against the local board cache and renders the result into JQL clauses and envelope data.
Package boardscope resolves the `--board NAME` / `--board-id N` flag pair against the local board cache and renders the result into JQL clauses and envelope data.
Package cache hosts the `jira cache` command group: per-resource primers that fetch Jira metadata into the per-profile cache, plus housekeeping (clear, refresh).
Package cache hosts the `jira cache` command group: per-resource primers that fetch Jira metadata into the per-profile cache, plus housekeeping (clear, refresh).
registry
Package registry is the single source of truth for the cacheable Jira metadata resources: their identity, default freshness window, and fetch.
Package registry is the single source of truth for the cacheable Jira metadata resources: their identity, default freshness window, and fetch.
Package cmdutil holds the cross-cutting helper layer shared by every jira-cli command: envelope writers, client/profile accessors, output-mode resolution, mutation gates, the credential-warning sink, and small generic value helpers.
Package cmdutil holds the cross-cutting helper layer shared by every jira-cli command: envelope writers, client/profile accessors, output-mode resolution, mutation gates, the credential-warning sink, and small generic value helpers.
Package completion hosts the `jira completion` command and the dynamic shell-completion emitters.
Package completion hosts the `jira completion` command and the dynamic shell-completion emitters.
Package config implements the `jira config` cobra command tree, which manages the local configuration file, profiles, and theme settings.
Package config implements the `jira config` cobra command tree, which manages the local configuration file, profiles, and theme settings.
Package epic hosts the `jira epic` command group: list, board, add, and remove for epic-to-issue membership.
Package epic hosts the `jira epic` command group: list, board, add, and remove for epic-to-issue membership.
Package issue hosts the `jira issue` command group — the CLI's largest verb — covering the issue lifecycle (create, view, list, edit, clone, move, delete, transition) and its sub-resources: comments, attachments, links, watchers, and rank.
Package issue hosts the `jira issue` command group — the CLI's largest verb — covering the issue lifecycle (create, view, list, edit, clone, move, delete, transition) and its sub-resources: comments, attachments, links, watchers, and rank.
Package jql hosts the `jira jql` command group for building, validating, and referencing JQL queries — the local query-construction helpers that complement the search commands.
Package jql hosts the `jira jql` command group for building, validating, and referencing JQL queries — the local query-construction helpers that complement the search commands.
Package me hosts the `jira me` command, a short alias for the identity portion of `jira auth whoami` that prints the active profile's Jira identity.
Package me hosts the `jira me` command, a short alias for the identity portion of `jira auth whoami` that prints the active profile's Jira identity.
Package releasenotes implements `jira release-notes`, which prints jira-cli's own changelog — embedded in the binary — so a user can see what changed in the tool without opening GitHub or the docs site.
Package releasenotes implements `jira release-notes`, which prints jira-cli's own changelog — embedded in the binary — so a user can see what changed in the tool without opening GitHub or the docs site.
Package root assembles the CLI's top-level cobra command: the persistent flags, help renderer, PersistentPreRunE (config, logging, output-mode resolution), and the subcommand tree, plus the completion-preflight seam and Execute.
Package root assembles the CLI's top-level cobra command: the persistent flags, help renderer, PersistentPreRunE (config, logging, output-mode resolution), and the subcommand tree, plus the completion-preflight seam and Execute.
Package runtime is the dependency boundary between the binary shell in cmd/jira and the command implementations.
Package runtime is the dependency boundary between the binary shell in cmd/jira and the command implementations.
Package schema builds the machine-readable command and output schemas that `jira agent schema` emits and the docs generator reads.
Package schema builds the machine-readable command and output schemas that `jira agent schema` emits and the docs generator reads.
Package search hosts the `jira search` command group for running Jira searches — ad-hoc JQL and the saved named queries from the config's queries path.
Package search hosts the `jira search` command group for running Jira searches — ad-hoc JQL and the saved named queries from the config's queries path.
Package startup parses jira's global flags and first subcommand out of the raw argv before cobra runs.
Package startup parses jira's global flags and first subcommand out of the raw argv before cobra runs.
Package stdin is the ONLY place in the source tree allowed to read os.Stdin.
Package stdin is the ONLY place in the source tree allowed to read os.Stdin.
Package tui wires the `jira tui` command to the section-based dashboard.
Package tui wires the `jira tui` command to the section-based dashboard.
Package update implements the `jira update` cobra command, which self-updates a release-archive binary in place and points Scoop and go-install binaries at the command their channel manages updates with.
Package update implements the `jira update` cobra command, which self-updates a release-archive binary in place and points Scoop and go-install binaries at the command their channel manages updates with.
Package user hosts the `jira user` command group.
Package user hosts the `jira user` command group.
Package version implements the `jira version` cobra command: a bare version string for humans (and tooling that probes `<binary> version`), a labeled metadata block behind --detailed, and the structured envelope in machine modes.
Package version implements the `jira version` cobra command: a bare version string for humans (and tooling that probes `<binary> version`), a labeled metadata block behind --detailed, and the structured envelope in machine modes.
Package worklog hosts the `jira worklog` command group for adding and listing work logged against an issue.
Package worklog hosts the `jira worklog` command group for adding and listing work logged against an issue.

Jump to

Keyboard shortcuts

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