output

package
v0.1.1 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ExitOK         = 0 // success, including "no match"
	ExitUnexpected = 1 // unexpected failure, or no match with --fail-on-no-match
	ExitUsage      = 2 // bad flags, arguments, or missing local tools
	ExitAuth       = 3 // missing, rejected, or expired credentials
	ExitQuota      = 4 // quota, plan, or feature not available
	ExitNetwork    = 5 // network or server error
	ExitSafety     = 6 // a safety bound stopped the command
	ExitPartial    = 7 // batch finished with some failures
	ExitThreshold  = 8 // `usage --check` threshold crossed
)

Exit codes. They are part of the CLI's public contract (see README).

View Source
const CLIDocsURL = "https://github.com/AudDMusic/audd-cli/blob/main/docs/cli.md"

CLIDocsURL is the CLI reference: commands, limits, output, and exit codes (also offline with audd docs cli).

View Source
const SchemaVersion = 1

SchemaVersion is emitted in every JSON document and JSONL line.

Variables

Formats lists the accepted --format values.

Functions

func ExitCode

func ExitCode(err error) int

ExitCode returns the process exit code for err (0 for nil).

func FitTable

func FitTable(rows [][]string, width, gap, min int, shrink ...int)

FitTable cuts the cells of a table (columns separated by gap spaces) so each row fits in width columns. The columns in shrink are cut, in that order, down to at most min columns each; cut cells end with "…". width <= 0 leaves the table as is.

func Plural

func Plural(n int, noun string) string

Plural formats a count with its noun: "1 file", "1,250 requests". The noun takes a plain "s" for any other count.

func Redact

func Redact(s string) string

Redact hides token values in URLs and messages, such as the request URL Go includes in a connection error.

func ResolveNoColor

func ResolveNoColor(flag bool, getenv func(string) string, stdoutTTY bool) bool

ResolveNoColor decides whether color is disabled: --no-color or NO_COLOR disable it, FORCE_COLOR forces it on, otherwise color follows the TTY.

func Thousands

func Thousands(n int) string

Thousands formats n with comma thousands separators: 1250000 → "1,250,000".

func Truncate

func Truncate(s string, w int) string

Truncate cuts s to at most w columns, ending it with "…" when cut.

func Wrap

func Wrap(s string, width int) string

Wrap breaks each line of s at spaces so it fits in width columns. Continuation lines keep the line's leading indent. A word wider than the line stays whole. Escape sequences take no width. width <= 0 returns s.

func WriteKeyValues

func WriteKeyValues(w io.Writer, rows [][2]string, width int)

WriteKeyValues writes "key value" rows with the values aligned, wrapping long values at spaces to fit width (continuation lines are aligned with the value). width <= 0 does not wrap.

func WriteTable

func WriteTable(w io.Writer, rows [][]string, width int, shrink ...int)

WriteTable writes rows as columns separated by two spaces, the first row being the header, fitted to width (see FitTable). The last column is not padded.

Types

type Error

type Error struct {
	Code      string // stable snake_case: "no_token", "token_rejected", "login_required", "quota_exceeded", "limit_required", "confirmation_required", "max_requests_reached", "invalid_argument", "network", "server", "no_match", "missing_tool", ...
	APICode   int    // AudD API error code when applicable, else 0
	Message   string
	Hint      string // the exact next command when possible
	Retryable bool
	Exit      int
	DocsURL   string
}

Error is the only error type commands return for expected failures. Printer.Error renders it for humans or machines and returns Exit.

func AsError

func AsError(err error) *Error

AsError returns err as an *Error, wrapping unknown errors as "unexpected".

func Errf

func Errf(exit int, code, hint, format string, args ...any) *Error

Errf builds an *Error with the given exit code, stable code, and hint.

func (*Error) Error

func (e *Error) Error() string

type Format

type Format string

Format is an output format.

const (
	FormatTable Format = "table"
	FormatJSON  Format = "json"
	FormatJSONL Format = "jsonl"
	FormatCSV   Format = "csv"
)

func ParseFormat

func ParseFormat(s string) (Format, error)

ParseFormat validates a --format / AUDD_FORMAT value.

func ResolveFormat

func ResolveFormat(flag, env string, stdoutTTY, streaming bool) (f Format, explicit bool, err error)

ResolveFormat applies the precedence flag > env (AUDD_FORMAT or a config default) > automatic. Automatic is table on a TTY, json when piped, and jsonl when piped for streaming commands. explicit reports whether the format came from the flag or env rather than automatic detection.

type LineReader

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

LineReader reads lines from an input such as stdin and lets a caller stop waiting (through its context) without losing input: a line that arrives after the caller gave up is handed to the next ReadLine call instead.

func NewLineReader

func NewLineReader(r io.Reader) *LineReader

NewLineReader reads lines from r.

func (*LineReader) ReadLine

func (l *LineReader) ReadLine(ctx context.Context) (string, error)

ReadLine returns the next line, including its newline when present. It returns ctx.Err() when ctx ends first; the line still being read is then kept for the next call.

type Printer

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

Printer writes results to stdout and notes, progress, and errors to stderr, in the format chosen for this invocation. It is safe for concurrent use.

func NewPrinter

func NewPrinter(stdout, stderr io.Writer, opts PrinterOptions) *Printer

NewPrinter returns a Printer. See PrinterOptions for defaults.

func (*Printer) CheckFieldsFor

func (p *Printer) CheckFieldsFor(v any, known ...string) error

CheckFieldsFor checks --fields against the type of the result lines a command will print, before it does any work: a path is valid when v's type declares it, or when known names it. A known entry ending in ".*" accepts anything below it (an optional provider block, say). Without known, a path into a part of v whose shape is open (raw API JSON, maps) is accepted too and checked again against the output. It is a usage error (exit 2) that lists the available fields otherwise.

Once the check passes on fields the type or known fully describe, the output is not checked again: a field a result happens to lack prints as null rather than failing after the work is done.

func (*Printer) Confirm

func (p *Printer) Confirm(question string, yes bool) error

Confirm asks a yes/no question on stderr. yes=true (from --yes) skips the question. Without a TTY on stdin it returns confirmation_required (exit 6). Any answer other than y/yes returns "declined" (exit 6).

func (*Printer) Error

func (p *Printer) Error(err error) int

Error prints err to stderr (human text, or JSON for machine formats) and returns the exit code. A nil error returns ExitOK and prints nothing.

func (*Printer) Event

func (p *Printer) Event(kindName string, v any) error

Event writes one streaming record. jsonl and json print {"schema_version":1,"type":kind, ...v}; csv writes "result" events as rows and drops other kinds; table prints result events as a compact line.

func (*Printer) Explicit

func (p *Printer) Explicit() bool

Explicit reports whether the format came from --format or AUDD_FORMAT rather than automatic detection.

func (*Printer) Fields

func (p *Printer) Fields() []string

Fields returns the --fields selection.

func (*Printer) Format

func (p *Printer) Format() Format

Format returns the active output format.

func (*Printer) Info

func (p *Printer) Info(format string, args ...any)

Info writes a note to stderr. Suppressed by --quiet; never on stdout.

func (*Printer) IsHuman

func (p *Printer) IsHuman() bool

IsHuman reports whether output is for people (table format).

func (*Printer) Options

func (p *Printer) Options() PrinterOptions

Options returns the options the Printer was built with.

func (*Printer) Progress

func (p *Printer) Progress() Progress

Progress returns a progress reporter bound to stderr.

func (*Printer) Quiet

func (p *Printer) Quiet() bool

Quiet reports whether --quiet is set.

func (*Printer) Result

func (p *Printer) Result(v any, human func(w io.Writer)) error

Result prints one result (a struct, map, or slice). In table mode it calls human(w), or renders a generic table when human is nil or --fields is set (--fields trims every format, so the table shows only those fields). In json it prints {"schema_version":1, <fields of v>} (slices as "items"). jsonl prints one "result" line per item. csv flattens v (or []v) into rows; nested keys are dotted ("extra.isrc") and --fields picks and orders columns.

func (*Printer) SeparateNotes

func (p *Printer) SeparateNotes()

SeparateNotes prints an empty line on stderr when notes were printed before, so they stand apart from the result that follows. It does so only for people (table format) and not with --quiet.

func (*Printer) SetDocument

func (p *Printer) SetDocument()

SetDocument undoes SetStreaming for a run that prints one document after all (a dry run): an automatically chosen jsonl format becomes json again.

func (*Printer) SetStreaming

func (p *Printer) SetStreaming()

SetStreaming marks the command as streaming: an automatically chosen json format becomes jsonl. Explicit formats and table mode are unchanged.

func (*Printer) Spinner

func (p *Printer) Spinner(label string) (stop func())

Spinner shows label with a spinner on stderr until stop is called. It draws nothing when stderr is not a TTY or with --quiet.

func (*Printer) Stderr

func (p *Printer) Stderr() io.Writer

Stderr is the stream for notes, progress, and errors.

func (*Printer) StdinLines

func (p *Printer) StdinLines() *LineReader

StdinLines is the shared line reader over the printer's stdin. Every reader of terminal input in the process goes through it, so input typed after one reader stopped waiting reaches the next one.

func (*Printer) Stdout

func (p *Printer) Stdout() io.Writer

Stdout is the result stream (for TUIs and custom renderers).

func (*Printer) StdoutWidth

func (p *Printer) StdoutWidth() int

StdoutWidth is the terminal width of stdout, or 0 when stdout is not a terminal (machine output and pipes are never fitted to a width).

func (*Printer) Styles

func (p *Printer) Styles() Styles

Styles returns lipgloss styles that honor --no-color, NO_COLOR, and FORCE_COLOR.

func (*Printer) Transient

func (p *Printer) Transient() *TransientBlock

Transient returns the open block, or nil.

func (*Printer) TransientBlock

func (p *Printer) TransientBlock() *TransientBlock

TransientBlock opens a block on stderr (see TransientBlock). When one is already open it is returned, so a nested waiting block is part of it.

func (*Printer) Warn

func (p *Printer) Warn(format string, args ...any)

Warn writes a note to stderr even with --quiet.

type PrinterOptions

type PrinterOptions struct {
	// Format is the resolved format (flag > AUDD_FORMAT > auto). Empty means
	// automatic: table on a TTY, json otherwise, jsonl after SetStreaming.
	Format  Format
	Fields  []string // --fields
	Quiet   bool
	NoColor bool // --no-color, NO_COLOR; FORCE_COLOR overrides

	StdoutTTY, StderrTTY, StdinTTY bool

	// StderrWidth is the terminal width of stderr; 0 reads it from the
	// terminal (80 when that fails).
	StderrWidth int
	// StdoutWidth is the terminal width of stdout; 0 reads it from the
	// terminal (80 when that fails).
	StdoutWidth int

	// Stdin is read by Confirm. Defaults to os.Stdin.
	Stdin io.Reader
}

PrinterOptions configures a Printer.

type Progress

type Progress interface {
	Start(total int, label string)
	Inc(n int)
	SetLabel(s string)
	Done()
}

Progress reports progress on stderr. It is a no-op when stderr is not a TTY.

type Styles

type Styles struct {
	Title    lipgloss.Style // headings, song titles
	Bold     lipgloss.Style
	Dim      lipgloss.Style // secondary text, labels
	Accent   lipgloss.Style // highlights, links
	OK       lipgloss.Style
	Warn     lipgloss.Style
	Err      lipgloss.Style
	Key      lipgloss.Style // key/label column
	Renderer *lipgloss.Renderer
}

Styles are the shared text styles for human output.

type TransientBlock

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

TransientBlock is text on stderr that can be erased later, such as the instructions shown while a sign-in waits. While a block is open, every line the Printer writes to stderr (notes, warnings, the spinner) is part of it. Clear erases it by moving the cursor up over the screen rows it took (counted with the terminal width, so wrapped lines count) and clearing to the end of the screen; it does not rely on saving the cursor position, which breaks once the terminal scrolls.

When stderr is not a terminal or the output is not for people, the block only writes through and Clear does nothing.

func (*TransientBlock) Clear

func (b *TransientBlock) Clear() bool

Clear erases the block and closes it. It reports whether it erased anything: false for a pass-through block or one already closed.

func (*TransientBlock) CountInput

func (b *TransientBlock) CountInput(line string)

CountInput counts a line the terminal echoed while the block was open (typed or pasted input; line without its newline), so Clear erases it too.

func (*TransientBlock) Keep

func (b *TransientBlock) Keep()

Keep closes the block and leaves it on screen.

func (*TransientBlock) Rows

func (b *TransientBlock) Rows() int

Rows is the number of rows the block takes above the cursor's row.

func (*TransientBlock) Write

func (b *TransientBlock) Write(data []byte) (int, error)

Write writes to stderr as part of the block.

Jump to

Keyboard shortcuts

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