feat(cli): scaffold weknora CLI module foundation (PR-1)
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.
This commit is contained in:
@@ -0,0 +1,186 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestClassifyHTTPError(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want ErrorCode
|
||||
}{
|
||||
{"nil", nil, ""},
|
||||
{"non-HTTP transport", errors.New("dial tcp: lookup host: no such host"), CodeNetworkError},
|
||||
{"401", fmt.Errorf("HTTP error 401: invalid token"), CodeAuthUnauthenticated},
|
||||
{"403", fmt.Errorf("HTTP error 403: forbidden"), CodeAuthForbidden},
|
||||
{"404", fmt.Errorf("HTTP error 404: kb not found"), CodeResourceNotFound},
|
||||
{"409", fmt.Errorf("HTTP error 409: already exists"), CodeResourceAlreadyExists},
|
||||
{"429", fmt.Errorf("HTTP error 429: slow down"), CodeServerRateLimited},
|
||||
{"500", fmt.Errorf("HTTP error 500: internal"), CodeServerError},
|
||||
{"503", fmt.Errorf("HTTP error 503: unavailable"), CodeServerError},
|
||||
{"400 generic", fmt.Errorf("HTTP error 400: bad input"), CodeInputInvalidArgument},
|
||||
{"422 unprocessable", fmt.Errorf("HTTP error 422: validation"), CodeInputInvalidArgument},
|
||||
{"malformed status", fmt.Errorf("HTTP error abc: oops"), CodeServerError},
|
||||
{"missing colon", fmt.Errorf("HTTP error 404 no colon"), CodeServerError},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, ClassifyHTTPError(tc.err))
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
)
|
||||
|
||||
// ExitCode maps an error to the documented CLI exit code (spec §2.4).
|
||||
// Mirrors gh / Stripe convention:
|
||||
// - 0 success
|
||||
// - 1 generic / unknown
|
||||
// - 2 flag / argument problem
|
||||
// - 3 auth.*
|
||||
// - 4 resource.not_found
|
||||
// - 5 input.*
|
||||
// - 6 server.rate_limited
|
||||
// - 7 server.* (other) / network.*
|
||||
func ExitCode(err error) int {
|
||||
if err == nil {
|
||||
return 0
|
||||
}
|
||||
var fe *FlagError
|
||||
if errors.As(err, &fe) {
|
||||
return 2
|
||||
}
|
||||
if errors.Is(err, SilentError) {
|
||||
return 1
|
||||
}
|
||||
if IsAuthError(err) {
|
||||
return 3
|
||||
}
|
||||
if IsNotFound(err) {
|
||||
return 4
|
||||
}
|
||||
if matchPrefix(err, "input.") {
|
||||
return 5
|
||||
}
|
||||
if matchCode(err, CodeServerRateLimited) {
|
||||
return 6
|
||||
}
|
||||
if matchPrefix(err, "server.") || matchPrefix(err, "network.") {
|
||||
return 7
|
||||
}
|
||||
return 1
|
||||
}
|
||||
|
||||
// PrintError writes err to w as one human-readable line. The envelope-aware
|
||||
// JSON formatter is in `internal/format`; this helper is the human path used
|
||||
// when no command produced its own output.
|
||||
func PrintError(w io.Writer, err error) {
|
||||
if err == nil || errors.Is(err, SilentError) {
|
||||
return
|
||||
}
|
||||
fmt.Fprintln(w, err.Error())
|
||||
}
|
||||
|
||||
// PrintErrorEnvelope writes err as a JSON envelope on w. Used in agent mode /
|
||||
// --json / --format=json output so failures stay machine-parseable.
|
||||
func PrintErrorEnvelope(w io.Writer, err error) {
|
||||
if err == nil || errors.Is(err, SilentError) {
|
||||
return
|
||||
}
|
||||
_ = format.WriteEnvelope(w, format.Failure(ToErrorBody(err)))
|
||||
}
|
||||
|
||||
// ToErrorBody projects err into the canonical envelope ErrorBody. Exposed so
|
||||
// other emit paths (planned: MCP) reuse the same projection rather than
|
||||
// reimplementing the typed-error → wire-shape mapping.
|
||||
func ToErrorBody(err error) *format.ErrorBody {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
body := &format.ErrorBody{Message: err.Error()}
|
||||
var typed *Error
|
||||
if errors.As(err, &typed) {
|
||||
body.Code = string(typed.Code)
|
||||
body.Message = typed.Message
|
||||
body.Hint = typed.Hint
|
||||
body.Retryable = typed.Retryable
|
||||
// Surface the wrapped cause so agents see the actual server / SDK
|
||||
// error string, not just the wrap message ("hybrid search"). Stripe's
|
||||
// envelope does the same — the human's printed line and the JSON
|
||||
// envelope both end with the underlying problem.
|
||||
if typed.Cause != nil {
|
||||
body.Message = typed.Message + ": " + typed.Cause.Error()
|
||||
}
|
||||
return body
|
||||
}
|
||||
var fe *FlagError
|
||||
if errors.As(err, &fe) {
|
||||
body.Code = string(CodeInputInvalidArgument)
|
||||
return body
|
||||
}
|
||||
// Unclassified error; consumers see the message but no stable code.
|
||||
body.Code = string(CodeServerError)
|
||||
return body
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestExitCode(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
err error
|
||||
want int
|
||||
}{
|
||||
{"nil success", nil, 0},
|
||||
{"flag error", NewFlagError(errors.New("bad flag")), 2},
|
||||
{"silent", SilentError, 1},
|
||||
{"auth.* prefix", NewError(CodeAuthUnauthenticated, "x"), 3},
|
||||
{"auth.token_expired", NewError(CodeAuthTokenExpired, "x"), 3},
|
||||
{"resource.not_found", NewError(CodeResourceNotFound, "x"), 4},
|
||||
{"input.* prefix", NewError(CodeInputInvalidArgument, "x"), 5},
|
||||
{"input.missing_flag", NewError(CodeInputMissingFlag, "x"), 5},
|
||||
{"server.rate_limited", NewError(CodeServerRateLimited, "x"), 6},
|
||||
{"server.* prefix", NewError(CodeServerError, "x"), 7},
|
||||
{"server.timeout", NewError(CodeServerTimeout, "x"), 7},
|
||||
{"network.* prefix", NewError(CodeNetworkError, "x"), 7},
|
||||
{"unknown error", errors.New("plain"), 1},
|
||||
{"local.* prefix", NewError(CodeLocalConfigCorrupt, "x"), 1},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, ExitCode(tc.err))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestToErrorBody(t *testing.T) {
|
||||
t.Run("nil returns nil", func(t *testing.T) {
|
||||
assert.Nil(t, ToErrorBody(nil))
|
||||
})
|
||||
t.Run("typed without cause", func(t *testing.T) {
|
||||
body := ToErrorBody(NewError(CodeResourceNotFound, "kb missing"))
|
||||
assert.Equal(t, "resource.not_found", body.Code)
|
||||
assert.Equal(t, "kb missing", body.Message)
|
||||
})
|
||||
t.Run("typed with cause surfaces inner", func(t *testing.T) {
|
||||
inner := errors.New("HTTP error 500: server exploded")
|
||||
body := ToErrorBody(Wrapf(CodeServerError, inner, "hybrid search"))
|
||||
assert.Equal(t, "server.error", body.Code)
|
||||
// Both wrap context AND server cause must appear so agents see what
|
||||
// actually broke, not just our wrap label.
|
||||
assert.Equal(t, "hybrid search: HTTP error 500: server exploded", body.Message)
|
||||
})
|
||||
t.Run("flag error", func(t *testing.T) {
|
||||
body := ToErrorBody(NewFlagError(errors.New("bad flag")))
|
||||
assert.Equal(t, "input.invalid_argument", body.Code)
|
||||
})
|
||||
t.Run("unclassified", func(t *testing.T) {
|
||||
body := ToErrorBody(errors.New("anything"))
|
||||
assert.Equal(t, "server.error", body.Code)
|
||||
assert.Equal(t, "anything", body.Message)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPrintError(t *testing.T) {
|
||||
t.Run("nil is silent", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
PrintError(&buf, nil)
|
||||
assert.Empty(t, buf.String())
|
||||
})
|
||||
t.Run("SilentError is silent", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
PrintError(&buf, SilentError)
|
||||
assert.Empty(t, buf.String())
|
||||
})
|
||||
t.Run("typed error prints message", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
PrintError(&buf, NewError(CodeAuthUnauthenticated, "no creds"))
|
||||
assert.Contains(t, buf.String(), "auth.unauthenticated")
|
||||
assert.Contains(t, buf.String(), "no creds")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
)
|
||||
|
||||
// Exporter renders command output. Foundation PR ships a single
|
||||
// jsonExporter that writes the envelope; PR-3 lands lipgloss tables, jq,
|
||||
// and templates as additional implementations.
|
||||
type Exporter interface {
|
||||
Write(w io.Writer, env format.Envelope) error
|
||||
}
|
||||
|
||||
// NewJSONExporter returns an Exporter that emits envelope JSON via
|
||||
// format.WriteEnvelope (single-source encoder config: no HTML escape).
|
||||
func NewJSONExporter() Exporter { return &jsonExporter{} }
|
||||
|
||||
type jsonExporter struct{}
|
||||
|
||||
func (jsonExporter) Write(w io.Writer, env format.Envelope) error {
|
||||
return format.WriteEnvelope(w, env)
|
||||
}
|
||||
|
||||
// NewTableExporter is a foundation-PR alias for the JSON exporter; PR-3
|
||||
// replaces it with a lipgloss-based renderer that respects iostreams.IO
|
||||
// ColorEnabled. Until then table output looks identical to JSON output so
|
||||
// commands work end-to-end either way.
|
||||
func NewTableExporter(_ []string) Exporter { return &jsonExporter{} }
|
||||
@@ -0,0 +1,33 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
)
|
||||
|
||||
func TestJSONExporter_WritesEnvelope(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
exp := NewJSONExporter()
|
||||
require.NoError(t, exp.Write(&buf, format.Success(map[string]string{"k": "v"}, nil)))
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
assert.Equal(t, true, got["ok"])
|
||||
}
|
||||
|
||||
func TestTableExporter_PR1AliasesJSON(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, NewTableExporter([]string{"id"}).Write(&buf, format.Success("x", nil)))
|
||||
assert.Contains(t, buf.String(), `"ok":true`)
|
||||
}
|
||||
|
||||
func TestFlagError_IsSentinel(t *testing.T) {
|
||||
err := NewFlagError(assert.AnError)
|
||||
_, ok := err.(*FlagError)
|
||||
assert.True(t, ok)
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// Factory is the dependency container injected at command construction. Each
|
||||
// closure is lazy: --help / completion / `weknora schema` must NOT trigger
|
||||
// HTTP, keyring access, or filesystem I/O beyond the bare minimum.
|
||||
//
|
||||
// Four closures (ADR-4):
|
||||
// - Config: parses ~/.config/weknora/config.yaml (no network)
|
||||
// - Client: constructs the SDK client (network: server compat probe + cached)
|
||||
// - Prompter: returns interactive prompter; agent mode returns AgentPrompter
|
||||
// - Secrets: builds the OS keyring / file fallback credential store the
|
||||
// first time it is requested (probing the keyring at startup
|
||||
// would fork+exec on macOS and DBus-touch on Linux,
|
||||
// defeating the lazy contract above).
|
||||
//
|
||||
// IOStreams is intentionally NOT a Factory closure — it is the package singleton
|
||||
// iostreams.IO. The bar to add a new closure is at least 2 commands sharing the
|
||||
// same dependency; resist factory bloat (gh CLI cautionary tale).
|
||||
//
|
||||
// Client returns a *sdk.Client (the WeKnora SDK). Commands that want narrow
|
||||
// service interfaces (per ADR-4) declare them in their own files and let the
|
||||
// real SDK satisfy them implicitly via duck typing.
|
||||
type Factory struct {
|
||||
Config func() (*config.Config, error)
|
||||
Client func() (*sdk.Client, error)
|
||||
Prompter func() prompt.Prompter
|
||||
Secrets func() (secrets.Store, error)
|
||||
}
|
||||
|
||||
// New constructs a production Factory wired to real config / SDK client.
|
||||
//
|
||||
// All closures are lazy: invoking --help, version, or shell completion runs
|
||||
// none of them. The Secrets closure memoizes via sync.Once so the keyring
|
||||
// probe happens at most once per process.
|
||||
func New() *Factory {
|
||||
var (
|
||||
secretsOnce sync.Once
|
||||
secretsStore secrets.Store
|
||||
secretsErr error
|
||||
)
|
||||
f := &Factory{}
|
||||
f.Config = func() (*config.Config, error) { return config.Load() }
|
||||
f.Client = func() (*sdk.Client, error) { return buildClient(f) }
|
||||
f.Prompter = func() prompt.Prompter {
|
||||
if iostreams.IO.IsStdoutTTY() && iostreams.IO.IsStderrTTY() {
|
||||
return prompt.NewTTYPrompter()
|
||||
}
|
||||
return prompt.AgentPrompter{}
|
||||
}
|
||||
f.Secrets = func() (secrets.Store, error) {
|
||||
secretsOnce.Do(func() {
|
||||
secretsStore, secretsErr = secrets.NewBestEffortStore()
|
||||
})
|
||||
return secretsStore, secretsErr
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// buildClient resolves the active context, loads the credentials from secrets,
|
||||
// and constructs a *sdk.Client. Returns CodeAuthUnauthenticated when no
|
||||
// credentials are available so the user gets the right hint to run
|
||||
// `weknora auth login`.
|
||||
func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
cfg, err := f.Config()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctxName := cfg.CurrentContext
|
||||
if ctxName == "" {
|
||||
return nil, NewError(CodeAuthUnauthenticated, "no current context configured; run `weknora auth login` to set one up")
|
||||
}
|
||||
ctx, ok := cfg.Contexts[ctxName]
|
||||
if !ok {
|
||||
return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("config references unknown context %q", ctxName))
|
||||
}
|
||||
if ctx.Host == "" {
|
||||
return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("context %q has no host", ctxName))
|
||||
}
|
||||
|
||||
opts := []sdk.ClientOption{}
|
||||
store, err := f.Secrets()
|
||||
if err != nil {
|
||||
return nil, Wrapf(CodeLocalKeychainDenied, err, "init secrets store")
|
||||
}
|
||||
// Only fetch the secrets the context actually references. Skipping the
|
||||
// unused fetch avoids a `security` exec (macOS) / DBus call (Linux) per
|
||||
// authenticated invocation.
|
||||
if ctx.TokenRef != "" {
|
||||
if access, err := loadSecret(store, ctxName, "access"); err != nil {
|
||||
return nil, err
|
||||
} else if access != "" {
|
||||
opts = append(opts, sdk.WithBearerToken(access))
|
||||
}
|
||||
}
|
||||
if ctx.APIKeyRef != "" {
|
||||
if apiKey, err := loadSecret(store, ctxName, "api_key"); err != nil {
|
||||
return nil, err
|
||||
} else if apiKey != "" {
|
||||
opts = append(opts, sdk.WithAPIKey(apiKey))
|
||||
}
|
||||
}
|
||||
// ctx.TenantID is intentionally NOT injected as X-Tenant-ID. Servers derive
|
||||
// tenant from the credential itself (JWT claim or API key prefix); the
|
||||
// header is only meaningful for explicit cross-tenant switching by users
|
||||
// with CanAccessAllTenants. Auto-mirroring the persisted tenant from config
|
||||
// breaks that contract — gh / gcloud / Stripe CLIs all require an explicit
|
||||
// flag (`--tenant=N` is the planned v0.1 entry point) before sending it.
|
||||
// `tenant_id` stays in config for `auth status` display only.
|
||||
return sdk.NewClient(ctx.Host, opts...), nil
|
||||
}
|
||||
|
||||
// loadSecret returns the stored value for (context, key); ErrNotFound becomes
|
||||
// ("", nil) so callers can treat "not configured" as success.
|
||||
func loadSecret(store secrets.Store, context, key string) (string, error) {
|
||||
v, err := store.Get(context, key)
|
||||
if errors.Is(err, secrets.ErrNotFound) {
|
||||
return "", nil
|
||||
}
|
||||
if err != nil {
|
||||
return "", Wrapf(CodeLocalKeychainDenied, err, "load %s", key)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/prompt"
|
||||
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// TestFactory_Lazy ensures none of the closures execute work at construction
|
||||
// time — `--help` / `completion` must not trigger HTTP / keyring access.
|
||||
func TestFactory_Lazy(t *testing.T) {
|
||||
var configCalls, clientCalls, prompterCalls int
|
||||
f := &Factory{
|
||||
Config: func() (*config.Config, error) {
|
||||
configCalls++
|
||||
return &config.Config{}, nil
|
||||
},
|
||||
Client: func() (*sdk.Client, error) {
|
||||
clientCalls++
|
||||
return nil, nil
|
||||
},
|
||||
Prompter: func() prompt.Prompter {
|
||||
prompterCalls++
|
||||
return prompt.AgentPrompter{}
|
||||
},
|
||||
}
|
||||
// Asserting on closure presence — none should have run yet.
|
||||
assert.Equal(t, 0, configCalls)
|
||||
assert.Equal(t, 0, clientCalls)
|
||||
assert.Equal(t, 0, prompterCalls)
|
||||
// Smoke: each closure runs exactly once when called.
|
||||
_, err := f.Config()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, configCalls)
|
||||
_, _ = f.Client()
|
||||
assert.Equal(t, 1, clientCalls)
|
||||
_ = f.Prompter()
|
||||
assert.Equal(t, 1, prompterCalls)
|
||||
}
|
||||
|
||||
// TestNew_FoundationDefaults verifies the production New() returns a usable
|
||||
// Factory and that Client surfaces auth.unauthenticated when no current
|
||||
// context is configured (the precondition for `weknora auth login`).
|
||||
func TestNew_FoundationDefaults(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir()) // empty config → no current context
|
||||
f := New()
|
||||
require.NotNil(t, f)
|
||||
require.NotNil(t, f.Config)
|
||||
require.NotNil(t, f.Client)
|
||||
require.NotNil(t, f.Prompter)
|
||||
require.NotNil(t, f.Secrets)
|
||||
|
||||
_, err := f.Client()
|
||||
require.Error(t, err)
|
||||
var typed *Error
|
||||
require.True(t, errors.As(err, &typed), "expected *cmdutil.Error")
|
||||
assert.Equal(t, CodeAuthUnauthenticated, typed.Code)
|
||||
}
|
||||
|
||||
// TestTypedPredicates exercises the namespace and code matchers.
|
||||
func TestTypedPredicates(t *testing.T) {
|
||||
t.Run("IsAuthError matches auth.* prefix", func(t *testing.T) {
|
||||
err := NewError(CodeAuthUnauthenticated, "no creds")
|
||||
assert.True(t, IsAuthError(err))
|
||||
assert.False(t, IsNotFound(err))
|
||||
})
|
||||
t.Run("IsNotFound matches resource.not_found exactly", func(t *testing.T) {
|
||||
err := NewError(CodeResourceNotFound, "kb missing")
|
||||
assert.True(t, IsNotFound(err))
|
||||
assert.False(t, IsTransient(err))
|
||||
})
|
||||
t.Run("IsTransient matches network.* and server.timeout / rate_limited", func(t *testing.T) {
|
||||
assert.True(t, IsTransient(NewError(CodeNetworkError, "")))
|
||||
assert.True(t, IsTransient(NewError(CodeServerTimeout, "")))
|
||||
assert.True(t, IsTransient(NewError(CodeServerRateLimited, "")))
|
||||
assert.False(t, IsTransient(NewError(CodeServerError, "")))
|
||||
})
|
||||
t.Run("predicates walk the wrap chain", func(t *testing.T) {
|
||||
inner := NewError(CodeAuthTokenExpired, "expired")
|
||||
wrapped := Wrapf(CodeServerError, inner, "while calling foo")
|
||||
// IsAuthExpired matches the wrapped *Error first; outer Wrapf has
|
||||
// CodeServerError so the predicate returns false on the outer match.
|
||||
// This documents current behavior: predicates report the first *Error
|
||||
// in the chain, not deep walks.
|
||||
assert.False(t, IsAuthExpired(wrapped))
|
||||
// Direct match works.
|
||||
assert.True(t, IsAuthExpired(inner))
|
||||
})
|
||||
t.Run("non-typed errors are never matched", func(t *testing.T) {
|
||||
assert.False(t, IsAuthError(errors.New("plain error")))
|
||||
assert.False(t, IsNotFound(nil))
|
||||
})
|
||||
}
|
||||
|
||||
// TestError_Format checks the Error/Unwrap surface.
|
||||
func TestError_Format(t *testing.T) {
|
||||
cause := errors.New("dial tcp: refused")
|
||||
e := Wrapf(CodeNetworkError, cause, "connect to %s", "host")
|
||||
assert.Contains(t, e.Error(), "network.error")
|
||||
assert.Contains(t, e.Error(), "connect to host")
|
||||
assert.Contains(t, e.Error(), "dial tcp: refused")
|
||||
assert.Same(t, cause, errors.Unwrap(e))
|
||||
}
|
||||
|
||||
func memSecretsFn(s *secrets.MemStore) func() (secrets.Store, error) {
|
||||
return func() (secrets.Store, error) { return s, nil }
|
||||
}
|
||||
|
||||
func TestBuildClient_NoCurrentContext(t *testing.T) {
|
||||
f := &Factory{
|
||||
Config: func() (*config.Config, error) { return &config.Config{}, nil },
|
||||
Secrets: memSecretsFn(secrets.NewMemStore()),
|
||||
}
|
||||
_, err := buildClient(f)
|
||||
require.Error(t, err)
|
||||
var typed *Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, CodeAuthUnauthenticated, typed.Code)
|
||||
}
|
||||
|
||||
func TestBuildClient_UnknownContext(t *testing.T) {
|
||||
f := &Factory{
|
||||
Config: func() (*config.Config, error) {
|
||||
return &config.Config{CurrentContext: "ghost"}, nil
|
||||
},
|
||||
Secrets: memSecretsFn(secrets.NewMemStore()),
|
||||
}
|
||||
_, err := buildClient(f)
|
||||
require.Error(t, err)
|
||||
var typed *Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, CodeLocalConfigCorrupt, typed.Code)
|
||||
}
|
||||
|
||||
func TestBuildClient_MissingHost(t *testing.T) {
|
||||
f := &Factory{
|
||||
Config: func() (*config.Config, error) {
|
||||
return &config.Config{
|
||||
CurrentContext: "p",
|
||||
Contexts: map[string]config.Context{"p": {Host: ""}},
|
||||
}, nil
|
||||
},
|
||||
Secrets: memSecretsFn(secrets.NewMemStore()),
|
||||
}
|
||||
_, err := buildClient(f)
|
||||
require.Error(t, err)
|
||||
var typed *Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
assert.Equal(t, CodeLocalConfigCorrupt, typed.Code)
|
||||
}
|
||||
|
||||
func TestBuildClient_HappyPath(t *testing.T) {
|
||||
store := secrets.NewMemStore()
|
||||
require.NoError(t, store.Set("p", "access", "jwt"))
|
||||
require.NoError(t, store.Set("p", "api_key", "sk-x"))
|
||||
f := &Factory{
|
||||
Config: func() (*config.Config, error) {
|
||||
return &config.Config{
|
||||
CurrentContext: "p",
|
||||
Contexts: map[string]config.Context{
|
||||
"p": {
|
||||
Host: "https://kb.example.com",
|
||||
TenantID: 7,
|
||||
TokenRef: "mem://p/access",
|
||||
APIKeyRef: "mem://p/api_key",
|
||||
},
|
||||
},
|
||||
}, nil
|
||||
},
|
||||
Secrets: memSecretsFn(store),
|
||||
}
|
||||
cli, err := buildClient(f)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, cli)
|
||||
}
|
||||
|
||||
func TestBuildClient_SkipsUnreferencedSecrets(t *testing.T) {
|
||||
// If the context doesn't list APIKeyRef, buildClient must not call
|
||||
// Get(api_key) — a perf invariant: avoid keychain trips for unused creds.
|
||||
store := &countingSecrets{MemStore: secrets.NewMemStore()}
|
||||
require.NoError(t, store.Set("p", "access", "jwt"))
|
||||
f := &Factory{
|
||||
Config: func() (*config.Config, error) {
|
||||
return &config.Config{
|
||||
CurrentContext: "p",
|
||||
Contexts: map[string]config.Context{
|
||||
"p": {Host: "https://x", TokenRef: "mem://p/access"},
|
||||
},
|
||||
}, nil
|
||||
},
|
||||
Secrets: func() (secrets.Store, error) { return store, nil },
|
||||
}
|
||||
_, err := buildClient(f)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, 1, store.gets, "must fetch only access; api_key was not referenced")
|
||||
}
|
||||
|
||||
// countingSecrets wraps MemStore to count Get invocations.
|
||||
type countingSecrets struct {
|
||||
*secrets.MemStore
|
||||
gets int
|
||||
}
|
||||
|
||||
func (c *countingSecrets) Get(ctx, key string) (string, error) {
|
||||
c.gets++
|
||||
return c.MemStore.Get(ctx, key)
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// AddJSONFlags registers the standard output triplet on cmd:
|
||||
//
|
||||
// --json [fields] JSON envelope output, optional field-projection list
|
||||
// --jq <expr> embedded jq filter (PR-3 wires the real evaluator)
|
||||
// --template <tmpl> Go text/template (PR-3)
|
||||
//
|
||||
// The three flags are mutually exclusive at evaluation time; PR-3 enforces it.
|
||||
// `fields` is the list of valid field names that --json [fields] may project
|
||||
// against; commands pass their resource's field set (kb / doc / chunk / ...).
|
||||
//
|
||||
// *exporter is initialized to a JSON exporter; PR-3 swaps in jq/template
|
||||
// variants based on which flag the user supplied.
|
||||
func AddJSONFlags(cmd *cobra.Command, exporter *Exporter, fields []string) {
|
||||
_ = fields // PR-3 uses this for --json field-list completion + validation
|
||||
var jsonOut bool
|
||||
var jqExpr string
|
||||
var tmpl string
|
||||
cmd.Flags().BoolVar(&jsonOut, "json", false, "Output JSON envelope")
|
||||
cmd.Flags().StringVar(&jqExpr, "jq", "", "Filter output via embedded jq expression")
|
||||
cmd.Flags().StringVar(&tmpl, "template", "", "Format output via Go text/template")
|
||||
*exporter = NewJSONExporter()
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestAddJSONFlags_RegistersFlags(t *testing.T) {
|
||||
c := &cobra.Command{Use: "x"}
|
||||
var exp Exporter
|
||||
AddJSONFlags(c, &exp, []string{"id", "name"})
|
||||
assert.NotNil(t, c.Flags().Lookup("json"))
|
||||
assert.NotNil(t, c.Flags().Lookup("jq"))
|
||||
assert.NotNil(t, c.Flags().Lookup("template"))
|
||||
assert.NotNil(t, exp, "exporter must be initialized")
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// Options is the marker interface every command's <Verb>Options struct should
|
||||
// satisfy. Concrete Options structs (KbListOptions, DocUploadOptions, ...)
|
||||
// are declared in their own command file; see CONTRIBUTING.md for the template.
|
||||
type Options interface{}
|
||||
|
||||
// MustRequireFlag panics on programmer error (typo in flag name). cobra's
|
||||
// MarkFlagRequired only returns an error when the named flag does not exist
|
||||
// on the command, which means the caller has a typo at registration time —
|
||||
// non-recoverable. Wrap so command builders stay one-line.
|
||||
func MustRequireFlag(cmd *cobra.Command, name string) {
|
||||
if err := cmd.MarkFlagRequired(name); err != nil {
|
||||
panic(fmt.Sprintf("MarkFlagRequired %q: %v", name, err))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user