output

package
v0.4.8 Latest Latest
Warning

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

Go to latest
Published: Mar 6, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ExitWithError

func ExitWithError(err error)

ExitWithError prints an error and exits with the appropriate code. This provides backward compatibility with the existing cli.ExitWithError function.

func PrintWarning

func PrintWarning(w io.Writer, message string)

PrintWarning writes a warning message to the given writer. Provides backward compatibility with cli.PrintWarning.

Types

type Code

type Code string

Code represents a structured error or warning code. These are stable string identifiers for machine-readable error handling.

const (
	// General errors (exit code 1)
	CodeGeneralError    Code = "GENERAL_ERROR"
	CodeInvalidInput    Code = "INVALID_INPUT"
	CodeOperationFailed Code = "OPERATION_FAILED"
	CodeUsageError      Code = "USAGE_ERROR"

	// Config errors (exit code 2)
	CodeConfigNotFound   Code = "CONFIG_NOT_FOUND"
	CodeConfigInvalid    Code = "CONFIG_INVALID"
	CodeConfigParseError Code = "CONFIG_PARSE_ERROR"
	CodeConfigSaveError  Code = "CONFIG_SAVE_ERROR"

	// Vault errors (exit code 3)
	CodeVaultNotFound    Code = "VAULT_NOT_FOUND"
	CodeVaultLoadError   Code = "VAULT_LOAD_ERROR"
	CodeVaultSaveError   Code = "VAULT_SAVE_ERROR"
	CodeVaultEmpty       Code = "VAULT_EMPTY"
	CodeVaultLocked      Code = "VAULT_LOCKED"
	CodeVaultReadOnly    Code = "VAULT_READ_ONLY"
	CodeSecretNotFound   Code = "SECRET_NOT_FOUND"
	CodeSecretNoValues   Code = "SECRET_NO_VALUES"
	CodeIdentityNotFound Code = "IDENTITY_NOT_FOUND"

	// GPG errors (exit code 4)
	CodeGPGError         Code = "GPG_ERROR"
	CodeGPGKeyNotFound   Code = "GPG_KEY_NOT_FOUND"
	CodeGPGDecryptFailed Code = "GPG_DECRYPT_FAILED"
	CodeGPGEncryptFailed Code = "GPG_ENCRYPT_FAILED"
	CodeGPGSignFailed    Code = "GPG_SIGN_FAILED"
	CodeGPGVerifyFailed  Code = "GPG_VERIFY_FAILED"

	// Auth errors (exit code 5)
	CodeAuthError Code = "AUTH_ERROR"

	// Validation errors (exit code 6)
	CodeValidationError  Code = "VALIDATION_ERROR"
	CodeSignatureInvalid Code = "SIGNATURE_INVALID"
	CodeHashMismatch     Code = "HASH_MISMATCH"

	// Fingerprint errors (exit code 7)
	CodeFingerprintRequired Code = "FINGERPRINT_REQUIRED"

	// Access denied errors (exit code 8)
	CodeAccessDenied       Code = "SECRET_ACCESS_DENIED"
	CodeIdentityNotInVault Code = "IDENTITY_NOT_IN_VAULT"

	// Algorithm errors (exit code 9)
	CodeAlgorithmNotAllowed Code = "ALGORITHM_NOT_ALLOWED"
	CodeAlgorithmWeak       Code = "ALGORITHM_WEAK"
)

Error codes - grouped by category

const (
	CodeWarnGeneric          Code = "WARN_GENERIC"
	CodeWarnFallbackValue    Code = "WARN_FALLBACK_VALUE"
	CodeWarnIgnoringConfig   Code = "WARN_IGNORING_CONFIG"
	CodeWarnVaultNotInConfig Code = "WARN_VAULT_NOT_IN_CONFIG"
	CodeWarnFlagIgnored      Code = "WARN_FLAG_IGNORED"
	CodeWarnFlagConflict     Code = "WARN_FLAG_CONFLICT"
	CodeWarnSelfRevoke       Code = "WARN_SELF_REVOKE"
	CodeWarnIdentityNotFound Code = "WARN_IDENTITY_NOT_FOUND"
	CodeWarnDecodeFailure    Code = "WARN_DECODE_FAILURE"
	CodeWarnDecryptFailure   Code = "WARN_DECRYPT_FAILURE"
	CodeWarnDeprecated       Code = "WARN_DEPRECATED"
	CodeWarnVaultLoadError   Code = "WARN_VAULT_LOAD_ERROR"
)

Warning codes

func CodeFromExitCode

func CodeFromExitCode(exitCode ExitCode) Code

CodeFromExitCode returns a generic Code for a numeric exit code. Used for backward compatibility when converting legacy errors.

func (Code) GetExitCode

func (c Code) GetExitCode() ExitCode

GetExitCode returns the numeric exit code for a structured code.

func (Code) IsWarning

func (c Code) IsWarning() bool

IsWarning returns true if the code is a warning code.

func (Code) String

func (c Code) String() string

String returns the string representation of the code.

type Envelope

type Envelope struct {
	Data     interface{} `json:"data,omitempty"`
	Warnings []*Warning  `json:"warnings,omitempty"`
	Error    *Error      `json:"error,omitempty"`
}

Envelope wraps command output in a standardized JSON structure. This provides a consistent format for all JSON output with data, warnings, and errors.

func NewEnvelope

func NewEnvelope(data interface{}) *Envelope

NewEnvelope creates a new envelope with the given data.

func NewErrorEnvelope

func NewErrorEnvelope(err *Error) *Envelope

NewErrorEnvelope creates an envelope containing only an error.

func (*Envelope) AddWarning

func (e *Envelope) AddWarning(w *Warning)

AddWarning appends a warning to the envelope.

func (*Envelope) AddWarnings

func (e *Envelope) AddWarnings(warnings []*Warning)

AddWarnings appends multiple warnings to the envelope.

func (*Envelope) HasError

func (e *Envelope) HasError() bool

HasError returns true if there is an error.

func (*Envelope) HasWarnings

func (e *Envelope) HasWarnings() bool

HasWarnings returns true if there are any warnings.

func (*Envelope) IsSuccess

func (e *Envelope) IsSuccess() bool

IsSuccess returns true if there is no error.

func (*Envelope) Marshal

func (e *Envelope) Marshal() ([]byte, error)

Marshal returns the envelope as JSON bytes.

func (*Envelope) MarshalIndent

func (e *Envelope) MarshalIndent() ([]byte, error)

MarshalIndent returns the envelope as indented JSON bytes.

func (*Envelope) SetData

func (e *Envelope) SetData(data interface{})

SetData sets the data payload of the envelope.

func (*Envelope) SetError

func (e *Envelope) SetError(err *Error)

SetError sets the error on the envelope.

func (*Envelope) WriteTo

func (e *Envelope) WriteTo(w io.Writer, indent bool) error

WriteTo serializes the envelope to a writer as JSON.

type Error

type Error struct {
	Code    Code                   `json:"code"`
	Message string                 `json:"message"`
	Details map[string]interface{} `json:"details,omitempty"`
	Cause   error                  `json:"-"` // Not serialized, for error chaining
}

Error represents a structured error with code, message, and optional metadata. It implements the standard error interface and supports error chaining.

func FromLegacyError

func FromLegacyError(message string, exitCode ExitCode) *Error

FromLegacyError creates an output.Error from a message and numeric exit code. Used for backward compatibility when converting legacy errors.

func NewError

func NewError(code Code, message string) *Error

NewError creates a new structured error with the given code and message.

func NewErrorf

func NewErrorf(code Code, format string, args ...interface{}) *Error

NewErrorf creates a new structured error with a formatted message.

func NewLegacyError deprecated

func NewLegacyError(message string, exitCode ExitCode) *Error

NewLegacyError creates an error matching the legacy cli.Error signature. This is a convenience function for gradual migration.

Deprecated: Use NewError with a structured Code instead.

func (*Error) Error

func (e *Error) Error() string

Error implements the error interface.

func (*Error) ExitCode

func (e *Error) ExitCode() ExitCode

ExitCode returns the numeric exit code for CLI use.

func (*Error) Is

func (e *Error) Is(target error) bool

Is checks if this error matches another error by code. This supports errors.Is() for code-based matching.

func (*Error) MarshalJSON

func (e *Error) MarshalJSON() ([]byte, error)

MarshalJSON provides custom JSON marshaling that includes the exit code.

func (*Error) ToLegacy

func (e *Error) ToLegacy() (string, ExitCode)

ToLegacy returns the message and exit code for backward compatibility. This allows the new Error type to be used with code expecting the old format.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the underlying cause for errors.Is/As support.

func (*Error) WithCause

func (e *Error) WithCause(cause error) *Error

WithCause wraps an underlying error for error chaining.

func (*Error) WithDetail

func (e *Error) WithDetail(key string, value interface{}) *Error

WithDetail adds a metadata field to the error and returns the error for chaining.

func (*Error) WithDetails

func (e *Error) WithDetails(details map[string]interface{}) *Error

WithDetails adds multiple metadata fields to the error.

type ExitCode

type ExitCode int

ExitCode represents numeric exit codes for CLI backward compatibility. These match the existing exit codes in internal/cli/errors.go.

const (
	ExitSuccess             ExitCode = 0
	ExitGeneralError        ExitCode = 1
	ExitConfigError         ExitCode = 2
	ExitVaultError          ExitCode = 3
	ExitGPGError            ExitCode = 4
	ExitAuthError           ExitCode = 5
	ExitValidationError     ExitCode = 6
	ExitFingerprintRequired ExitCode = 7
	ExitAccessDenied        ExitCode = 8
	ExitAlgorithmNotAllowed ExitCode = 9
)

func PrintError

func PrintError(w io.Writer, err error) ExitCode

PrintError writes an error message to the given writer and returns the exit code. This provides backward compatibility with the existing cli.PrintError function.

func (ExitCode) Int

func (e ExitCode) Int() int

Int returns the integer value of the exit code.

type Handler

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

Handler manages output emission based on mode and format. It supports silent mode (suppress warnings) and JSON mode (envelope output).

func NewHandler

func NewHandler(stdout, stderr io.Writer, opts ...HandlerOption) *Handler

NewHandler creates a new output handler with the given writers and options.

func (*Handler) ClearWarnings

func (h *Handler) ClearWarnings()

ClearWarnings resets the warning collection.

func (*Handler) Clone

func (h *Handler) Clone() *Handler

Clone creates a new handler with the same settings but fresh warning collection. Useful for per-command handlers.

func (*Handler) Error

func (h *Handler) Error(e *Error)

Error emits an error to stderr (text mode only). In JSON mode, errors are included in the envelope via WriteJSON.

func (*Handler) Errorf

func (h *Handler) Errorf(code Code, format string, args ...interface{})

Errorf creates and emits an error with a formatted message.

func (*Handler) GetWarnings

func (h *Handler) GetWarnings() []*Warning

GetWarnings returns collected warnings.

func (*Handler) IsJSON

func (h *Handler) IsJSON() bool

IsJSON returns whether JSON mode is enabled.

func (*Handler) IsSilent

func (h *Handler) IsSilent() bool

IsSilent returns whether silent mode is enabled.

func (*Handler) IsTerminal added in v0.4.6

func (h *Handler) IsTerminal() bool

IsTerminal returns true if stdin is connected to an interactive terminal.

func (*Handler) Stderr

func (h *Handler) Stderr() io.Writer

Stderr returns the stderr writer.

func (*Handler) Stdin added in v0.4.4

func (h *Handler) Stdin() io.Reader

Stdin returns the stdin reader.

func (*Handler) Stdout

func (h *Handler) Stdout() io.Writer

Stdout returns the stdout writer.

func (*Handler) Success

func (h *Handler) Success(message string)

Success emits a success message to stdout (text mode only).

func (*Handler) Successf

func (h *Handler) Successf(format string, args ...interface{})

Successf emits a formatted success message to stdout.

func (*Handler) Warn

func (h *Handler) Warn(w *Warning)

Warn emits a warning. In text mode, it prints immediately (unless silent). In JSON mode, warnings are collected for the envelope.

func (*Handler) WarnWithDetails

func (h *Handler) WarnWithDetails(code Code, message string, details map[string]interface{})

WarnWithDetails creates and emits a warning with metadata.

func (*Handler) Warnf

func (h *Handler) Warnf(code Code, format string, args ...interface{})

Warnf creates and emits a warning with a formatted message.

func (*Handler) WarningCount

func (h *Handler) WarningCount() int

WarningCount returns the number of collected warnings.

func (*Handler) WithJSONMode

func (h *Handler) WithJSONMode(enabled bool) *Handler

WithJSONMode returns a new handler with JSON mode set. The new handler shares stdout/stderr but has fresh warning collection.

func (*Handler) WriteData

func (h *Handler) WriteData(format string, args ...interface{})

WriteData writes data output to stdout (text mode only). Does not add a newline; caller is responsible for formatting.

func (*Handler) WriteJSON

func (h *Handler) WriteJSON(data interface{}, err *Error) error

WriteJSON writes the JSON envelope with collected warnings and optional error. This is the primary output method for JSON mode.

func (*Handler) WriteJSONError

func (h *Handler) WriteJSONError(err *Error) error

WriteJSONError writes a JSON envelope containing only an error.

func (*Handler) WriteLine

func (h *Handler) WriteLine(message string)

WriteLine writes a line of output to stdout (text mode only). Ensures message ends with newline.

type HandlerOption

type HandlerOption func(*Handler)

HandlerOption configures a Handler.

func WithJSON

func WithJSON(json bool) HandlerOption

WithJSON sets JSON output mode.

func WithSilent

func WithSilent(silent bool) HandlerOption

WithSilent sets silent mode (suppress warning output to stderr).

func WithStdin added in v0.4.4

func WithStdin(stdin io.Reader) HandlerOption

WithStdin sets the stdin reader.

type Warning

type Warning struct {
	Code      Code                   `json:"code"`
	Message   string                 `json:"message"`
	Details   map[string]interface{} `json:"details,omitempty"`
	Timestamp time.Time              `json:"timestamp"`
}

Warning represents a structured warning with code, message, and optional metadata.

func NewWarning

func NewWarning(code Code, message string) *Warning

NewWarning creates a new structured warning with the given code and message.

func NewWarningf

func NewWarningf(code Code, format string, args ...interface{}) *Warning

NewWarningf creates a new warning with a formatted message.

func (*Warning) String

func (w *Warning) String() string

String returns a human-readable representation of the warning.

func (*Warning) WithDetail

func (w *Warning) WithDetail(key string, value interface{}) *Warning

WithDetail adds a metadata field to the warning and returns it for chaining.

func (*Warning) WithDetails

func (w *Warning) WithDetails(details map[string]interface{}) *Warning

WithDetails adds multiple metadata fields to the warning.

Jump to

Keyboard shortcuts

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