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:
nullkey
2026-05-06 14:22:36 +08:00
committed by lyingbug
parent 6019c4b661
commit a39805aa89
39 changed files with 2708 additions and 0 deletions
+34
View File
@@ -0,0 +1,34 @@
package agent
import (
"strings"
"github.com/spf13/cobra"
)
// AIAgentHelpKey is the cobra Annotation key used to attach an AI-agent-specific
// help blurb to a command. The blurb is appended to --help output only when
// agent mode is active. Mirrors Stripe's pkg/cmd/templates.go AIAgentHelpAnnotationKey.
const AIAgentHelpKey = "ai_agent_help"
// FormatAgentGuidance returns the agent-targeted help text registered on cmd,
// or "" if none. Render it after the standard help when ShouldUseAgentMode reports true.
func FormatAgentGuidance(cmd *cobra.Command) string {
if cmd == nil {
return ""
}
v, ok := cmd.Annotations[AIAgentHelpKey]
if !ok {
return ""
}
return strings.TrimSpace(v)
}
// SetAgentHelp is a small helper that initializes Annotations and stores the
// blurb under AIAgentHelpKey. Use it in NewCmdX constructors before returning.
func SetAgentHelp(cmd *cobra.Command, blurb string) {
if cmd.Annotations == nil {
cmd.Annotations = map[string]string{}
}
cmd.Annotations[AIAgentHelpKey] = strings.TrimSpace(blurb)
}
+39
View File
@@ -0,0 +1,39 @@
// Package agent handles AI agent integration: --agent flag sugar, env detection,
// and per-command help annotations.
package agent
import "os"
// AIAgentName identifies the detected coding agent invoking the CLI. Empty
// string means no agent detected (or detection is disabled).
type AIAgentName string
// aiAgentEnvs maps environment variable presence to a coding agent name.
// Modeled on Stripe's pkg/useragent/useragent.go DetectAIAgent.
var aiAgentEnvs = []struct {
env string
name AIAgentName
}{
{"CLAUDECODE", "claude-code"},
{"CURSOR_AGENT", "cursor"},
{"CODEX_PROMPT_HOSTNAME", "codex"},
{"AIDER_PROMPT", "aider"},
{"CONTINUE_GLOBAL_DIR", "continue"},
{"OPENCODE_RUNNING", "opencode"},
{"GEMINICODER_PROFILE", "gemini-coder"},
}
// DetectAIAgent returns the first known agent name whose env var is set to a
// non-empty value, or "" if none are present. Detection is suppressed when
// WEKNORA_NO_AGENT_AUTODETECT is truthy. Tests substitute via t.Setenv.
func DetectAIAgent() AIAgentName {
if v := os.Getenv("WEKNORA_NO_AGENT_AUTODETECT"); v != "" && v != "0" && v != "false" {
return ""
}
for _, a := range aiAgentEnvs {
if os.Getenv(a.env) != "" {
return a.name
}
}
return ""
}
+90
View File
@@ -0,0 +1,90 @@
package agent
import (
"testing"
"github.com/stretchr/testify/assert"
)
// clearAgentEnv unsets every env var DetectAIAgent inspects, so a developer
// running these tests from inside Claude Code / Cursor doesn't see false
// positives.
func clearAgentEnv(t *testing.T) {
t.Helper()
for _, a := range aiAgentEnvs {
t.Setenv(a.env, "")
}
t.Setenv("WEKNORA_NO_AGENT_AUTODETECT", "")
t.Setenv("WEKNORA_AGENT", "")
}
func TestDetectAIAgent(t *testing.T) {
cases := []struct {
name string
set map[string]string
want AIAgentName
}{
{name: "empty env", set: nil, want: ""},
{name: "unrelated env", set: map[string]string{"PATH": "/usr/bin"}, want: ""},
{name: "claude code", set: map[string]string{"CLAUDECODE": "1"}, want: "claude-code"},
{name: "cursor", set: map[string]string{"CURSOR_AGENT": "yes"}, want: "cursor"},
{name: "codex", set: map[string]string{"CODEX_PROMPT_HOSTNAME": "host"}, want: "codex"},
{name: "aider", set: map[string]string{"AIDER_PROMPT": "y"}, want: "aider"},
{name: "continue", set: map[string]string{"CONTINUE_GLOBAL_DIR": "/tmp"}, want: "continue"},
{name: "opencode", set: map[string]string{"OPENCODE_RUNNING": "1"}, want: "opencode"},
{name: "gemini-coder", set: map[string]string{"GEMINICODER_PROFILE": "default"}, want: "gemini-coder"},
{
name: "first-match precedence",
set: map[string]string{"CLAUDECODE": "1", "CURSOR_AGENT": "1"},
want: "claude-code",
},
{name: "empty value treated as unset", set: map[string]string{"CLAUDECODE": ""}, want: ""},
{
name: "WEKNORA_NO_AGENT_AUTODETECT=1 suppresses detection",
set: map[string]string{"CLAUDECODE": "1", "WEKNORA_NO_AGENT_AUTODETECT": "1"},
want: "",
},
{
name: "WEKNORA_NO_AGENT_AUTODETECT=0 still allows detection",
set: map[string]string{"CLAUDECODE": "1", "WEKNORA_NO_AGENT_AUTODETECT": "0"},
want: "claude-code",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
clearAgentEnv(t)
for k, v := range tc.set {
t.Setenv(k, v)
}
assert.Equal(t, tc.want, DetectAIAgent())
})
}
}
func TestShouldUseAgentMode_Triggers(t *testing.T) {
t.Run("WEKNORA_AGENT=1 triggers", func(t *testing.T) {
clearAgentEnv(t)
t.Setenv("WEKNORA_AGENT", "1")
assert.True(t, ShouldUseAgentMode(nil))
})
t.Run("WEKNORA_AGENT=true triggers", func(t *testing.T) {
clearAgentEnv(t)
t.Setenv("WEKNORA_AGENT", "true")
assert.True(t, ShouldUseAgentMode(nil))
})
t.Run("WEKNORA_AGENT=0 does not trigger", func(t *testing.T) {
clearAgentEnv(t)
t.Setenv("WEKNORA_AGENT", "0")
assert.False(t, ShouldUseAgentMode(nil))
})
t.Run("AI agent env triggers", func(t *testing.T) {
clearAgentEnv(t)
t.Setenv("CLAUDECODE", "1")
assert.True(t, ShouldUseAgentMode(nil))
})
t.Run("no triggers", func(t *testing.T) {
clearAgentEnv(t)
assert.False(t, ShouldUseAgentMode(nil))
})
}
+56
View File
@@ -0,0 +1,56 @@
package agent
import (
"os"
"github.com/spf13/cobra"
)
// agentSugarFlags lists the flags ApplyAgentSugar sets to their agent-friendly
// defaults when triggered. Each entry is no-op'd at runtime if the leaf hasn't
// registered the flag (e.g. version doesn't have --no-progress).
var agentSugarFlags = []struct{ name, value string }{
{"json", "true"},
{"no-interactive", "true"},
{"no-progress", "true"},
}
// ApplyAgentSugar evaluates --agent / WEKNORA_AGENT / env-based AI agent
// detection, then sets json / no-interactive / no-progress to their
// agent-friendly defaults unless the user already set them.
func ApplyAgentSugar(cmd *cobra.Command) {
if !ShouldUseAgentMode(cmd) {
return
}
for _, kv := range agentSugarFlags {
if f := cmd.Flags().Lookup(kv.name); f != nil && !cmd.Flags().Changed(kv.name) {
_ = cmd.Flags().Set(kv.name, kv.value)
}
}
}
// ShouldUseAgentMode returns true if any of the three triggers are active:
// (1) --agent flag, (2) WEKNORA_AGENT=1 env, (3) a known agent env var is set.
func ShouldUseAgentMode(cmd *cobra.Command) bool {
if cmd != nil {
if v, err := cmd.Flags().GetBool("agent"); err == nil && v {
return true
}
}
if truthy(os.Getenv("WEKNORA_AGENT")) {
return true
}
return DetectAIAgent() != ""
}
// truthy treats any non-empty value other than "0" / "false" / "FALSE" as
// truthy. This is wider than strconv.ParseBool by design — users set
// WEKNORA_AGENT=1, =true, or =yes interchangeably across CI shells.
func truthy(v string) bool {
switch v {
case "", "0", "false", "FALSE":
return false
default:
return true
}
}
+87
View File
@@ -0,0 +1,87 @@
package agent
import (
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// newTestCmd returns a cobra command with the flags ApplyAgentSugar
// expects to be present (`--agent`, `--json`, `--no-interactive`,
// `--no-progress`).
func newTestCmd() *cobra.Command {
c := &cobra.Command{Use: "x"}
c.Flags().Bool("agent", false, "")
c.Flags().Bool("json", false, "")
c.Flags().Bool("no-interactive", false, "")
c.Flags().Bool("no-progress", false, "")
return c
}
func TestApplyAgentSugar_AgentFlagSet(t *testing.T) {
c := newTestCmd()
require.NoError(t, c.Flags().Set("agent", "true"))
ApplyAgentSugar(c)
j, _ := c.Flags().GetBool("json")
assert.True(t, j)
ni, _ := c.Flags().GetBool("no-interactive")
assert.True(t, ni)
np, _ := c.Flags().GetBool("no-progress")
assert.True(t, np)
}
func TestApplyAgentSugar_NoTrigger(t *testing.T) {
clearAgentEnv(t)
c := newTestCmd()
ApplyAgentSugar(c)
j, _ := c.Flags().GetBool("json")
assert.False(t, j, "without --agent or env, --json must remain unset")
}
func TestApplyAgentSugar_ExplicitJSONFalseWins(t *testing.T) {
clearAgentEnv(t)
c := newTestCmd()
require.NoError(t, c.Flags().Set("agent", "true"))
require.NoError(t, c.Flags().Set("json", "false"))
ApplyAgentSugar(c)
j, _ := c.Flags().GetBool("json")
assert.False(t, j, "explicit --json=false must override agent sugar")
}
func TestFormatAgentGuidance(t *testing.T) {
c := &cobra.Command{Use: "x"}
assert.Equal(t, "", FormatAgentGuidance(c))
SetAgentHelp(c, " use --idempotency-key for safe retries ")
assert.Equal(t, "use --idempotency-key for safe retries", FormatAgentGuidance(c))
}
func TestSetAgentHelp_InitsAnnotations(t *testing.T) {
c := &cobra.Command{Use: "x"}
assert.Nil(t, c.Annotations)
SetAgentHelp(c, "blurb")
require.NotNil(t, c.Annotations)
assert.Equal(t, "blurb", c.Annotations[AIAgentHelpKey])
}
func TestTruthy(t *testing.T) {
cases := []struct {
in string
want bool
}{
{"", false},
{"0", false},
{"false", false},
{"FALSE", false},
{"1", true},
{"true", true},
{"yes", true},
{"anything-else", true},
}
for _, tc := range cases {
t.Run(tc.in, func(t *testing.T) {
assert.Equal(t, tc.want, truthy(tc.in))
})
}
}
+16
View File
@@ -0,0 +1,16 @@
// Package build holds compile-time-injected build metadata.
//
// Values are set via -ldflags="-X github.com/Tencent/WeKnora/cli/internal/build.Version=..." at link time;
// the Makefile's `version` target wires them up.
package build
var (
Version = "dev"
Commit = "none"
Date = "unknown"
)
// Info returns a snapshot of the build metadata.
func Info() (version, commit, date string) {
return Version, Commit, Date
}
+25
View File
@@ -0,0 +1,25 @@
package build
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestInfo_DefaultDevValues(t *testing.T) {
v, c, d := Info()
// In a non-ldflags-injected build, these are the package defaults; tests
// that vary them need to assign at run time, not via -ldflags (testing
// here only that Info returns whatever is current).
assert.NotEmpty(t, v)
assert.NotEmpty(t, c)
assert.NotEmpty(t, d)
}
func TestInfo_ReflectsInjectedValues(t *testing.T) {
old := Version
t.Cleanup(func() { Version = old })
Version = "v0.0.0-test"
v, _, _ := Info()
assert.Equal(t, "v0.0.0-test", v)
}
+186
View File
@@ -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
}
+36
View File
@@ -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))
})
}
}
+100
View File
@@ -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
}
+84
View File
@@ -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")
})
}
+30
View File
@@ -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{} }
+33
View File
@@ -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)
}
+135
View File
@@ -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
}
+214
View File
@@ -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)
}
+28
View File
@@ -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()
}
+18
View File
@@ -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")
}
+22
View File
@@ -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))
}
}
+106
View File
@@ -0,0 +1,106 @@
// Package config reads and writes the user-level config at
// $XDG_CONFIG_HOME/weknora/config.yaml. yaml.v3 directly; viper is intentionally
// not used (see ADR-2).
//
// v0.0 supports only Load/Save with multi-host context map; project link
// (.weknora/project.toml) is wired in v0.2 (ADR-16).
package config
import (
"errors"
"fmt"
"os"
"path/filepath"
"gopkg.in/yaml.v3"
)
// Config is the on-disk schema. Empty zero-value is valid (returned when the
// file does not exist) so commands like --help / version don't fail.
type Config struct {
CurrentContext string `yaml:"current_context,omitempty"`
Contexts map[string]Context `yaml:"contexts,omitempty"`
// Defaults holds CLI-wide defaults; fields opt-in.
Defaults struct {
Format string `yaml:"format,omitempty"`
NoVersionCheck bool `yaml:"no_version_check,omitempty"`
RequestIDPrefix string `yaml:"request_id_prefix,omitempty"`
} `yaml:"defaults,omitempty"`
}
// Context is one named connection target (host + tenant + credential reference).
type Context struct {
Host string `yaml:"host"`
TenantID uint64 `yaml:"tenant_id,omitempty"`
User string `yaml:"user,omitempty"`
APIKeyRef string `yaml:"api_key_ref,omitempty"` // keychain://... or file://...
TokenRef string `yaml:"token_ref,omitempty"` // keychain://... or file://...
RefreshRef string `yaml:"refresh_token_ref,omitempty"`
DefaultKBID string `yaml:"default_kb_id,omitempty"`
}
// ErrCorrupt is returned by Load when the file exists but cannot be parsed.
// Callers should map this to error code "local.config_corrupt".
var ErrCorrupt = errors.New("config: file is malformed")
// Path returns the absolute config file path.
//
// We honor XDG_CONFIG_HOME on every OS (CLI convention — gh, kubectl, helm
// all do this even on macOS, where os.UserConfigDir would otherwise return
// ~/Library/Application Support). Falls back to ~/.config/weknora.
func Path() (string, error) {
if x := os.Getenv("XDG_CONFIG_HOME"); x != "" {
return filepath.Join(x, "weknora", "config.yaml"), nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("locate home dir: %w", err)
}
return filepath.Join(home, ".config", "weknora", "config.yaml"), nil
}
// Load reads the config file. If it does not exist, returns a zero-value
// Config with no error (commands like `version` and `--help` must not fail
// just because the user has not run `auth login` yet).
func Load() (*Config, error) {
p, err := Path()
if err != nil {
return nil, err
}
data, err := os.ReadFile(p)
if errors.Is(err, os.ErrNotExist) {
return &Config{}, nil
}
if err != nil {
return nil, fmt.Errorf("read config: %w", err)
}
var c Config
if err := yaml.Unmarshal(data, &c); err != nil {
return nil, fmt.Errorf("%w: %v", ErrCorrupt, err)
}
return &c, nil
}
// Save writes the config atomically (write temp + rename) with mode 0600.
func Save(c *Config) error {
p, err := Path()
if err != nil {
return err
}
if err := os.MkdirAll(filepath.Dir(p), 0o700); err != nil {
return fmt.Errorf("mkdir config dir: %w", err)
}
data, err := yaml.Marshal(c)
if err != nil {
return fmt.Errorf("marshal config: %w", err)
}
tmp := p + ".tmp"
if err := os.WriteFile(tmp, data, 0o600); err != nil {
return fmt.Errorf("write config: %w", err)
}
if err := os.Rename(tmp, p); err != nil {
return fmt.Errorf("rename config: %w", err)
}
return nil
}
+90
View File
@@ -0,0 +1,90 @@
package config
import (
"errors"
"os"
"path/filepath"
"runtime"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/testutil"
)
func TestLoad_FileMissing(t *testing.T) {
testutil.XDGTempDir(t)
c, err := Load()
require.NoError(t, err, "missing file must not error (commands like --help must work)")
assert.NotNil(t, c)
assert.Empty(t, c.Contexts)
}
func TestSaveLoad_RoundTrip(t *testing.T) {
testutil.XDGTempDir(t)
in := &Config{
CurrentContext: "prod",
Contexts: map[string]Context{
"prod": {Host: "https://kb.example.com", TenantID: 7, APIKeyRef: "keychain://weknora/prod/access"},
},
}
require.NoError(t, Save(in))
out, err := Load()
require.NoError(t, err)
assert.Equal(t, "prod", out.CurrentContext)
assert.Equal(t, "https://kb.example.com", out.Contexts["prod"].Host)
assert.Equal(t, uint64(7), out.Contexts["prod"].TenantID)
p, err := Path()
require.NoError(t, err)
st, err := os.Stat(p)
require.NoError(t, err)
if runtime.GOOS != "windows" {
// Windows file ACLs don't map to Unix mode bits; os.Chmod is
// effectively a no-op for owner/group/other distinctions, so the
// 0600 invariant only meaningfully holds on Unix-like platforms.
assert.Equal(t, os.FileMode(0o600), st.Mode().Perm())
}
}
func TestLoad_Corrupt(t *testing.T) {
dir := testutil.XDGTempDir(t)
p := filepath.Join(dir, "weknora", "config.yaml")
require.NoError(t, os.MkdirAll(filepath.Dir(p), 0o700))
require.NoError(t, os.WriteFile(p, []byte("not: valid: yaml: ::"), 0o600))
_, err := Load()
require.Error(t, err)
assert.True(t, errors.Is(err, ErrCorrupt))
}
func TestPath_HonorsXDG(t *testing.T) {
xdg := filepath.Join(t.TempDir(), "xdg")
t.Setenv("XDG_CONFIG_HOME", xdg)
p, err := Path()
require.NoError(t, err)
assert.Equal(t, filepath.Join(xdg, "weknora", "config.yaml"), p)
}
func TestPath_FallsBackToHome(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", "")
t.Setenv("HOME", filepath.Join(t.TempDir(), "home"))
p, err := Path()
require.NoError(t, err)
// Compare via slash-normalized form so the assertion is platform-agnostic
// (Windows uses backslash; semantics here is "the relative tail").
assert.Contains(t, filepath.ToSlash(p), "/.config/weknora/config.yaml")
}
func TestSave_AtomicReplace(t *testing.T) {
dir := testutil.XDGTempDir(t)
require.NoError(t, Save(&Config{CurrentContext: "a"}))
require.NoError(t, Save(&Config{CurrentContext: "b"}))
out, err := Load()
require.NoError(t, err)
assert.Equal(t, "b", out.CurrentContext)
matches, _ := filepath.Glob(filepath.Join(dir, "weknora", "*.tmp"))
assert.Empty(t, matches)
}
+73
View File
@@ -0,0 +1,73 @@
// Package format renders command output: JSON envelope, jq, template, table.
//
// Non-TTY default = JSON envelope (ADR-5). Envelope schema is the contract
// shared with `weknora mcp serve` tools and external agents.
package format
import (
"encoding/json"
"io"
)
// Envelope is the canonical success/failure shape returned by every command.
type Envelope struct {
OK bool `json:"ok"`
Data any `json:"data,omitempty"`
Error *ErrorBody `json:"error,omitempty"`
Meta *Meta `json:"_meta,omitempty"`
}
// Meta carries non-payload context fields useful to agents and observability.
type Meta struct {
Context string `json:"context,omitempty"`
TenantID uint64 `json:"tenant_id,omitempty"`
KBID string `json:"kb_id,omitempty"`
RequestID string `json:"request_id,omitempty"`
NextCursor string `json:"next_cursor,omitempty"`
HasMore bool `json:"has_more,omitempty"`
Warnings []string `json:"warnings,omitempty"`
AppliedFilters []string `json:"applied_filters,omitempty"`
}
// RiskLevel classifies an error by the kind of operation that produced it.
// Agents use this to decide whether to retry, escalate, or stop.
type RiskLevel string
const (
RiskRead RiskLevel = "read"
RiskMutating RiskLevel = "mutating"
RiskDestructive RiskLevel = "destructive"
)
// ErrorBody is the failure shape. `code` is a stable namespaced ID (e.g.
// "auth.unauthenticated"); `hint` is an actionable next step; `risk` flags
// destructive intent for agent self-governance.
type ErrorBody struct {
Code string `json:"code"`
Message string `json:"message"`
Hint string `json:"hint,omitempty"`
RequestID string `json:"request_id,omitempty"`
Context string `json:"context,omitempty"`
Risk RiskLevel `json:"risk,omitempty"`
Retryable bool `json:"retryable,omitempty"`
ConsoleURL string `json:"console_url,omitempty"`
Details map[string]any `json:"details,omitempty"`
}
// WriteEnvelope serializes env as one-line JSON to w. Used for non-TTY output
// and for `--format json` / `--agent` modes.
func WriteEnvelope(w io.Writer, env Envelope) error {
enc := json.NewEncoder(w)
enc.SetEscapeHTML(false)
return enc.Encode(env)
}
// Success constructs a success envelope.
func Success(data any, meta *Meta) Envelope {
return Envelope{OK: true, Data: data, Meta: meta}
}
// Failure constructs a failure envelope.
func Failure(err *ErrorBody) Envelope {
return Envelope{OK: false, Error: err}
}
+50
View File
@@ -0,0 +1,50 @@
package format
import (
"bytes"
"encoding/json"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSuccessEnvelope(t *testing.T) {
env := Success(map[string]string{"id": "kb_abc"}, &Meta{Context: "prod", RequestID: "cli-01"})
var buf bytes.Buffer
require.NoError(t, WriteEnvelope(&buf, env))
var got map[string]any
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
assert.Equal(t, true, got["ok"])
assert.NotNil(t, got["data"])
assert.NotNil(t, got["_meta"])
assert.Nil(t, got["error"])
}
func TestFailureEnvelope(t *testing.T) {
env := Failure(&ErrorBody{
Code: "auth.unauthenticated",
Message: "no creds",
Hint: "run weknora auth login",
Risk: RiskRead,
Retryable: false,
})
var buf bytes.Buffer
require.NoError(t, WriteEnvelope(&buf, env))
var got map[string]any
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
assert.Equal(t, false, got["ok"])
errBody := got["error"].(map[string]any)
assert.Equal(t, "auth.unauthenticated", errBody["code"])
assert.Equal(t, "run weknora auth login", errBody["hint"])
assert.Equal(t, "read", errBody["risk"])
}
func TestEnvelope_NoEscapeHTML(t *testing.T) {
// Hints / messages may include & or <; ensure we don't HTML-escape them
// (would break agent jq pipelines).
env := Failure(&ErrorBody{Code: "x", Message: "a & b < c"})
var buf bytes.Buffer
require.NoError(t, WriteEnvelope(&buf, env))
assert.Contains(t, buf.String(), "a & b < c")
}
+68
View File
@@ -0,0 +1,68 @@
// Package iostreams wraps stdout/stderr/stdin with TTY detection and color awareness.
//
// Tests swap the package-level singleton via SetForTest; production code reads
// the global IO directly. (Tests must not call SetForTest from t.Parallel(),
// since the swap is process-global.)
package iostreams
import (
"bytes"
"io"
"os"
"testing"
"github.com/mattn/go-isatty"
)
// IOStreams holds standard I/O handles plus environment-derived flags.
type IOStreams struct {
In io.Reader
Out io.Writer
Err io.Writer
stdoutTTY bool
stderrTTY bool
}
// IO is the package-level singleton.
var IO *IOStreams = newProduction()
func newProduction() *IOStreams {
return &IOStreams{
In: os.Stdin,
Out: os.Stdout,
Err: os.Stderr,
stdoutTTY: isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd()),
stderrTTY: isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd()),
}
}
// IsStdoutTTY reports whether stdout is a terminal.
func (s *IOStreams) IsStdoutTTY() bool { return s.stdoutTTY }
// IsStderrTTY reports whether stderr is a terminal.
func (s *IOStreams) IsStderrTTY() bool { return s.stderrTTY }
// ColorEnabled honors NO_COLOR (https://no-color.org) and TERM=dumb.
// Computed on demand so env changes after init are picked up by callers.
func (s *IOStreams) ColorEnabled() bool {
if !s.stdoutTTY {
return false
}
if os.Getenv("NO_COLOR") != "" {
return false
}
return os.Getenv("TERM") != "dumb"
}
// SetForTest replaces the package singleton with in-memory buffers for the
// duration of t. Call it once per test. Not safe under t.Parallel().
func SetForTest(t *testing.T) (out, errBuf *bytes.Buffer) {
t.Helper()
saved := IO
out = &bytes.Buffer{}
errBuf = &bytes.Buffer{}
IO = &IOStreams{In: bytes.NewReader(nil), Out: out, Err: errBuf}
t.Cleanup(func() { IO = saved })
return out, errBuf
}
+36
View File
@@ -0,0 +1,36 @@
package iostreams
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestSetForTest(t *testing.T) {
out, errBuf := SetForTest(t)
IO.Out.Write([]byte("stdout"))
IO.Err.Write([]byte("stderr"))
assert.Equal(t, "stdout", out.String())
assert.Equal(t, "stderr", errBuf.String())
}
func TestSetForTest_RestoresSingleton(t *testing.T) {
original := IO
t.Run("nested", func(t *testing.T) {
SetForTest(t)
assert.NotSame(t, original, IO)
})
// After the subtest's t.Cleanup runs, IO must be restored.
assert.Same(t, original, IO)
}
func TestProductionGetters(t *testing.T) {
// We can't reliably assert the *value* of these (depends on whether tests
// run in a TTY) but we can ensure the methods don't panic and return
// consistent values across calls.
p := newProduction()
a, b := p.IsStdoutTTY(), p.IsStderrTTY()
assert.Equal(t, a, p.IsStdoutTTY())
assert.Equal(t, b, p.IsStderrTTY())
_ = p.ColorEnabled() // smoke
}
+32
View File
@@ -0,0 +1,32 @@
// Package prompt defines the interactive-input abstraction.
//
// Production impl will use charmbracelet/huh in v0.0 commands that need
// password input (auth login). Foundation PR ships only the interface +
// a sentinel error so non-TTY contexts surface the right error.
package prompt
import "errors"
// ErrAgentNoPrompt is returned by any Prompter call made when the CLI is in
// agent / non-interactive mode. Commands should map this to a "missing flag"
// user error before returning to cobra.
var ErrAgentNoPrompt = errors.New("prompt: interactive input not available in agent/non-interactive mode")
// Prompter is the small abstraction the auth login flow needs. Tests inject
// scripted responses; production wires charmbracelet/huh.
type Prompter interface {
// Input collects free-form text input from the user.
Input(label, defaultValue string) (string, error)
// Password collects a secret without echoing.
Password(label string) (string, error)
// Confirm asks for yes/no confirmation, used by destructive commands.
Confirm(label string, defaultValue bool) (bool, error)
}
// AgentPrompter rejects all interactive calls. Use it as the Factory.Prompter
// closure result whenever agent mode is detected.
type AgentPrompter struct{}
func (AgentPrompter) Input(string, string) (string, error) { return "", ErrAgentNoPrompt }
func (AgentPrompter) Password(string) (string, error) { return "", ErrAgentNoPrompt }
func (AgentPrompter) Confirm(string, bool) (bool, error) { return false, ErrAgentNoPrompt }
+18
View File
@@ -0,0 +1,18 @@
package prompt
import (
"errors"
"testing"
"github.com/stretchr/testify/assert"
)
func TestAgentPrompter_AlwaysRejects(t *testing.T) {
p := AgentPrompter{}
_, err := p.Input("label", "default")
assert.True(t, errors.Is(err, ErrAgentNoPrompt))
_, err = p.Password("password")
assert.True(t, errors.Is(err, ErrAgentNoPrompt))
_, err = p.Confirm("yes?", false)
assert.True(t, errors.Is(err, ErrAgentNoPrompt))
}
+72
View File
@@ -0,0 +1,72 @@
// Package safepaths provides path-traversal protection for file inputs to
// commands such as `weknora doc upload`.
//
// Two primary checks:
// - Validate(path): reject empty, ".", "..", or paths containing embedded ".." segments.
// - WithinRoot(path, root): both are made absolute and compared with a
// separator-aware prefix check, so a directory named "..foo" cannot
// masquerade as escaping ".." (the lexical strings.HasPrefix(rel, "..")
// trap).
//
// Symlinks are NOT resolved; callers needing realpath semantics must
// pre-resolve. Modeled on the same pattern as `internal/utils/security.go`
// SafePathUnderBase in the server module.
package safepaths
import (
"errors"
"fmt"
"path/filepath"
"strings"
)
// ErrPathEscapes signals that the given path resolves outside the allowed root.
var ErrPathEscapes = errors.New("path escapes allowed root")
// ErrEmptyPath signals an empty input.
var ErrEmptyPath = errors.New("path is empty")
// ErrSuspiciousPath signals a "."/".." or embedded ".." traversal.
var ErrSuspiciousPath = errors.New("path contains suspicious traversal segment")
// Validate cleans path and rejects empty inputs, "." / "..", or any path that
// contains an embedded ".." segment after cleaning. It does not resolve symlinks.
func Validate(path string) (string, error) {
if path == "" {
return "", ErrEmptyPath
}
cleaned := filepath.Clean(path)
if cleaned == "" || cleaned == "." || cleaned == ".." {
return "", fmt.Errorf("%w: %q", ErrSuspiciousPath, path)
}
for _, seg := range strings.Split(cleaned, string(filepath.Separator)) {
if seg == ".." {
return "", fmt.Errorf("%w: %q", ErrSuspiciousPath, path)
}
}
return cleaned, nil
}
// WithinRoot reports whether path lies inside root after both are made
// absolute. Comparison is separator-aware: a path "/srv/data..foo" is NOT
// treated as escaping "/srv/data" just because "..foo" textually starts
// with "..".
func WithinRoot(path, root string) error {
absPath, err := filepath.Abs(path)
if err != nil {
return fmt.Errorf("resolve path: %w", err)
}
absRoot, err := filepath.Abs(root)
if err != nil {
return fmt.Errorf("resolve root: %w", err)
}
// Equal paths count as "within"; otherwise require a separator-bounded prefix.
if absPath == absRoot {
return nil
}
withSep := absRoot + string(filepath.Separator)
if !strings.HasPrefix(absPath, withSep) {
return fmt.Errorf("%w: %s not under %s", ErrPathEscapes, absPath, absRoot)
}
return nil
}
+70
View File
@@ -0,0 +1,70 @@
package safepaths
import (
"errors"
"path/filepath"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestValidate(t *testing.T) {
t.Run("rejects empty", func(t *testing.T) {
_, err := Validate("")
require.ErrorIs(t, err, ErrEmptyPath)
})
t.Run("rejects bare dot", func(t *testing.T) {
_, err := Validate(".")
require.ErrorIs(t, err, ErrSuspiciousPath)
})
t.Run("rejects bare double-dot", func(t *testing.T) {
_, err := Validate("..")
require.ErrorIs(t, err, ErrSuspiciousPath)
})
t.Run("rejects relative path that ascends past start", func(t *testing.T) {
// "../foo" preserves the ".." after Clean.
_, err := Validate("../foo")
require.ErrorIs(t, err, ErrSuspiciousPath)
})
t.Run("cleans benign relative", func(t *testing.T) {
// "a/b/../c" cleans to "a/c" — fine.
got, err := Validate("a/b/../c")
require.NoError(t, err)
assert.Equal(t, filepath.Clean("a/c"), got)
})
t.Run("cleans cancelling relative", func(t *testing.T) {
// "a/../b" cleans to "b" — also fine; the ascent fully resolves.
got, err := Validate("a/../b")
require.NoError(t, err)
assert.Equal(t, "b", got)
})
}
func TestWithinRoot(t *testing.T) {
t.Run("inside root", func(t *testing.T) {
err := WithinRoot("/srv/data/file.md", "/srv/data")
require.NoError(t, err)
})
t.Run("equal to root", func(t *testing.T) {
err := WithinRoot("/srv/data", "/srv/data")
require.NoError(t, err)
})
t.Run("escapes via parent", func(t *testing.T) {
err := WithinRoot("/srv/data/../../etc/passwd", "/srv/data")
require.Error(t, err)
assert.True(t, errors.Is(err, ErrPathEscapes))
})
t.Run("sibling outside", func(t *testing.T) {
err := WithinRoot("/srv/other", "/srv/data")
require.Error(t, err)
assert.True(t, errors.Is(err, ErrPathEscapes))
})
t.Run("dotdot-prefix sibling is not within", func(t *testing.T) {
// /srv/data..foo lexically starts with "/srv/data" but is a different dir.
// Without separator-awareness this would be a false negative.
err := WithinRoot("/srv/data..foo/x", "/srv/data")
require.Error(t, err)
assert.True(t, errors.Is(err, ErrPathEscapes))
})
}
+135
View File
@@ -0,0 +1,135 @@
// Package secrets stores and retrieves credentials.
//
// v0.0 ships a file-only Store implementation (0600 perms under
// $XDG_CONFIG_HOME/weknora/secrets/). The OS keyring backend lands in v0.1
// once auth login is needed in TTY contexts (current PR is foundation only).
//
// Namespace convention: "weknora:<context>:<key>" where key is "access" or "refresh".
package secrets
import (
"errors"
"fmt"
"os"
"path/filepath"
"strings"
)
// ErrNotFound is returned when the requested secret does not exist.
var ErrNotFound = errors.New("secret: not found")
// Store is the abstraction CLI commands depend on; tests inject in-memory impls.
//
// Ref returns a stable URI (e.g. file://<context>/<key> or
// keychain://weknora/<context>/<key>) describing where a saved secret lives.
// Backends own their scheme so commands never need to type-assert the
// concrete implementation.
type Store interface {
Get(context, key string) (string, error)
Set(context, key, value string) error
Delete(context, key string) error
Ref(context, key string) string
}
// FileStore writes 0600 plain-text files under $XDG_CONFIG_HOME/weknora/secrets/<context>.
// It is the headless / CI default and the keychain fallback. Real keychain support
// is wired in v0.1 (see ADR-17 for namespace strategy).
type FileStore struct {
root string
}
// NewFileStore returns a FileStore rooted at $XDG_CONFIG_HOME/weknora/secrets
// (or ~/.config/weknora/secrets if XDG_CONFIG_HOME is unset). Same convention
// as config.Path — see that file for the rationale (CLI convention).
func NewFileStore() (*FileStore, error) {
root, err := defaultRoot()
if err != nil {
return nil, err
}
return &FileStore{root: root}, nil
}
func defaultRoot() (string, error) {
if x := os.Getenv("XDG_CONFIG_HOME"); x != "" {
return filepath.Join(x, "weknora", "secrets"), nil
}
home, err := os.UserHomeDir()
if err != nil {
return "", fmt.Errorf("locate home dir: %w", err)
}
return filepath.Join(home, ".config", "weknora", "secrets"), nil
}
func (f *FileStore) path(context, key string) string {
return filepath.Join(f.root, context, key)
}
func (f *FileStore) Get(context, key string) (string, error) {
data, err := os.ReadFile(f.path(context, key))
if errors.Is(err, os.ErrNotExist) {
return "", ErrNotFound
}
if err != nil {
return "", fmt.Errorf("read secret: %w", err)
}
return string(data), nil
}
func (f *FileStore) Set(context, key, value string) error {
dir := filepath.Join(f.root, context)
if err := os.MkdirAll(dir, 0o700); err != nil {
return fmt.Errorf("mkdir secrets dir: %w", err)
}
if err := os.WriteFile(f.path(context, key), []byte(value), 0o600); err != nil {
return fmt.Errorf("write secret: %w", err)
}
return nil
}
func (f *FileStore) Delete(context, key string) error {
err := os.Remove(f.path(context, key))
if errors.Is(err, os.ErrNotExist) {
return nil
}
return err
}
// Ref returns the file:// URI under which a secret would be stored. Path
// component is forward-slash-normalized per RFC 8089 (file:///path on Unix,
// file:///C:/... on Windows) — the wire format must not depend on platform
// path separator since this string is persisted to config.yaml and may be
// consumed by tooling on a different OS.
func (f *FileStore) Ref(context, key string) string {
p := filepath.ToSlash(f.path(context, key))
if !strings.HasPrefix(p, "/") {
// Windows absolute path "C:/..." needs a leading slash to form a
// proper file:/// URI ("file:///C:/...").
p = "/" + p
}
return "file://" + p
}
// MemStore is an in-memory implementation of Store used by tests across
// packages. It is intentionally exported (not _test.go-only) so that
// downstream packages can compose it without copying the same 20 lines.
type MemStore struct{ m map[string]string }
// NewMemStore returns an empty in-memory secrets store.
func NewMemStore() *MemStore { return &MemStore{m: map[string]string{}} }
func (m *MemStore) k(c, key string) string { return c + ":" + key }
func (m *MemStore) Get(c, key string) (string, error) {
v, ok := m.m[m.k(c, key)]
if !ok {
return "", ErrNotFound
}
return v, nil
}
func (m *MemStore) Set(c, key, value string) error { m.m[m.k(c, key)] = value; return nil }
func (m *MemStore) Delete(c, key string) error { delete(m.m, m.k(c, key)); return nil }
// Ref returns a mem:// URI; meaningful only inside tests.
func (m *MemStore) Ref(c, key string) string { return "mem://" + c + "/" + key }
+87
View File
@@ -0,0 +1,87 @@
package secrets
import (
"errors"
"os"
"runtime"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/Tencent/WeKnora/cli/internal/testutil"
)
func TestFileStore_RoundTrip(t *testing.T) {
testutil.XDGTempDir(t)
s, err := NewFileStore()
require.NoError(t, err)
_, err = s.Get("prod", "access")
require.Error(t, err)
assert.True(t, errors.Is(err, ErrNotFound))
require.NoError(t, s.Set("prod", "access", "secret-value"))
got, err := s.Get("prod", "access")
require.NoError(t, err)
assert.Equal(t, "secret-value", got)
require.NoError(t, s.Delete("prod", "access"))
_, err = s.Get("prod", "access")
require.True(t, errors.Is(err, ErrNotFound))
require.NoError(t, s.Delete("prod", "access"), "Delete on missing must be a no-op")
}
func TestFileStore_FileMode(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("file mode bits don't map to Windows ACLs; 0600 invariant is Unix-only")
}
testutil.XDGTempDir(t)
s, err := NewFileStore()
require.NoError(t, err)
require.NoError(t, s.Set("prod", "access", "v"))
st, err := os.Stat(s.path("prod", "access"))
require.NoError(t, err)
assert.Equal(t, os.FileMode(0o600), st.Mode().Perm(), "secrets must be 0600")
}
func TestFileStore_NamespaceIsolation(t *testing.T) {
testutil.XDGTempDir(t)
s, err := NewFileStore()
require.NoError(t, err)
require.NoError(t, s.Set("prod", "access", "P"))
require.NoError(t, s.Set("staging", "access", "S"))
got, _ := s.Get("prod", "access")
assert.Equal(t, "P", got)
got, _ = s.Get("staging", "access")
assert.Equal(t, "S", got)
}
func TestFileStore_Ref(t *testing.T) {
testutil.XDGTempDir(t)
s, err := NewFileStore()
require.NoError(t, err)
ref := s.Ref("prod", "access")
// Ref is RFC 8089: scheme + slash-normalized path. On Windows the path
// starts with a drive letter (file:///C:/...); on Unix file:///home/...
assert.True(t, strings.HasPrefix(ref, "file:///"), "expected file:/// scheme, got %q", ref)
assert.Contains(t, ref, "/prod/access")
}
func TestMemStore_RoundTripAndRef(t *testing.T) {
s := NewMemStore()
_, err := s.Get("p", "k")
require.ErrorIs(t, err, ErrNotFound)
require.NoError(t, s.Set("p", "k", "v"))
got, err := s.Get("p", "k")
require.NoError(t, err)
assert.Equal(t, "v", got)
assert.Equal(t, "mem://p/k", s.Ref("p", "k"))
require.NoError(t, s.Delete("p", "k"))
_, err = s.Get("p", "k")
require.ErrorIs(t, err, ErrNotFound)
}
+20
View File
@@ -0,0 +1,20 @@
// Package testutil holds small test-only helpers shared across cli/internal packages.
//
// Build tag is intentionally absent: Go links _test.go files only into test
// binaries, but other packages need to import this from their tests. Keep
// production code out.
package testutil
import (
"testing"
)
// XDGTempDir creates a fresh temp dir and points XDG_CONFIG_HOME at it for the
// duration of t. Use whenever a test exercises code that reads
// $XDG_CONFIG_HOME/weknora/* (config.Load, secrets.NewFileStore, ...).
func XDGTempDir(t *testing.T) string {
t.Helper()
dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir)
return dir
}