feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING)
D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
This commit is contained in:
@@ -0,0 +1,148 @@
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
type AddOptions struct {
|
||||
Host string
|
||||
User string
|
||||
}
|
||||
|
||||
// profileAddFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `profile add`. The result describes the newly-registered profile.
|
||||
var profileAddFields = []string{
|
||||
"name", "host", "user", "current",
|
||||
}
|
||||
|
||||
// addResult is the typed payload emitted under data on success.
|
||||
type addResult struct {
|
||||
Name string `json:"name"`
|
||||
Host string `json:"host"`
|
||||
User string `json:"user,omitempty"`
|
||||
Current bool `json:"current"`
|
||||
}
|
||||
|
||||
// NewCmdAdd builds `weknora profile add`. Registers a *credentialless*
|
||||
// connection target - host + optional user only. Credentials for the new
|
||||
// profile are attached separately with `weknora auth login --name <n>`,
|
||||
// separating "where" the CLI talks to (the host) and "how" it authenticates
|
||||
// (the credential). If you want one command for both, run
|
||||
// `weknora auth login --name <n> --host <h>` instead.
|
||||
func NewCmdAdd(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &AddOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "add <name>",
|
||||
Short: "Register a new profile (host without credentials)",
|
||||
Long: `Add a new profile entry to config.yaml. Stores host (and optionally
|
||||
user) but does NOT prompt for credentials. Use ` + "`weknora auth login --name <n>`" + ` to
|
||||
attach credentials in a single step instead, or run ` + "`weknora auth login --name <n>`" + ` after
|
||||
` + "`weknora profile add`" + ` to fill them in.
|
||||
|
||||
The first profile added is auto-selected as the current profile. Subsequent
|
||||
adds leave the current profile untouched.`,
|
||||
Example: ` weknora profile add staging --host https://staging.example.com
|
||||
weknora profile add prod --host https://prod.example.com --user alice@example.com`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
return runAdd(opts, fopts, args[0])
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Host, "host", "", "Server base URL, e.g. https://kb.example.com (required)")
|
||||
cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'profile list' (optional, cosmetic only)")
|
||||
cmdutil.AddFormatFlag(cmd, profileAddFields...)
|
||||
_ = cmd.MarkFlagRequired("host")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runAdd(opts *AddOptions, fopts *cmdutil.FormatOptions, name string) error {
|
||||
if err := validateName(name); err != nil {
|
||||
return err
|
||||
}
|
||||
host, err := cmdutil.NormalizeHost(opts.Host)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, exists := cfg.Contexts[name]; exists {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeResourceAlreadyExists,
|
||||
Message: fmt.Sprintf("profile %q already exists", name),
|
||||
Hint: fmt.Sprintf("use a different name, or run `weknora profile remove %s` first", name),
|
||||
}
|
||||
}
|
||||
if cfg.Contexts == nil {
|
||||
cfg.Contexts = map[string]config.Context{}
|
||||
}
|
||||
cfg.Contexts[name] = config.Context{Host: host, User: opts.User}
|
||||
wasFirst := cfg.CurrentContext == ""
|
||||
if wasFirst {
|
||||
cfg.CurrentContext = name
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
|
||||
}
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, addResult{Name: name, Host: host, User: opts.User, Current: wasFirst}, nil)
|
||||
}
|
||||
if wasFirst {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s (now current). Run `weknora auth login --name %s` to attach credentials.\n", name, name)
|
||||
} else {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added profile %s. Run `weknora auth login --name %s` to attach credentials.\n", name, name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validateName enforces the allowlist advertised in the --help hint: letters,
|
||||
// digits, dash, underscore, dot. The `.` exception lets emails / DNS-like
|
||||
// names through; the path-traversal `..` is structurally rejected by a
|
||||
// separate guard because it would let a hand-edited config.yaml claim a
|
||||
// profile whose name walks out of the keyring namespace.
|
||||
func validateName(name string) error {
|
||||
if name == "" {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: "profile name must not be empty",
|
||||
}
|
||||
}
|
||||
if name == "." || name == ".." || strings.Contains(name, "/") || strings.Contains(name, "\\") {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("profile name %q is reserved or path-like", name),
|
||||
Hint: "use letters, digits, dashes, underscores, or dots",
|
||||
}
|
||||
}
|
||||
for _, r := range name {
|
||||
switch {
|
||||
case r >= 'a' && r <= 'z',
|
||||
r >= 'A' && r <= 'Z',
|
||||
r >= '0' && r <= '9',
|
||||
r == '-' || r == '_' || r == '.':
|
||||
continue
|
||||
default:
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeInputInvalidArgument,
|
||||
Message: fmt.Sprintf("profile name %q contains invalid character %q", name, r),
|
||||
Hint: "use letters, digits, dashes, underscores, or dots",
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
func TestAdd_HappyPath(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
if err := runAdd(&AddOptions{Host: "https://my.example.com", User: "alice@example.com"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "staging"); err != nil {
|
||||
t.Fatalf("runAdd: %v", err)
|
||||
}
|
||||
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
c, ok := cfg.Contexts["staging"]
|
||||
if !ok {
|
||||
t.Fatalf("staging not in Contexts; got keys=%v", profileKeys(cfg.Contexts))
|
||||
}
|
||||
if c.Host != "https://my.example.com" {
|
||||
t.Errorf("Host=%q, want https://my.example.com", c.Host)
|
||||
}
|
||||
if c.User != "alice@example.com" {
|
||||
t.Errorf("User=%q, want alice@example.com", c.User)
|
||||
}
|
||||
// First profile auto-becomes current.
|
||||
if cfg.CurrentContext != "staging" {
|
||||
t.Errorf("first profile should auto-become current, got CurrentContext=%q", cfg.CurrentContext)
|
||||
}
|
||||
if !strings.Contains(out.String(), "staging") {
|
||||
t.Errorf("output should mention added name, got %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdd_DuplicateName(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "staging",
|
||||
Contexts: map[string]config.Context{"staging": {Host: "https://old.example.com"}},
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
err := runAdd(&AddOptions{Host: "https://new.example.com"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "staging")
|
||||
if err == nil {
|
||||
t.Fatal("expected error on duplicate name")
|
||||
}
|
||||
cm, ok := err.(*cmdutil.Error)
|
||||
if !ok {
|
||||
t.Fatalf("expected *cmdutil.Error, got %T", err)
|
||||
}
|
||||
if cm.Code != cmdutil.CodeResourceAlreadyExists {
|
||||
t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeResourceAlreadyExists)
|
||||
}
|
||||
// Existing entry must NOT be overwritten.
|
||||
got, _ := config.Load()
|
||||
if got.Contexts["staging"].Host != "https://old.example.com" {
|
||||
t.Errorf("existing profile overwritten; Host=%q", got.Contexts["staging"].Host)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdd_BadHost(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
bad := []string{
|
||||
"", // empty
|
||||
"my.example.com", // missing scheme
|
||||
"ftp://my.example.com", // wrong scheme
|
||||
"http://", // missing host
|
||||
}
|
||||
for _, h := range bad {
|
||||
err := runAdd(&AddOptions{Host: h}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "staging")
|
||||
if err == nil {
|
||||
t.Errorf("host=%q: expected error", h)
|
||||
continue
|
||||
}
|
||||
cm, ok := err.(*cmdutil.Error)
|
||||
if !ok {
|
||||
t.Errorf("host=%q: expected *cmdutil.Error, got %T", h, err)
|
||||
continue
|
||||
}
|
||||
if cm.Code != cmdutil.CodeInputInvalidArgument {
|
||||
t.Errorf("host=%q: code=%q, want %q", h, cm.Code, cmdutil.CodeInputInvalidArgument)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdd_SecondProfileDoesNotChangeCurrent(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "production",
|
||||
Contexts: map[string]config.Context{"production": {Host: "https://prod.example.com"}},
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
if err := runAdd(&AddOptions{Host: "https://stg.example.com"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "staging"); err != nil {
|
||||
t.Fatalf("runAdd: %v", err)
|
||||
}
|
||||
got, _ := config.Load()
|
||||
if got.CurrentContext != "production" {
|
||||
t.Errorf("adding a second profile must not switch current; got %q", got.CurrentContext)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAdd_JSON(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
if err := runAdd(&AddOptions{Host: "https://my.example.com"}, &cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}, "staging"); err != nil {
|
||||
t.Fatalf("runAdd: %v", err)
|
||||
}
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("invalid JSON: %v\noutput=%q", err, out.String())
|
||||
}
|
||||
got := env.Data
|
||||
if got["name"] != "staging" {
|
||||
t.Errorf("name should be staging, got %v", got)
|
||||
}
|
||||
if got["host"] != "https://my.example.com" {
|
||||
t.Errorf("host wrong: %v", got)
|
||||
}
|
||||
if got["current"] != true {
|
||||
t.Errorf("first added profile must be current=true, got %v", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
"text/tabwriter"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/output"
|
||||
)
|
||||
|
||||
type ListOptions struct{}
|
||||
|
||||
// profileListFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `profile list`. Each entry is a per-profile summary row.
|
||||
var profileListFields = []string{
|
||||
"name", "host", "user", "current",
|
||||
}
|
||||
|
||||
type listEntry struct {
|
||||
Name string `json:"name"`
|
||||
Host string `json:"host"`
|
||||
User string `json:"user,omitempty"`
|
||||
Current bool `json:"current"`
|
||||
}
|
||||
|
||||
// NewCmdList builds `weknora profile list`. Per-host enumeration with an
|
||||
// active marker. Reads only config.yaml - no network, no keyring touch.
|
||||
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List configured profiles",
|
||||
Long: `Show every profile registered in ~/.config/weknora/config.yaml. The
|
||||
active profile (used by subsequent commands when --profile is unset) is
|
||||
marked with a leading "*". No network requests are issued.
|
||||
|
||||
The credential mode (api-key vs password) is intentionally not shown here -
|
||||
run "weknora auth list" for that. "profile list" is the catalog of *where*
|
||||
the CLI can talk to; "auth list" is the catalog of *how*.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
return runList(fopts)
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, profileListFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runList(fopts *cmdutil.FormatOptions) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
entries := make([]listEntry, 0, len(cfg.Contexts))
|
||||
for name, c := range cfg.Contexts {
|
||||
entries = append(entries, listEntry{
|
||||
Name: name,
|
||||
Host: c.Host,
|
||||
User: c.User,
|
||||
Current: name == cfg.CurrentContext,
|
||||
})
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
|
||||
|
||||
if fopts.WantsJSON() {
|
||||
meta := &output.Meta{Count: len(entries)}
|
||||
return fopts.Emit(iostreams.IO.Out, entries, meta)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "No profiles configured. Run `weknora auth login` (or `weknora profile add`) to create one.")
|
||||
return nil
|
||||
}
|
||||
tw := tabwriter.NewWriter(iostreams.IO.Out, 0, 0, 2, ' ', 0)
|
||||
fmt.Fprintln(tw, " NAME\tHOST\tUSER")
|
||||
for _, e := range entries {
|
||||
marker := " "
|
||||
if e.Current {
|
||||
marker = "* "
|
||||
}
|
||||
fmt.Fprintf(tw, "%s%s\t%s\t%s\n", marker, e.Name, e.Host, format.DashIfEmpty(e.User))
|
||||
}
|
||||
return tw.Flush()
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
func TestList_Empty(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
if err := runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "No profiles") {
|
||||
t.Errorf("empty output should mention `No profiles`, got %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_MultipleSorted(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "staging",
|
||||
Contexts: map[string]config.Context{
|
||||
"production": {Host: "https://prod.example.com", User: "alice@example.com"},
|
||||
"staging": {Host: "https://staging.example.com"},
|
||||
"alpha": {Host: "https://alpha.example.com"},
|
||||
},
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
if err := runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
// header
|
||||
if !strings.Contains(got, "NAME") || !strings.Contains(got, "HOST") {
|
||||
t.Errorf("missing header NAME/HOST in %q", got)
|
||||
}
|
||||
// row ordering: alpha < production < staging
|
||||
iAlpha := strings.Index(got, "alpha")
|
||||
iProd := strings.Index(got, "production")
|
||||
iStg := strings.Index(got, "staging")
|
||||
if !(iAlpha < iProd && iProd < iStg) {
|
||||
t.Errorf("rows must be alphabetical, got order alpha=%d prod=%d staging=%d in %q", iAlpha, iProd, iStg, got)
|
||||
}
|
||||
// active marker on staging row
|
||||
stgLine := lineContaining(got, "staging")
|
||||
if !strings.HasPrefix(stgLine, "*") {
|
||||
t.Errorf("active profile row must start with `*`, got %q", stgLine)
|
||||
}
|
||||
}
|
||||
|
||||
func TestList_JSON(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "staging",
|
||||
Contexts: map[string]config.Context{
|
||||
"staging": {Host: "https://staging.example.com", User: "bob@example.com"},
|
||||
"production": {Host: "https://prod.example.com"},
|
||||
},
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
if err := runList(&cmdutil.FormatOptions{Mode: cmdutil.FormatJSON}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
|
||||
var env struct {
|
||||
OK bool `json:"ok"`
|
||||
Data []map[string]any `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("invalid JSON: %v\noutput=%q", err, out.String())
|
||||
}
|
||||
rows := env.Data
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("expected 2 entries, got %d", len(rows))
|
||||
}
|
||||
// alphabetical: production before staging
|
||||
if rows[0]["name"] != "production" {
|
||||
t.Errorf("first row should be production, got %v", rows[0])
|
||||
}
|
||||
if rows[1]["name"] != "staging" || rows[1]["current"] != true {
|
||||
t.Errorf("second row should be staging with current=true, got %v", rows[1])
|
||||
}
|
||||
}
|
||||
|
||||
// lineContaining returns the first line of s that contains needle (trimmed of
|
||||
// the trailing newline) or "" if no line matches.
|
||||
func lineContaining(s, needle string) string {
|
||||
for l := range strings.SplitSeq(s, "\n") {
|
||||
if strings.Contains(l, needle) {
|
||||
return l
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Package profilecmd holds the `weknora profile` command tree
|
||||
// (list / add / remove / use).
|
||||
//
|
||||
// Package name `profilecmd` (not `profile`) to keep the pattern consistent
|
||||
// with other cmd subpackages.
|
||||
// The cobra Use: string is "profile" - this is what users type.
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
)
|
||||
|
||||
// NewCmd builds the `weknora profile` parent command.
|
||||
func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "profile",
|
||||
Short: "Manage CLI profiles (named connection targets)",
|
||||
}
|
||||
cmd.AddCommand(NewCmdList(f))
|
||||
cmd.AddCommand(NewCmdAdd(f))
|
||||
cmd.AddCommand(NewCmdRemove(f))
|
||||
cmd.AddCommand(NewCmdUse(f))
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"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"
|
||||
)
|
||||
|
||||
type RemoveOptions struct {
|
||||
Yes bool // sourced from the global -y/--yes persistent flag (matches `kb delete`)
|
||||
}
|
||||
|
||||
// profileRemoveFields enumerates the fields surfaced for `--format json` discovery on
|
||||
// `profile remove`. The result reports the disposition of the removed entry.
|
||||
var profileRemoveFields = []string{
|
||||
"name", "removed", "was_current",
|
||||
}
|
||||
|
||||
// removeResult is the typed payload emitted under data on success.
|
||||
type removeResult struct {
|
||||
Name string `json:"name"`
|
||||
Removed bool `json:"removed"`
|
||||
WasCurrent bool `json:"was_current"`
|
||||
}
|
||||
|
||||
// NewCmdRemove builds `weknora profile remove`. Drops the entry from
|
||||
// config.yaml and best-effort clears keyring references. Removing a
|
||||
// non-current profile is low-friction (no prompt). Removing the *current*
|
||||
// profile triggers the destructive-write confirmation protocol (exit 10),
|
||||
// because subsequent commands will have no default connection target.
|
||||
func NewCmdRemove(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &RemoveOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "remove <name>",
|
||||
Short: "Remove a profile (drops entry, clears keyring refs)",
|
||||
Long: `Deletes the named profile from config.yaml and best-effort clears any
|
||||
keyring references it owned (matches ` + "`weknora auth logout`" + `).
|
||||
|
||||
Removing the current profile also clears CurrentContext - subsequent commands
|
||||
will error until you select another with ` + "`weknora profile use <name>`" + ` or pick
|
||||
one up via the global ` + "`--profile`" + ` flag. Because that change is observable in
|
||||
every later command, removing the current profile requires explicit -y/--yes
|
||||
in scripted / --format json invocations (exit code 10; see cli/README.md).`,
|
||||
Example: ` weknora profile remove staging # remove non-current → no prompt
|
||||
weknora profile remove production -y # remove current → confirm`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
store, err := f.Secrets()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runRemove(opts, fopts, args[0], store, f.Prompter())
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, profileRemoveFields...)
|
||||
cmdutil.SetAgentHelp(cmd, cmdutil.AgentHelp{
|
||||
UsedFor: "remove a named profile and its stored credentials",
|
||||
RequiredFlags: []string{"<name> (positional)"},
|
||||
Examples: []string{
|
||||
"weknora profile remove staging",
|
||||
"weknora profile remove production -y",
|
||||
},
|
||||
Warnings: []string{
|
||||
"profile remove drops the named profile and its stored credentials. Never auto-add -y.",
|
||||
},
|
||||
})
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runRemove(opts *RemoveOptions, fopts *cmdutil.FormatOptions, name string, store secrets.Store, p prompt.Prompter) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, exists := cfg.Contexts[name]
|
||||
if !exists {
|
||||
return notFoundError(name, cfg)
|
||||
}
|
||||
wasCurrent := name == cfg.CurrentContext
|
||||
|
||||
jsonOut := fopts.WantsJSON()
|
||||
// Confirmation only fires for removing the current profile - non-current
|
||||
// remove uses the same low-friction policy as `auth logout`.
|
||||
if wasCurrent {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "current profile", name, "profile.remove", fmt.Sprintf("weknora profile remove %s -y", name)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Config first, secrets after: a crash in between leaves an orphan
|
||||
// keyring entry but no dangling config ref (same ordering as auth logout).
|
||||
delete(cfg.Contexts, name)
|
||||
if wasCurrent {
|
||||
cfg.CurrentContext = ""
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
|
||||
}
|
||||
clearProfileSecrets(store, ctx, name)
|
||||
|
||||
result := removeResult{Name: name, Removed: true, WasCurrent: wasCurrent}
|
||||
if jsonOut {
|
||||
return fopts.Emit(iostreams.IO.Out, result, nil)
|
||||
}
|
||||
if wasCurrent {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Removed profile %s (current profile cleared - run `weknora profile use <name>` to pick another)\n", name)
|
||||
} else {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Removed profile %s\n", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// clearProfileSecrets mirrors auth/logout.go: best-effort delete every secret
|
||||
// slot the profile references. Errors are swallowed so a missing keyring
|
||||
// entry doesn't block remove (same policy as `auth logout`).
|
||||
func clearProfileSecrets(store secrets.Store, c config.Context, name string) {
|
||||
if c.TokenRef != "" {
|
||||
_ = store.Delete(name, "access")
|
||||
}
|
||||
if c.RefreshRef != "" {
|
||||
_ = store.Delete(name, "refresh")
|
||||
}
|
||||
if c.APIKeyRef != "" {
|
||||
_ = store.Delete(name, "api_key")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
||||
"github.com/Tencent/WeKnora/cli/internal/testutil"
|
||||
)
|
||||
|
||||
// seedStore returns a MemStore pre-loaded with sentinel values for every
|
||||
// secret slot a profile might reference. Tests assert deletion by checking
|
||||
// `secrets.ErrNotFound` post-runRemove.
|
||||
func seedStore(t *testing.T, name string, slots ...string) *secrets.MemStore {
|
||||
t.Helper()
|
||||
s := secrets.NewMemStore()
|
||||
for _, slot := range slots {
|
||||
if err := s.Set(name, slot, "sentinel-"+name+"-"+slot); err != nil {
|
||||
t.Fatalf("seed %s/%s: %v", name, slot, err)
|
||||
}
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
func assertDeleted(t *testing.T, s *secrets.MemStore, name, slot string) {
|
||||
t.Helper()
|
||||
if _, err := s.Get(name, slot); !errors.Is(err, secrets.ErrNotFound) {
|
||||
t.Errorf("expected %s/%s removed, got err=%v", name, slot, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemove_NonCurrent_NoPromptNeeded(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "production",
|
||||
Contexts: map[string]config.Context{
|
||||
"production": {Host: "https://prod.example.com", TokenRef: "mem://production/access"},
|
||||
"staging": {Host: "https://staging.example.com", APIKeyRef: "mem://staging/api_key"},
|
||||
},
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
store := seedStore(t, "staging", "api_key")
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
if err := runRemove(&RemoveOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "staging", store, p); err != nil {
|
||||
t.Fatalf("runRemove: %v", err)
|
||||
}
|
||||
if p.Asked {
|
||||
t.Errorf("non-current remove must not prompt")
|
||||
}
|
||||
|
||||
got, _ := config.Load()
|
||||
if _, exists := got.Contexts["staging"]; exists {
|
||||
t.Errorf("staging should have been removed; Contexts=%v", got.Contexts)
|
||||
}
|
||||
if got.CurrentContext != "production" {
|
||||
t.Errorf("CurrentContext must be unchanged, got %q", got.CurrentContext)
|
||||
}
|
||||
assertDeleted(t, store, "staging", "api_key")
|
||||
if !strings.Contains(out.String(), "staging") {
|
||||
t.Errorf("output should mention removed profile, got %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemove_NotFound_WithDidYouMean(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{Contexts: map[string]config.Context{
|
||||
"production": {Host: "https://prod"},
|
||||
"staging": {Host: "https://staging"},
|
||||
}}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
err := runRemove(&RemoveOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "prodution", secrets.NewMemStore(), &testutil.ConfirmPrompter{})
|
||||
if err == nil {
|
||||
t.Fatal("expected not-found error")
|
||||
}
|
||||
cm, ok := err.(*cmdutil.Error)
|
||||
if !ok {
|
||||
t.Fatalf("expected *cmdutil.Error, got %T", err)
|
||||
}
|
||||
if cm.Code != cmdutil.CodeLocalProfileNotFound {
|
||||
t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeLocalProfileNotFound)
|
||||
}
|
||||
if !strings.Contains(cm.Hint, "production") {
|
||||
t.Errorf("hint should suggest 'production', got %q", cm.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemove_Current_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "production",
|
||||
Contexts: map[string]config.Context{
|
||||
"production": {Host: "https://prod", TokenRef: "mem://production/access"},
|
||||
"staging": {Host: "https://staging"},
|
||||
},
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
store := seedStore(t, "production", "access")
|
||||
err := runRemove(&RemoveOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "production", store, &testutil.ConfirmPrompter{})
|
||||
if err == nil {
|
||||
t.Fatal("expected confirmation-required error")
|
||||
}
|
||||
cm, ok := err.(*cmdutil.Error)
|
||||
if !ok {
|
||||
t.Fatalf("expected *cmdutil.Error, got %T", err)
|
||||
}
|
||||
if cm.Code != cmdutil.CodeInputConfirmationRequired {
|
||||
t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeInputConfirmationRequired)
|
||||
}
|
||||
if cmdutil.ExitCode(err) != 10 {
|
||||
t.Errorf("expected exit-10, got %d", cmdutil.ExitCode(err))
|
||||
}
|
||||
// Must not have mutated config or keyring.
|
||||
if got, _ := config.Load(); got.CurrentContext != "production" {
|
||||
t.Errorf("config mutated despite confirmation gate: CurrentContext=%q", got.CurrentContext)
|
||||
}
|
||||
if v, err := store.Get("production", "access"); err != nil || v == "" {
|
||||
t.Errorf("keyring touched before confirmation, get=%q err=%v", v, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemove_Current_WithYes_ClearsCurrent(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "production",
|
||||
Contexts: map[string]config.Context{
|
||||
"production": {Host: "https://prod", TokenRef: "mem://production/access"},
|
||||
"staging": {Host: "https://staging"},
|
||||
},
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
store := seedStore(t, "production", "access")
|
||||
if err := runRemove(&RemoveOptions{Yes: true}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "production", store, &testutil.ConfirmPrompter{}); err != nil {
|
||||
t.Fatalf("runRemove: %v", err)
|
||||
}
|
||||
got, _ := config.Load()
|
||||
if _, exists := got.Contexts["production"]; exists {
|
||||
t.Errorf("production should be removed")
|
||||
}
|
||||
if got.CurrentContext != "" {
|
||||
t.Errorf("removing current must clear CurrentContext, got %q", got.CurrentContext)
|
||||
}
|
||||
assertDeleted(t, store, "production", "access")
|
||||
if !strings.Contains(out.String(), "current profile cleared") {
|
||||
t.Errorf("output should warn about cleared current, got %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemove_Current_TTY_PromptNo(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, errBuf := iostreams.SetForTestWithTTY(t)
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "production",
|
||||
Contexts: map[string]config.Context{"production": {Host: "https://prod"}},
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runRemove(&RemoveOptions{}, &cmdutil.FormatOptions{Mode: cmdutil.FormatText}, "production", secrets.NewMemStore(), p)
|
||||
if err == nil {
|
||||
t.Fatal("expected user-aborted error")
|
||||
}
|
||||
cm, ok := err.(*cmdutil.Error)
|
||||
if !ok {
|
||||
t.Fatalf("expected *cmdutil.Error, got %T", err)
|
||||
}
|
||||
if cm.Code != cmdutil.CodeUserAborted {
|
||||
t.Errorf("code=%q, want %q", cm.Code, cmdutil.CodeUserAborted)
|
||||
}
|
||||
if !p.Asked {
|
||||
t.Errorf("prompt should have been asked on TTY")
|
||||
}
|
||||
if !strings.Contains(errBuf.String(), "Aborted") {
|
||||
t.Errorf("stderr should contain Aborted, got %q", errBuf.String())
|
||||
}
|
||||
if got, _ := config.Load(); got.CurrentContext != "production" {
|
||||
t.Errorf("aborted remove must not mutate config")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sort"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
// profileUseFields enumerates fields surfaced for `--format json` discovery on
|
||||
// `profile use`.
|
||||
var profileUseFields = []string{"current_profile", "previous_profile"}
|
||||
|
||||
// NewCmdUse builds the `weknora profile use <name>` command.
|
||||
func NewCmdUse(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "use <name>",
|
||||
Short: "Switch the default profile for subsequent commands",
|
||||
Long: `Switches the default profile written in config.yaml. Names are case-sensitive.
|
||||
|
||||
The active profile is what every subsequent command uses for auth + host. The
|
||||
global --profile flag (e.g. weknora --profile staging kb list) overrides for
|
||||
one command without writing to disk.
|
||||
|
||||
AI agents: Do NOT switch the active profile unless the user explicitly asked
|
||||
you to. Profile selection is a user preference; one-shot overrides should use
|
||||
the global --profile flag instead, which writes nothing to disk.`,
|
||||
Example: ` weknora profile use staging # persist switch
|
||||
weknora --profile staging kb list # one-shot override (no disk write)
|
||||
weknora profile use staging --format json # {current_profile, previous_profile}`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
fopts, err := cmdutil.CheckFormatFlag(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
fopts.ResolveDefault(iostreams.IO.IsStdoutTTY())
|
||||
return runUse(args[0], fopts)
|
||||
},
|
||||
}
|
||||
cmdutil.AddFormatFlag(cmd, profileUseFields...)
|
||||
return cmd
|
||||
}
|
||||
|
||||
type useResult struct {
|
||||
CurrentProfile string `json:"current_profile"`
|
||||
PreviousProfile string `json:"previous_profile,omitempty"`
|
||||
}
|
||||
|
||||
func runUse(name string, fopts *cmdutil.FormatOptions) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, ok := cfg.Contexts[name]; !ok {
|
||||
return notFoundError(name, cfg)
|
||||
}
|
||||
prev := cfg.CurrentContext
|
||||
cfg.CurrentContext = name
|
||||
if err := config.Save(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
result := useResult{CurrentProfile: name, PreviousProfile: prev}
|
||||
if fopts.WantsJSON() {
|
||||
return fopts.Emit(iostreams.IO.Out, result, nil)
|
||||
}
|
||||
if prev != "" && prev != name {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Switched profile to %s (was %s)\n", name, prev)
|
||||
} else {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Active profile: %s\n", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func notFoundError(name string, cfg *config.Config) error {
|
||||
if len(cfg.Contexts) == 0 {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeLocalProfileNotFound,
|
||||
Message: fmt.Sprintf("profile not found: %s", name),
|
||||
Hint: "no profiles registered - run `weknora auth login` first",
|
||||
}
|
||||
}
|
||||
keys := profileKeys(cfg.Contexts)
|
||||
candidate := closestMatch(name, keys)
|
||||
var hint string
|
||||
if candidate != "" && candidate != name {
|
||||
hint = fmt.Sprintf("did you mean: %q?", candidate)
|
||||
} else {
|
||||
hint = fmt.Sprintf("available profiles: %v", keys)
|
||||
}
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeLocalProfileNotFound,
|
||||
Message: fmt.Sprintf("profile not found: %s", name),
|
||||
Hint: hint,
|
||||
}
|
||||
}
|
||||
|
||||
func profileKeys(m map[string]config.Context) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// closestMatch returns the candidate with min levenshtein distance ≤ 2,
|
||||
// or "" if none qualifies. Ties broken by lexicographic order so the hint
|
||||
// is deterministic across map-iteration orderings (Go randomizes range over
|
||||
// map; without this, did-you-mean output is flaky for equally-close
|
||||
// candidates).
|
||||
func closestMatch(target string, candidates []string) string {
|
||||
sorted := append([]string(nil), candidates...)
|
||||
sort.Strings(sorted)
|
||||
best := ""
|
||||
bestD := 3
|
||||
for _, c := range sorted {
|
||||
d := levenshtein(target, c)
|
||||
if d < bestD {
|
||||
bestD = d
|
||||
best = c
|
||||
}
|
||||
}
|
||||
if bestD > 2 {
|
||||
return ""
|
||||
}
|
||||
return best
|
||||
}
|
||||
|
||||
func levenshtein(a, b string) int {
|
||||
la, lb := len(a), len(b)
|
||||
if la == 0 {
|
||||
return lb
|
||||
}
|
||||
if lb == 0 {
|
||||
return la
|
||||
}
|
||||
prev := make([]int, lb+1)
|
||||
curr := make([]int, lb+1)
|
||||
for j := 0; j <= lb; j++ {
|
||||
prev[j] = j
|
||||
}
|
||||
for i := 1; i <= la; i++ {
|
||||
curr[0] = i
|
||||
for j := 1; j <= lb; j++ {
|
||||
cost := 1
|
||||
if a[i-1] == b[j-1] {
|
||||
cost = 0
|
||||
}
|
||||
curr[j] = min(curr[j-1]+1, prev[j]+1, prev[j-1]+cost)
|
||||
}
|
||||
prev, curr = curr, prev
|
||||
}
|
||||
return prev[lb]
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package profilecmd
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
func TestUse_OK(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "staging",
|
||||
Contexts: map[string]config.Context{
|
||||
"staging": {Host: "https://staging.example.com"},
|
||||
"production": {Host: "https://prod.example.com"},
|
||||
},
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save initial config: %v", err)
|
||||
}
|
||||
|
||||
if err := runUse("production", &cmdutil.FormatOptions{Mode: cmdutil.FormatText}); err != nil {
|
||||
t.Fatalf("runUse: %v", err)
|
||||
}
|
||||
|
||||
got, err := config.Load()
|
||||
if err != nil {
|
||||
t.Fatalf("reload: %v", err)
|
||||
}
|
||||
if got.CurrentContext != "production" {
|
||||
t.Errorf("CurrentContext = %q, want production", got.CurrentContext)
|
||||
}
|
||||
if !strings.Contains(out.String(), "production") {
|
||||
t.Errorf("output should mention switched-to profile, got %q", out.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUse_NotFound_WithDidYouMean(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{Contexts: map[string]config.Context{
|
||||
"production": {Host: "https://prod"},
|
||||
"staging": {Host: "https://staging"},
|
||||
}}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
err := runUse("prodution", &cmdutil.FormatOptions{Mode: cmdutil.FormatText}) // typo: missing 'c'
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
cm, ok := err.(*cmdutil.Error)
|
||||
if !ok {
|
||||
t.Fatalf("expected *cmdutil.Error, got %T", err)
|
||||
}
|
||||
if cm.Code != cmdutil.CodeLocalProfileNotFound {
|
||||
t.Errorf("code = %q, want %q", cm.Code, cmdutil.CodeLocalProfileNotFound)
|
||||
}
|
||||
if cm.Hint != `did you mean: "production"?` {
|
||||
t.Errorf("hint should be exact `did you mean: \"production\"?`, got %q", cm.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
// TestUse_NotFound_DeterministicTieBreak guards against map-iteration-order
|
||||
// flake: when two candidates have equal levenshtein distance, the suggestion
|
||||
// must be reproducibly the lexicographically-smaller one.
|
||||
func TestUse_NotFound_DeterministicTieBreak(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
cfg := &config.Config{Contexts: map[string]config.Context{
|
||||
"prod": {Host: "https://a"},
|
||||
"prom": {Host: "https://b"},
|
||||
"prog": {Host: "https://c"},
|
||||
}}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
// "prox" is distance 1 from prod / prom (both win); lex tie-break → prod.
|
||||
for i := 0; i < 5; i++ {
|
||||
err := runUse("prox", &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
if err == nil {
|
||||
t.Fatalf("iter %d: expected error", i)
|
||||
}
|
||||
cm := err.(*cmdutil.Error)
|
||||
if cm.Hint != `did you mean: "prod"?` {
|
||||
t.Fatalf("iter %d: tie-break must pick lex-smallest 'prod', got %q", i, cm.Hint)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestUse_NotFound_EmptyProfiles(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
err := runUse("anything", &cmdutil.FormatOptions{Mode: cmdutil.FormatText})
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
cm := err.(*cmdutil.Error)
|
||||
if !strings.Contains(cm.Hint, "auth login") {
|
||||
t.Errorf("hint should mention `auth login` for empty profiles, got %q", cm.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUse_CaseSensitive(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{Contexts: map[string]config.Context{
|
||||
"Production": {Host: "https://prod"},
|
||||
}}
|
||||
_ = config.Save(cfg)
|
||||
|
||||
err := runUse("production", &cmdutil.FormatOptions{Mode: cmdutil.FormatText}) // lowercase - must NOT match "Production"
|
||||
if err == nil {
|
||||
t.Fatal("expected case-sensitive miss")
|
||||
}
|
||||
cm := err.(*cmdutil.Error)
|
||||
// did-you-mean kicks in (distance 1 - "P"→"p")
|
||||
if !strings.Contains(cm.Hint, "Production") {
|
||||
t.Errorf("hint should suggest 'Production' (case-different), got %q", cm.Hint)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user