a39805aa89
Empty cli/ Go module with Factory + Options skeleton that all v0.x commands plug into. Foundation packages (10 internal/): - cmdutil: Factory(3 closure: Config/Client/Prompter) + Options + Errors with namespaced ErrorCode + typed predicates (IsAuthError / IsNotFound / IsTransient / IsAuthExpired) + Exporter + AddJSONFlags + ExitCode/PrintError - iostreams: package singleton with TTY detection; ColorEnabled honors NO_COLOR / TERM=dumb on demand - agent: mode + detect + annotations (Stripe pkg/useragent pattern; CLAUDECODE / CURSOR_AGENT / CODEX_* / AIDER_* / CONTINUE_* / OPENCODE_* / GEMINICODER env detection) - build: ldflags-injected version/commit/date - safepaths: separator-aware path-traversal protection - config: yaml.v3 schema + atomic save 0600 (XDG-style) - format: success/failure envelope (code/hint/request_id/risk/retryable/ console_url) with typed RiskLevel - prompt: Prompter interface + AgentPrompter (rejects in agent mode) - secrets: file 0600 store with weknora:<context>:<key> namespace - testutil: XDGTempDir(t) test helper Smoke command: weknora version (-/--json). Build/test/vet matrix in .github/workflows/cli.yml across linux x macos x windows x Go 1.24. Factory.Client returns CodeLocalUnimplemented until PR-3 wires the SDK adapter; PR-1 commands (version) don't need it.
187 lines
6.2 KiB
Go
187 lines
6.2 KiB
Go
// Package cmdutil contains the Factory, Options helpers, error types,
|
|
// JSON-flag wiring, and the Exporter abstraction shared by all commands.
|
|
package cmdutil
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
// ErrorCode is a namespaced stable identifier carried in the failure envelope.
|
|
// SemVer governance: v0.x maintains the registry below; new codes are noted
|
|
// in release notes. v0.9 introduces a CI compat test (see ADR-6b).
|
|
type ErrorCode string
|
|
|
|
const (
|
|
// auth.* — authentication / permission
|
|
CodeAuthUnauthenticated ErrorCode = "auth.unauthenticated"
|
|
CodeAuthTokenExpired ErrorCode = "auth.token_expired"
|
|
CodeAuthBadCredential ErrorCode = "auth.bad_credential"
|
|
CodeAuthForbidden ErrorCode = "auth.forbidden"
|
|
CodeAuthCrossTenantBlocked ErrorCode = "auth.cross_tenant_blocked"
|
|
CodeAuthTenantMismatch ErrorCode = "auth.tenant_mismatch"
|
|
|
|
// resource.*
|
|
CodeResourceNotFound ErrorCode = "resource.not_found"
|
|
CodeResourceAlreadyExists ErrorCode = "resource.already_exists"
|
|
CodeResourceLocked ErrorCode = "resource.locked"
|
|
|
|
// input.* — flag and argument validation
|
|
CodeInputInvalidArgument ErrorCode = "input.invalid_argument"
|
|
CodeInputMissingFlag ErrorCode = "input.missing_flag"
|
|
|
|
// server.* / network.*
|
|
CodeServerError ErrorCode = "server.error"
|
|
CodeServerTimeout ErrorCode = "server.timeout"
|
|
CodeServerRateLimited ErrorCode = "server.rate_limited"
|
|
CodeServerIncompatibleVersion ErrorCode = "server.incompatible_version"
|
|
CodeNetworkError ErrorCode = "network.error"
|
|
|
|
// local.* — config / file / keychain on the user's machine
|
|
CodeLocalConfigCorrupt ErrorCode = "local.config_corrupt"
|
|
CodeLocalKeychainDenied ErrorCode = "local.keychain_denied"
|
|
CodeLocalFileIO ErrorCode = "local.file_io"
|
|
CodeLocalUnimplemented ErrorCode = "local.unimplemented"
|
|
|
|
// mcp.*
|
|
CodeMCPReadonlyMode ErrorCode = "mcp.readonly_mode"
|
|
CodeMCPToolNotAllowed ErrorCode = "mcp.tool_not_allowed"
|
|
CodeMCPSchemaUnknown ErrorCode = "mcp.schema_unknown_command"
|
|
)
|
|
|
|
// Error is the typed error implementations carry through the call stack.
|
|
// RunE returns a *Error and the root command formats it into the envelope.
|
|
type Error struct {
|
|
Code ErrorCode
|
|
Message string
|
|
Hint string
|
|
Cause error
|
|
Retryable bool
|
|
HTTPStatus int
|
|
}
|
|
|
|
func (e *Error) Error() string {
|
|
if e == nil {
|
|
return ""
|
|
}
|
|
if e.Cause != nil {
|
|
return fmt.Sprintf("%s: %s: %v", e.Code, e.Message, e.Cause)
|
|
}
|
|
return fmt.Sprintf("%s: %s", e.Code, e.Message)
|
|
}
|
|
|
|
func (e *Error) Unwrap() error { return e.Cause }
|
|
|
|
// NewError constructs a typed error.
|
|
func NewError(code ErrorCode, message string) *Error {
|
|
return &Error{Code: code, Message: message}
|
|
}
|
|
|
|
// Wrapf wraps cause with a typed code and Sprintf-style message.
|
|
func Wrapf(code ErrorCode, cause error, format string, args ...any) *Error {
|
|
return &Error{Code: code, Message: fmt.Sprintf(format, args...), Cause: cause}
|
|
}
|
|
|
|
// FlagError signals user-visible flag/argument problems; the root command
|
|
// prints help on top of the message and exits 2 (gh-style).
|
|
type FlagError struct{ err error }
|
|
|
|
func (e *FlagError) Error() string { return e.err.Error() }
|
|
func (e *FlagError) Unwrap() error { return e.err }
|
|
|
|
// NewFlagError wraps err as a FlagError.
|
|
func NewFlagError(err error) error { return &FlagError{err: err} }
|
|
|
|
// SilentError skips printing to stderr; useful when a command has already
|
|
// emitted a fully-formatted message and exits non-zero.
|
|
var SilentError = errors.New("silent error (handled)")
|
|
|
|
// CancelError marks a user-cancelled operation (Ctrl-C / "no" at confirm).
|
|
var CancelError = errors.New("operation cancelled")
|
|
|
|
// Typed predicates — use these instead of comparing ErrorCode strings (Stripe pattern).
|
|
// They walk the error chain so wrapped errors still match.
|
|
|
|
// IsAuthError matches any auth.* code.
|
|
func IsAuthError(err error) bool { return matchPrefix(err, "auth.") }
|
|
|
|
// IsNotFound matches resource.not_found.
|
|
func IsNotFound(err error) bool { return matchCode(err, CodeResourceNotFound) }
|
|
|
|
// IsTransient matches network.* and server.timeout / rate_limited (worth retrying).
|
|
func IsTransient(err error) bool {
|
|
return matchPrefix(err, "network.") ||
|
|
matchCode(err, CodeServerTimeout) ||
|
|
matchCode(err, CodeServerRateLimited)
|
|
}
|
|
|
|
// IsAuthExpired matches auth.token_expired.
|
|
func IsAuthExpired(err error) bool { return matchCode(err, CodeAuthTokenExpired) }
|
|
|
|
// matchCode returns true if err (or anything it wraps) is a *Error with code == c.
|
|
// errors.As walks the wrap chain itself; the explicit unwrap loop is unnecessary.
|
|
func matchCode(err error, c ErrorCode) bool {
|
|
var e *Error
|
|
if !errors.As(err, &e) {
|
|
return false
|
|
}
|
|
return e.Code == c
|
|
}
|
|
|
|
// matchPrefix returns true if err (or anything it wraps) is a *Error whose code
|
|
// has the given namespace prefix (e.g. "auth.").
|
|
func matchPrefix(err error, prefix string) bool {
|
|
var e *Error
|
|
if !errors.As(err, &e) {
|
|
return false
|
|
}
|
|
return strings.HasPrefix(string(e.Code), prefix)
|
|
}
|
|
|
|
// ClassifyHTTPError maps an SDK HTTP error to the canonical ErrorCode by
|
|
// parsing the "HTTP error <status>: ..." message format the SDK currently
|
|
// emits (client.parseResponse). Until the SDK exposes a typed APIError this
|
|
// is the lowest-friction way to surface 401/404/429/etc. as the right
|
|
// envelope code instead of every server-side problem collapsing to
|
|
// server.error.
|
|
//
|
|
// Returns CodeNetworkError when err is not an HTTP error (transport / DNS),
|
|
// and CodeServerError when the status can't be parsed.
|
|
func ClassifyHTTPError(err error) ErrorCode {
|
|
if err == nil {
|
|
return ""
|
|
}
|
|
msg := err.Error()
|
|
rest, ok := strings.CutPrefix(msg, "HTTP error ")
|
|
if !ok {
|
|
return CodeNetworkError
|
|
}
|
|
end := strings.IndexByte(rest, ':')
|
|
if end <= 0 {
|
|
return CodeServerError
|
|
}
|
|
status, perr := strconv.Atoi(rest[:end])
|
|
if perr != nil {
|
|
return CodeServerError
|
|
}
|
|
switch {
|
|
case status == 401:
|
|
return CodeAuthUnauthenticated
|
|
case status == 403:
|
|
return CodeAuthForbidden
|
|
case status == 404:
|
|
return CodeResourceNotFound
|
|
case status == 409:
|
|
return CodeResourceAlreadyExists
|
|
case status == 429:
|
|
return CodeServerRateLimited
|
|
case status >= 500:
|
|
return CodeServerError
|
|
case status >= 400:
|
|
return CodeInputInvalidArgument
|
|
}
|
|
return CodeServerError
|
|
}
|