feat(cli): add whoami / doctor / kb / context commands (PR-7)
5 new leaf commands wired into the root tree:
whoami — simplified `auth status` (user_id + tenant_id only)
doctor — 4-item self-check (base_url / auth / server_version / cred_storage)
with --offline / --no-cache flags + skip cascade + summary.all_passed
防 agent 看到 envelope.ok=true 误判命令整体 success
kb list — list KBs (default updated_at desc; 0 KB → "(no knowledge bases)")
tabwriter 4-col (ID/NAME/DOCS/UPDATED), display-width truncation
kb get — show single KB details (KEY: VALUE, suppress empty fields)
context use — switch default context (writes config.current_context),
带 levenshtein distance ≤ 2 的 did-you-mean hint
Each command uses the v0.0 narrow Service interface pattern (testable via
fakes), agent.SetAgentHelp for AI-friendly hints, and ClassifyHTTPError
for stable error code mapping.
cmdutil/errors.go: 新增 CodeLocalContextNotFound for `context use`,加入 AllCodes() 注册集.
cli/cmd/root.go: NewRootCmd 改为 exported (acceptance/contract 测试需要),
注册 4 个新命令 + 1 parent group; root_test.go 跟随更新.
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
// Package contextcmd holds `weknora context` command tree (use; list / set /
|
||||
// delete in v0.4).
|
||||
//
|
||||
// Package name `contextcmd` (not `context`) to avoid shadowing stdlib context.
|
||||
// The cobra Use: string is "context" — this is what users type.
|
||||
package contextcmd
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
)
|
||||
|
||||
// NewCmd builds the `weknora context` parent command.
|
||||
func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "context",
|
||||
Short: "Manage CLI contexts (named connection targets)",
|
||||
Args: cobra.NoArgs,
|
||||
Run: func(c *cobra.Command, _ []string) { _ = c.Help() },
|
||||
}
|
||||
cmd.AddCommand(NewCmdUse(f))
|
||||
return cmd
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
package contextcmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/agent"
|
||||
"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"
|
||||
)
|
||||
|
||||
// NewCmdUse builds the `weknora context use <name>` command.
|
||||
func NewCmdUse(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "use <name>",
|
||||
Short: "Switch the default context for subsequent commands",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
return runUse(args[0])
|
||||
},
|
||||
}
|
||||
agent.SetAgentHelp(cmd, "Switches default CLI context. Returns previous_context + current_context. Errors with hint when name unknown.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
type useResult struct {
|
||||
CurrentContext string `json:"current_context"`
|
||||
PreviousContext string `json:"previous_context,omitempty"`
|
||||
}
|
||||
|
||||
func runUse(name string) 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
|
||||
}
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.Success(useResult{
|
||||
CurrentContext: name,
|
||||
PreviousContext: prev,
|
||||
}, nil))
|
||||
}
|
||||
|
||||
func notFoundError(name string, cfg *config.Config) error {
|
||||
if len(cfg.Contexts) == 0 {
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeLocalContextNotFound,
|
||||
Message: fmt.Sprintf("context not found: %s", name),
|
||||
Hint: "no contexts registered — run `weknora auth login` first",
|
||||
}
|
||||
}
|
||||
candidate := closestMatch(name, contextKeys(cfg.Contexts))
|
||||
hint := availableHint(cfg)
|
||||
if candidate != "" && candidate != name {
|
||||
hint = fmt.Sprintf("did you mean: %q?", candidate)
|
||||
}
|
||||
return &cmdutil.Error{
|
||||
Code: cmdutil.CodeLocalContextNotFound,
|
||||
Message: fmt.Sprintf("context not found: %s", name),
|
||||
Hint: hint,
|
||||
}
|
||||
}
|
||||
|
||||
func contextKeys(m map[string]config.Context) []string {
|
||||
out := make([]string, 0, len(m))
|
||||
for k := range m {
|
||||
out = append(out, k)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func availableHint(cfg *config.Config) string {
|
||||
return fmt.Sprintf("available contexts: %v", contextKeys(cfg.Contexts))
|
||||
}
|
||||
|
||||
// closestMatch returns the candidate with min levenshtein distance ≤ 2,
|
||||
// or "" if none qualifies.
|
||||
func closestMatch(target string, candidates []string) string {
|
||||
best := ""
|
||||
bestD := 3
|
||||
for _, c := range candidates {
|
||||
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,103 @@
|
||||
package contextcmd
|
||||
|
||||
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"); 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 context, 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") // 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.CodeLocalContextNotFound {
|
||||
t.Errorf("code = %q, want %q", cm.Code, cmdutil.CodeLocalContextNotFound)
|
||||
}
|
||||
if !strings.Contains(cm.Hint, "production") {
|
||||
t.Errorf("hint should suggest 'production', got %q", cm.Hint)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUse_NotFound_EmptyContexts(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
|
||||
err := runUse("anything")
|
||||
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 Contexts, 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") // 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