output

package
v0.8.0-rc.2 Latest Latest
Warning

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

Go to latest
Published: Aug 3, 2026 License: MIT Imports: 22 Imported by: 0

Documentation

Overview

Package output provides JSON/Markdown output formatting and error handling.

Index

Constants

View Source
const (
	ExitOK        = clioutput.ExitOK
	ExitUsage     = clioutput.ExitUsage
	ExitNotFound  = clioutput.ExitNotFound
	ExitAuth      = clioutput.ExitAuth
	ExitForbidden = clioutput.ExitForbidden
	ExitRateLimit = clioutput.ExitRateLimit
	ExitNetwork   = clioutput.ExitNetwork
	ExitAPI       = clioutput.ExitAPI
	ExitAmbiguous = clioutput.ExitAmbiguous
)

Exit codes matching the Bash implementation (re-exported from shared module).

View Source
const (
	CodeUsage     = clioutput.CodeUsage
	CodeNotFound  = clioutput.CodeNotFound
	CodeAuth      = clioutput.CodeAuth
	CodeForbidden = clioutput.CodeForbidden
	CodeRateLimit = clioutput.CodeRateLimit
	CodeNetwork   = clioutput.CodeNetwork
	CodeAPI       = clioutput.CodeAPI
	CodeAmbiguous = clioutput.CodeAmbiguous
)

Error codes for JSON envelope (re-exported from shared module).

Variables

This section is empty.

Functions

func ExitCodeFor

func ExitCodeFor(code string) int

ExitCodeFor returns the exit code for a given error code.

func IsJQError added in v0.7.0

func IsJQError(err error) bool

IsJQError returns true if the error is a jq-related error (validation failure, unsupported command, or flag conflict).

func NormalizeData

func NormalizeData(data any) any

NormalizeData converts json.RawMessage and other types to standard Go types.

func PluralNoun added in v0.7.0

func PluralNoun(s string) string

PluralNoun returns a simple English plural for tool-related nouns. Handles the sibilant cases we encounter (inbox → inboxes) and falls back to appending "s".

func RequestID added in v0.8.0

func RequestID(err error) string

RequestID returns the SDK request ID carried by err, if present.

func TruncationNotice

func TruncationNotice(count, defaultLimit int, all bool, explicitLimit int) string

TruncationNotice returns a notice string if results may be truncated.

func TruncationNoticeWithTotal

func TruncationNoticeWithTotal(count, totalCount int) string

TruncationNoticeWithTotal returns a truncation notice using totalCount from the API.

Types

type Breadcrumb struct {
	Action      string `json:"action"`
	Cmd         string `json:"cmd"`
	Description string `json:"description"`
}

Breadcrumb is a suggested follow-up action.

type Error

type Error = clioutput.Error

Error is a structured error with code, message, and optional hint. Type alias — zero-cost, full compatibility with errors.As.

func AsError

func AsError(err error) *Error

func ErrAPI

func ErrAPI(status int, msg string) *Error

func ErrAmbiguous

func ErrAmbiguous(resource string, matches []string) *Error

func ErrAuth

func ErrAuth(msg string) *Error

func ErrForbidden

func ErrForbidden(msg string) *Error

func ErrForbiddenScope

func ErrForbiddenScope() *Error

func ErrJQConflict added in v0.7.0

func ErrJQConflict(flag string) *Error

ErrJQConflict returns a usage error for flags that conflict with --jq.

func ErrJQNotSupported added in v0.7.0

func ErrJQNotSupported(command string) *Error

ErrJQNotSupported returns a usage error for commands that don't support --jq.

func ErrJQRuntime added in v0.7.0

func ErrJQRuntime(cause error) *Error

ErrJQRuntime returns a usage error for jq runtime failures (e.g. type errors, non-serializable results).

func ErrJQValidation added in v0.7.0

func ErrJQValidation(cause error) *Error

ErrJQValidation returns a usage error for invalid --jq expressions.

func ErrNetwork

func ErrNetwork(cause error) *Error

func ErrNotFound

func ErrNotFound(resource, identifier string) *Error

func ErrNotFoundHint

func ErrNotFoundHint(resource, identifier, hint string) *Error

func ErrRateLimit

func ErrRateLimit(retryAfter int) *Error

func ErrUsage

func ErrUsage(msg string) *Error

func ErrUsageHint

func ErrUsageHint(msg, hint string) *Error

type ErrorResponse

type ErrorResponse struct {
	OK    bool           `json:"ok"`
	Error string         `json:"error"`
	Code  string         `json:"code"`
	Hint  string         `json:"hint,omitempty"`
	Meta  map[string]any `json:"meta,omitempty"`
}

ErrorResponse is the error envelope for JSON output.

type ErrorResponseOption

type ErrorResponseOption func(*ErrorResponse)

ErrorResponseOption modifies an ErrorResponse.

func WithErrorStats

func WithErrorStats(metrics *observability.SessionMetrics) ErrorResponseOption

WithErrorStats adds session metrics to the error response metadata.

type Format

type Format int

Format specifies the output format.

const (
	FormatAuto Format = iota // Auto-detect: TTY → Styled, non-TTY → JSON
	FormatJSON
	FormatMarkdown // Literal Markdown syntax (portable, pipeable)
	FormatStyled   // ANSI styled output (forced, even when piped)
	FormatQuiet
	FormatIDs
	FormatCount
)

type MarkdownRenderer

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

MarkdownRenderer outputs literal Markdown syntax (portable, pipeable).

func NewMarkdownRenderer

func NewMarkdownRenderer(w io.Writer) *MarkdownRenderer

NewMarkdownRenderer creates a renderer for literal Markdown output.

func (*MarkdownRenderer) RenderError

func (r *MarkdownRenderer) RenderError(w io.Writer, resp *ErrorResponse) error

RenderError renders an error response as literal Markdown.

func (*MarkdownRenderer) RenderResponse

func (r *MarkdownRenderer) RenderResponse(w io.Writer, resp *Response) error

RenderResponse renders a success response as literal Markdown.

type Options

type Options struct {
	Format    Format
	Writer    io.Writer
	ErrWriter io.Writer // Diagnostic output (notices in quiet mode); defaults to os.Stderr.
	Verbose   bool
	JQFilter  string // jq expression to apply to JSON output (built-in via gojq)
}

Options controls output behavior.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns options for standard output.

type Renderer

type Renderer struct {

	// Text styles
	Summary lipgloss.Style
	Muted   lipgloss.Style
	Data    lipgloss.Style
	Error   lipgloss.Style
	Hint    lipgloss.Style
	Warning lipgloss.Style
	Success lipgloss.Style
	Subtle  lipgloss.Style // for footer elements (most understated)

	// Table styles
	Header    lipgloss.Style
	Cell      lipgloss.Style
	CellMuted lipgloss.Style
	// contains filtered or unexported fields
}

Renderer handles styled terminal output.

func NewRenderer

func NewRenderer(w io.Writer, forceStyled bool) *Renderer

NewRenderer creates a renderer with styles from the resolved theme. Styling is enabled when writing to a TTY, or when forceStyled is true. Theme resolution follows: NO_COLOR env → BASECAMP_THEME env → user theme (~/.config/basecamp/theme/colors.toml, which may be symlinked to system themes) → default.

func NewRendererWithTheme

func NewRendererWithTheme(w io.Writer, forceStyled bool, theme tui.Theme) *Renderer

NewRendererWithTheme creates a renderer with a specific theme (for testing).

func (*Renderer) RenderError

func (r *Renderer) RenderError(w io.Writer, resp *ErrorResponse) error

RenderError renders an error response to the writer with a styled error box.

func (*Renderer) RenderResponse

func (r *Renderer) RenderResponse(w io.Writer, resp *Response) error

RenderResponse renders a success response to the writer.

type Response

type Response struct {
	OK          bool           `json:"ok"`
	Data        any            `json:"data,omitempty"`
	Summary     string         `json:"summary,omitempty"`
	Notice      string         `json:"notice,omitempty"` // Informational message (e.g., truncation warning)
	Breadcrumbs []Breadcrumb   `json:"breadcrumbs,omitempty"`
	Context     map[string]any `json:"context,omitempty"`
	Meta        map[string]any `json:"meta,omitempty"`
	Entity      string         `json:"-"` // Schema hint for presenter (not serialized)
	DisplayData any            `json:"-"` // Alternate data for styled/markdown rendering (not serialized)
	// contains filtered or unexported fields
}

Response is the success envelope for JSON output.

type ResponseOption

type ResponseOption func(*Response)

ResponseOption modifies a Response.

func WithBreadcrumbs

func WithBreadcrumbs(b ...Breadcrumb) ResponseOption

WithBreadcrumbs adds breadcrumbs to the response.

func WithContext

func WithContext(key string, value any) ResponseOption

WithContext adds context to the response.

func WithDiagnostic added in v0.7.0

func WithDiagnostic(s string) ResponseOption

WithDiagnostic sets a notice that is also emitted to stderr in quiet mode. Use this for degraded-operation warnings (e.g. unresolved mentions) that automation consumers need to detect. Truncation and other informational notices should use WithNotice instead.

func WithDisplayData added in v0.2.2

func WithDisplayData(data any) ResponseOption

WithDisplayData provides alternate data for styled/markdown rendering. When set, the presenter uses this instead of Data, keeping Data untouched for JSON serialization. Use this when the response wrapper struct should be preserved for machine consumption but a different shape (e.g. an unwrapped slice) is better for human-oriented output.

func WithEntity

func WithEntity(name string) ResponseOption

WithEntity hints which schema to use for entity-aware presentation.

func WithGroupBy added in v0.2.2

func WithGroupBy(field string) ResponseOption

WithGroupBy overrides the schema's default group_by field for task list rendering. For example, WithGroupBy("due_on") groups todos by due date instead of project.

func WithMeta

func WithMeta(key string, value any) ResponseOption

WithMeta adds metadata to the response.

func WithNotice

func WithNotice(s string) ResponseOption

WithNotice adds an informational notice to the response. Use this for non-error messages like truncation warnings. Like WithSummary, the value is stored verbatim; terminal sinks sanitize.

func WithStats

func WithStats(metrics *observability.SessionMetrics) ResponseOption

WithStats adds session metrics to the response metadata.

func WithSummary

func WithSummary(s string) ResponseOption

WithSummary adds a summary to the response. The value is stored verbatim so machine (JSON) output preserves the original content; terminal sinks (styled/markdown renderers, quiet-mode stderr diagnostics) sanitize at render time.

func WithoutBreadcrumbs added in v0.2.0

func WithoutBreadcrumbs() ResponseOption

WithoutBreadcrumbs removes all breadcrumbs from the response.

type Writer

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

Writer handles all output formatting.

func New

func New(opts Options) *Writer

New creates a new output writer. If JQFilter is set, the jq expression is parsed and compiled eagerly so errors surface immediately rather than on the first write.

func (*Writer) EffectiveFormat

func (w *Writer) EffectiveFormat() Format

EffectiveFormat resolves FormatAuto based on TTY detection.

func (*Writer) Err

func (w *Writer) Err(err error, opts ...ErrorResponseOption) error

Err outputs an error response.

func (*Writer) OK

func (w *Writer) OK(data any, opts ...ResponseOption) error

OK outputs a success response.

Jump to

Keyboard shortcuts

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