output

package
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2026 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

View Source
const (
	Dim    = "\033[2m"
	Bold   = "\033[1m"
	Yellow = "\033[33m"
	Cyan   = "\033[36m"
	Red    = "\033[31m"
	Green  = "\033[32m"
	Reset  = "\033[0m"
)
View Source
const (
	ExitOK         = 0 // 成功
	ExitAPI        = 1 // API / 通用错误(含 permission、not_found、conflict、rate_limit)
	ExitValidation = 2 // 参数校验失败
	ExitAuth       = 3 // 认证失败(token 无效 / 过期)
	ExitNetwork    = 4 // 网络错误(连接超时、DNS 解析失败等)
	ExitInternal   = 5 // 内部错误(不应发生)
)

Fine-grained error types (permission, not_found, rate_limit, etc.) are communicated via the JSON error envelope's "type" field, not via exit codes.

View Source
const (
	// Auth: token missing / invalid / expired.
	LarkErrTokenMissing = 99991661 // Authorization header missing or empty
	LarkErrTokenBadFmt  = 99991671 // token format error (must start with "t-" or "u-")
	LarkErrTokenInvalid = 99991668 // user_access_token invalid or expired
	LarkErrATInvalid    = 99991663 // access_token invalid (generic)
	LarkErrTokenExpired = 99991677 // user_access_token expired, refresh to obtain a new one

	// Permission: scope not granted.
	LarkErrAppScopeNotEnabled    = 99991672 // app has not applied for the required API scope
	LarkErrTokenNoPermission     = 99991676 // token lacks the required scope
	LarkErrUserScopeInsufficient = 99991679 // user has not granted the required scope
	LarkErrUserNotAuthorized     = 230027   // user not authorized

	// App credential / status.
	LarkErrAppCredInvalid  = 99991543 // app_id or app_secret is incorrect
	LarkErrAppNotInUse     = 99991662 // app is disabled or not installed in this tenant
	LarkErrAppUnauthorized = 99991673 // app status unavailable; check installation

	// Rate limit.
	LarkErrRateLimit = 99991400 // request frequency limit exceeded

	// Refresh token errors (authn service).
	LarkErrRefreshInvalid     = 20026 // refresh_token invalid or v1 format
	LarkErrRefreshExpired     = 20037 // refresh_token expired
	LarkErrRefreshRevoked     = 20064 // refresh_token revoked
	LarkErrRefreshAlreadyUsed = 20073 // refresh_token already consumed (single-use rotation)
	LarkErrRefreshServerError = 20050 // refresh endpoint server-side error, retryable
)

Lark API generic error code constants. ref: https://open.feishu.cn/document/server-docs/api-call-guide/generic-error-code

Variables

View Source
var PendingNotice func() map[string]interface{}

PendingNotice, if set, returns system-level notices to inject as the "_notice" field in JSON output envelopes. Set by cmd/root.go. Returns nil when there is nothing to report.

Functions

func ClassifyLarkError

func ClassifyLarkError(code int, msg string) (int, string, string)

ClassifyLarkError maps a Lark API error code + message to (exitCode, errType, hint). errType provides fine-grained classification in the JSON envelope; exitCode is kept coarse (ExitAuth or ExitAPI).

func ExtractItems

func ExtractItems(data interface{}) []interface{}

ExtractItems extracts the data array from a response. It tries two strategies in order:

  1. Lark API envelope: result["data"][arrayField] (e.g. {"code":0,"data":{"items":[…]}})
  2. Direct map: result[arrayField] (e.g. {"members":[…],"total":5})

If data is already a plain []interface{}, it is returned as-is.

func FindArrayField

func FindArrayField(data map[string]interface{}) string

FindArrayField finds the primary array field in a response's data object. It first checks knownArrayFields in priority order, then falls back to the lexicographically smallest unknown array field for deterministic results.

func FormatAsCSV

func FormatAsCSV(w io.Writer, data interface{})

FormatAsCSV formats data as CSV (with header) and writes it to w.

func FormatAsCSVPaginated

func FormatAsCSVPaginated(w io.Writer, data interface{}, isFirstPage bool)

FormatAsCSVPaginated formats data as CSV with pagination awareness. When isFirstPage is true, outputs the header row; otherwise only data rows.

func FormatAsTable

func FormatAsTable(w io.Writer, data interface{})

FormatAsTable formats data as a table and writes it to w.

  • []interface{} (array of objects) → header + separator + rows
  • map[string]interface{} (single object) → key-value two-column table
  • empty array → "(empty)"

func FormatAsTablePaginated

func FormatAsTablePaginated(w io.Writer, data interface{}, isFirstPage bool)

FormatAsTablePaginated formats data as a table with pagination awareness. When isFirstPage is true, outputs the header; otherwise only data rows.

func FormatValue

func FormatValue(w io.Writer, data interface{}, format Format)

FormatValue formats a single response and writes it to w.

func GetNotice added in v1.0.1

func GetNotice() map[string]interface{}

GetNotice returns the current pending notice for struct-based callers. Returns nil when there is nothing to report.

func MarkRaw

func MarkRaw(err error) error

MarkRaw sets Raw=true on an ExitError so that enrichment (e.g. enrichPermissionError) is skipped and the original API error is preserved. Returns the original error unchanged if it is not an ExitError.

func PrintError

func PrintError(w io.Writer, msg string)

PrintError prints an error message to w.

func PrintJson

func PrintJson(w io.Writer, data interface{})

PrintJson prints data as formatted JSON to w.

func PrintNdjson

func PrintNdjson(w io.Writer, data interface{})

PrintNdjson prints data as NDJSON (Newline Delimited JSON) to w.

func PrintSuccess

func PrintSuccess(w io.Writer, msg string)

PrintSuccess prints a success message to w.

func PrintTable

func PrintTable(w io.Writer, rows []map[string]interface{})

PrintTable prints rows as a table to w. Delegates to FormatAsTable for flattening, column union, and width handling.

func WriteErrorEnvelope

func WriteErrorEnvelope(w io.Writer, err *ExitError, identity string)

WriteErrorEnvelope writes a JSON error envelope for the given ExitError to w.

Types

type Envelope

type Envelope struct {
	OK       bool                   `json:"ok"`
	Identity string                 `json:"identity,omitempty"`
	Data     interface{}            `json:"data,omitempty"`
	Meta     *Meta                  `json:"meta,omitempty"`
	Notice   map[string]interface{} `json:"_notice,omitempty"`
}

Envelope is the standard success response wrapper.

type ErrDetail

type ErrDetail struct {
	Type       string      `json:"type"`
	Code       int         `json:"code,omitempty"`
	Message    string      `json:"message"`
	Hint       string      `json:"hint,omitempty"`
	ConsoleURL string      `json:"console_url,omitempty"`
	Detail     interface{} `json:"detail,omitempty"`
}

ErrDetail describes a structured error.

type ErrorEnvelope

type ErrorEnvelope struct {
	OK       bool                   `json:"ok"`
	Identity string                 `json:"identity,omitempty"`
	Error    *ErrDetail             `json:"error"`
	Meta     *Meta                  `json:"meta,omitempty"`
	Notice   map[string]interface{} `json:"_notice,omitempty"`
}

ErrorEnvelope is the standard error response wrapper.

type ExitError

type ExitError struct {
	Code   int
	Detail *ErrDetail
	Err    error
	Raw    bool // when true, skip enrichment (e.g. enrichPermissionError) and preserve original error
}

ExitError is a structured error that carries an exit code and optional detail. It is propagated up the call chain and handled by main.go to produce a JSON error envelope on stderr and the correct exit code.

func ErrAPI

func ErrAPI(larkCode int, msg string, detail any) *ExitError

ErrAPI creates an API ExitError using ClassifyLarkError. For permission errors, uses a concise message; the raw API response is preserved in Detail.

func ErrAuth

func ErrAuth(format string, args ...any) *ExitError

ErrAuth creates an auth ExitError (exit 3).

func ErrBare

func ErrBare(code int) *ExitError

ErrBare creates an ExitError with only an exit code and no envelope. Used for cases like `auth check` where the JSON output is already written to stdout.

func ErrNetwork

func ErrNetwork(format string, args ...any) *ExitError

ErrNetwork creates a network ExitError (exit 4).

func ErrValidation

func ErrValidation(format string, args ...any) *ExitError

ErrValidation creates a validation ExitError (exit 2).

func ErrWithHint

func ErrWithHint(code int, errType, msg, hint string) *ExitError

ErrWithHint creates an ExitError with a hint string.

func Errorf

func Errorf(code int, errType, format string, args ...any) *ExitError

Errorf creates an ExitError with the given code, type, and formatted message.

func (*ExitError) Error

func (e *ExitError) Error() string

func (*ExitError) Unwrap

func (e *ExitError) Unwrap() error

type Format

type Format int

Format represents an output format type.

const (
	FormatJSON Format = iota
	FormatNDJSON
	FormatTable
	FormatCSV
)

func ParseFormat

func ParseFormat(s string) (Format, bool)

ParseFormat parses a format string into a Format value. The second return value is false if the format string was not recognized, in which case FormatJSON is returned as default.

func (Format) String

func (f Format) String() string

String returns the string representation of a Format.

type Meta

type Meta struct {
	Count    int    `json:"count,omitempty"`
	Rollback string `json:"rollback,omitempty"`
}

Meta carries optional metadata in envelope responses.

type PaginatedFormatter

type PaginatedFormatter struct {
	W      io.Writer
	Format Format
	// contains filtered or unexported fields
}

PaginatedFormatter holds state across paginated calls to ensure consistent columns (table/csv use the first page's columns for all pages).

func NewPaginatedFormatter

func NewPaginatedFormatter(w io.Writer, format Format) *PaginatedFormatter

NewPaginatedFormatter creates a formatter that tracks pagination state.

func (*PaginatedFormatter) FormatPage

func (pf *PaginatedFormatter) FormatPage(data interface{})

FormatPage formats one page of items.

Jump to

Keyboard shortcuts

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