output

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Mar 1, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

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

Index

Constants

View Source
const (
	ExitOK        = 0 // Success
	ExitUsage     = 1 // Invalid arguments or flags
	ExitNotFound  = 2 // Resource not found
	ExitAuth      = 3 // Not authenticated
	ExitForbidden = 4 // Access denied (scope issue)
	ExitRateLimit = 5 // Rate limited (429)
	ExitNetwork   = 6 // Connection/DNS/timeout error
	ExitAPI       = 7 // Server returned error
	ExitAmbiguous = 8 // Multiple matches for name
)

Exit codes matching the Bash implementation.

View Source
const (
	CodeUsage     = "usage"
	CodeNotFound  = "not_found"
	CodeAuth      = "auth_required"
	CodeForbidden = "forbidden"
	CodeRateLimit = "rate_limit"
	CodeNetwork   = "network"
	CodeAPI       = "api_error"
	CodeAmbiguous = "ambiguous"
)

Error codes for JSON envelope.

Variables

This section is empty.

Functions

func ExitCodeFor

func ExitCodeFor(code string) int

ExitCodeFor returns the exit code for a given error code.

func NormalizeData

func NormalizeData(data any) any

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

func TruncationNotice

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

TruncationNotice returns a notice string if results may be truncated. Returns empty string if no truncation warning is needed. Parameters:

  • count: number of results returned
  • defaultLimit: the default limit for this resource type (e.g., 100)
  • all: whether --all flag was used
  • explicitLimit: limit set via --limit flag (0 if not set)

func TruncationNoticeWithTotal

func TruncationNoticeWithTotal(count, totalCount int) string

TruncationNoticeWithTotal returns a truncation notice when results are truncated. Uses totalCount from API's X-Total-Count header to show accurate counts. Returns empty string if no truncation or totalCount is 0 (unavailable).

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 struct {
	Code       string
	Message    string
	Hint       string
	HTTPStatus int
	Retryable  bool
	Cause      error
}

Error is a structured error with code, message, and optional hint.

func AsError

func AsError(err error) *Error

AsError attempts to convert an error to an *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 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

func (*Error) Error

func (e *Error) Error() string

func (*Error) ExitCode

func (e *Error) ExitCode() int

ExitCode returns the appropriate exit code for this error.

func (*Error) Unwrap

func (e *Error) Unwrap() 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
	Verbose bool
}

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)
}

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 WithEntity

func WithEntity(name string) ResponseOption

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

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.

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.

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.

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