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,77 @@
|
||||
// Package whoami implements `weknora whoami` — a top-level standalone leaf,
|
||||
// the simplified counterpart of `auth status` that prints only user_id and
|
||||
// tenant_id (spec §1.2). Use `auth status` for full diagnostics.
|
||||
package whoami
|
||||
|
||||
import (
|
||||
"context"
|
||||
"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/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
// Options captures the (sparse) configuration of `weknora whoami`.
|
||||
type Options struct {
|
||||
JSONOut bool
|
||||
}
|
||||
|
||||
// Service is the narrow SDK surface this command depends on.
|
||||
type Service interface {
|
||||
GetCurrentUser(ctx context.Context) (*sdk.CurrentUserResponse, error)
|
||||
}
|
||||
|
||||
// result is the typed payload emitted by `--json`.
|
||||
type result struct {
|
||||
UserID string `json:"user_id"`
|
||||
TenantID uint64 `json:"tenant_id,omitempty"`
|
||||
}
|
||||
|
||||
// NewCmd builds the `weknora whoami` command.
|
||||
func NewCmd(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &Options{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "whoami",
|
||||
Short: "Print user_id and tenant_id of the active context",
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runWhoami(c.Context(), opts, cli)
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
agent.SetAgentHelp(cmd, "Returns the active context principal as JSON envelope. Quick identity check; for full diagnostics use `weknora auth status`.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runWhoami(ctx context.Context, opts *Options, svc Service) error {
|
||||
if svc == nil {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "no SDK client available; run `weknora auth login`")
|
||||
}
|
||||
resp, err := svc.GetCurrentUser(ctx)
|
||||
if err != nil {
|
||||
return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "fetch current user")
|
||||
}
|
||||
if resp == nil || resp.Data.User == nil {
|
||||
return cmdutil.NewError(cmdutil.CodeAuthUnauthenticated, "server returned empty user; run `weknora auth login`")
|
||||
}
|
||||
r := result{UserID: resp.Data.User.ID}
|
||||
if resp.Data.Tenant != nil {
|
||||
r.TenantID = resp.Data.Tenant.ID
|
||||
}
|
||||
if opts.JSONOut {
|
||||
return cmdutil.NewJSONExporter().Write(iostreams.IO.Out, format.Success(r, nil))
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "user_id: %s\n", r.UserID)
|
||||
if r.TenantID != 0 {
|
||||
fmt.Fprintf(iostreams.IO.Out, "tenant_id: %d\n", r.TenantID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package whoami
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
|
||||
type fakeSvc struct {
|
||||
resp *sdk.CurrentUserResponse
|
||||
err error
|
||||
}
|
||||
|
||||
func (f *fakeSvc) GetCurrentUser(_ context.Context) (*sdk.CurrentUserResponse, error) {
|
||||
return f.resp, f.err
|
||||
}
|
||||
|
||||
func newRespOK() *sdk.CurrentUserResponse {
|
||||
r := &sdk.CurrentUserResponse{}
|
||||
r.Data.User = &sdk.AuthUser{ID: "usr_abc"}
|
||||
r.Data.Tenant = &sdk.AuthTenant{ID: 42}
|
||||
return r
|
||||
}
|
||||
|
||||
func TestWhoami_Human(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeSvc{resp: newRespOK()}
|
||||
if err := runWhoami(context.Background(), &Options{}, svc); err != nil {
|
||||
t.Fatalf("runWhoami: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
if !strings.Contains(got, "user_id:") || !strings.Contains(got, "usr_abc") {
|
||||
t.Errorf("expected user_id: usr_abc in %q", got)
|
||||
}
|
||||
if !strings.Contains(got, "tenant_id:") || !strings.Contains(got, "42") {
|
||||
t.Errorf("expected tenant_id: 42 in %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhoami_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeSvc{resp: newRespOK()}
|
||||
if err := runWhoami(context.Background(), &Options{JSONOut: true}, svc); err != nil {
|
||||
t.Fatalf("runWhoami: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
if !strings.Contains(got, `"ok":true`) {
|
||||
t.Errorf("expected ok:true in %q", got)
|
||||
}
|
||||
if !strings.Contains(got, `"user_id":"usr_abc"`) {
|
||||
t.Errorf("expected user_id field in %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhoami_Unauthenticated(t *testing.T) {
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeSvc{err: errors.New("HTTP error 401: unauthenticated")}
|
||||
err := runWhoami(context.Background(), &Options{}, svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
if !cmdutil.IsAuthError(err) {
|
||||
t.Errorf("expected auth error, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWhoami_NilUser(t *testing.T) {
|
||||
// SDK could return success but without user pointer (server bug or partial response)
|
||||
_, _ = iostreams.SetForTest(t)
|
||||
svc := &fakeSvc{resp: &sdk.CurrentUserResponse{}} // Data.User == nil
|
||||
err := runWhoami(context.Background(), &Options{}, svc)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nil user")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user