chore(cli): gofmt sweep

`gofmt -w cli/` — trailing newlines, minor whitespace alignment. Caught
during PR-readiness review (`gofmt -l .` had been non-clean since the
em-dash → ASCII bulk replace earlier in the v0.4 series).
This commit is contained in:
nullkey
2026-05-15 05:00:26 +08:00
committed by lyingbug
parent f2e8e3f56c
commit 69fbbfc252
30 changed files with 74 additions and 84 deletions
+3 -1
View File
@@ -33,7 +33,9 @@ func TestMain(m *testing.M) {
} }
// update is the standard Go test golden-update flag. // update is the standard Go test golden-update flag.
// go test -update ./acceptance/contract/... //
// go test -update ./acceptance/contract/...
//
// Mirrors gh / kubectl / golang-migrate convention. // Mirrors gh / kubectl / golang-migrate convention.
var update = flag.Bool("update", false, "update golden files") var update = flag.Bool("update", false, "update golden files")
+21 -20
View File
@@ -13,18 +13,18 @@
// //
// Cases intentionally omitted (with reason): // Cases intentionally omitted (with reason):
// - doctor.success - non-offline path emits // - doctor.success - non-offline path emits
// unstable timing // unstable timing
// ("reachable in 2ms"). // ("reachable in 2ms").
// Unit tests in cli/cmd/doctor // Unit tests in cli/cmd/doctor
// cover the all-pass shape; // cover the all-pass shape;
// doctor.success_offline is // doctor.success_offline is
// the deterministic sibling // the deterministic sibling
// kept here. // kept here.
// - auth_login.success - requires stdin pipe // - auth_login.success - requires stdin pipe
// (--with-token) + keyring- // (--with-token) + keyring-
// aware Secrets store; the // aware Secrets store; the
// helper does not yet expose // helper does not yet expose
// a stdin hook. // a stdin hook.
// - auth_login.error_auth_unauthenticated - same setup as above. // - auth_login.error_auth_unauthenticated - same setup as above.
// //
// All cases use leaf-positioned --json (e.g. `version --json`). --json is a // All cases use leaf-positioned --json (e.g. `version --json`). --json is a
@@ -45,15 +45,16 @@ import (
) )
// wireCase declares one row in the contract matrix. Optional fields: // wireCase declares one row in the contract matrix. Optional fields:
// server - mock /api/v1/* endpoints; nil means no network. //
// preConfig - seed config.yaml under the per-test XDG_CONFIG_HOME // server - mock /api/v1/* endpoints; nil means no network.
// (set by newTestFactory); use for cases like // preConfig - seed config.yaml under the per-test XDG_CONFIG_HOME
// `context use` that read local state without an // (set by newTestFactory); use for cases like
// SDK round-trip. // `context use` that read local state without an
// wantErr - non-zero exit expected. // SDK round-trip.
// wantStderrSubstring - stderr must contain this substring (typically the // wantErr - non-zero exit expected.
// typed error code, e.g. "auth.unauthenticated"). // wantStderrSubstring - stderr must contain this substring (typically the
// Only meaningful when wantErr=true. // typed error code, e.g. "auth.unauthenticated").
// Only meaningful when wantErr=true.
type wireCase struct { type wireCase struct {
name string name string
args []string args []string
+3 -2
View File
@@ -5,6 +5,7 @@
// reviewer immediately sees "this is the contract surface - change with care". // reviewer immediately sees "this is the contract surface - change with care".
// //
// Sub-packages: // Sub-packages:
// contract/ - envelope JSON shape golden + error.code registry consistency //
// e2e/ - real WeKnora server blackbox tests (testscript-style) // contract/ - envelope JSON shape golden + error.code registry consistency
// e2e/ - real WeKnora server blackbox tests (testscript-style)
package acceptance package acceptance
+4 -4
View File
@@ -7,10 +7,10 @@
// the default `go test ./...` (mirrors gh's acceptance/ build tag pattern; // the default `go test ./...` (mirrors gh's acceptance/ build tag pattern;
// see https://github.com/cli/cli/tree/trunk/acceptance). To run: // see https://github.com/cli/cli/tree/trunk/acceptance). To run:
// //
// cd cli // cd cli
// WEKNORA_E2E_HOST=https://kb.example.com \ // WEKNORA_E2E_HOST=https://kb.example.com \
// WEKNORA_E2E_TOKEN=eyJhbGc... \ // WEKNORA_E2E_TOKEN=eyJhbGc... \
// go test -tags=acceptance_e2e -v ./acceptance/e2e/... // go test -tags=acceptance_e2e -v ./acceptance/e2e/...
// //
// Optional WEKNORA_E2E_KB_NAME_PREFIX customizes the throwaway KB name (default // Optional WEKNORA_E2E_KB_NAME_PREFIX customizes the throwaway KB name (default
// "cli-e2e-"). Cleanup runs even on test failure via t.Cleanup so the server // "cli-e2e-"). Cleanup runs even on test failure via t.Cleanup so the server
-1
View File
@@ -84,4 +84,3 @@ func runList(jopts *cmdutil.JSONOptions, f *cmdutil.Factory) error {
} }
return tw.Flush() return tw.Flush()
} }
+7 -7
View File
@@ -60,17 +60,17 @@ type ChatService interface {
// continue a conversation: the answer text, retrieval references, and the // continue a conversation: the answer text, retrieval references, and the
// session pointer to thread follow-ups. // session pointer to thread follow-ups.
type chatData struct { type chatData struct {
Answer string `json:"answer"` Answer string `json:"answer"`
References []*sdk.SearchResult `json:"references"` References []*sdk.SearchResult `json:"references"`
// Thinking holds the reasoning / reflection text emitted by reasoning // Thinking holds the reasoning / reflection text emitted by reasoning
// models (GPT-5, Claude extended thinking) via response_type=thinking // models (GPT-5, Claude extended thinking) via response_type=thinking
// frames. Omitted when empty (non-reasoning model or model didn't // frames. Omitted when empty (non-reasoning model or model didn't
// surface reasoning for this query). // surface reasoning for this query).
Thinking string `json:"thinking,omitempty"` Thinking string `json:"thinking,omitempty"`
SessionID string `json:"session_id"` SessionID string `json:"session_id"`
AssistantMessageID string `json:"assistant_message_id,omitempty"` AssistantMessageID string `json:"assistant_message_id,omitempty"`
KBID string `json:"kb_id"` KBID string `json:"kb_id"`
Query string `json:"query"` Query string `json:"query"`
} }
// NewCmd builds `weknora chat <text>`. // NewCmd builds `weknora chat <text>`.
-1
View File
@@ -145,4 +145,3 @@ func validateName(name string) error {
} }
return nil return nil
} }
-1
View File
@@ -140,4 +140,3 @@ func TestAdd_JSON(t *testing.T) {
t.Errorf("first added context must be current=true, got %v", got) t.Errorf("first added context must be current=true, got %v", got)
} }
} }
-1
View File
@@ -124,4 +124,3 @@ func clearContextSecrets(store secrets.Store, c config.Context, name string) {
_ = store.Delete(name, "api_key") _ = store.Delete(name, "api_key")
} }
} }
-1
View File
@@ -203,4 +203,3 @@ func TestRemove_Current_TTY_PromptNo(t *testing.T) {
t.Errorf("aborted remove must not mutate config") t.Errorf("aborted remove must not mutate config")
} }
} }
+3 -3
View File
@@ -75,9 +75,9 @@ func TestUse_NotFound_DeterministicTieBreak(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("XDG_CONFIG_HOME", t.TempDir())
_, _ = iostreams.SetForTest(t) _, _ = iostreams.SetForTest(t)
cfg := &config.Config{Contexts: map[string]config.Context{ cfg := &config.Config{Contexts: map[string]config.Context{
"prod": {Host: "https://a"}, "prod": {Host: "https://a"},
"prom": {Host: "https://b"}, "prom": {Host: "https://b"},
"prog": {Host: "https://c"}, "prog": {Host: "https://c"},
}} }}
if err := config.Save(cfg); err != nil { if err := config.Save(cfg); err != nil {
t.Fatalf("Save: %v", err) t.Fatalf("Save: %v", err)
+3 -3
View File
@@ -28,9 +28,9 @@ var docListFields = []string{
} }
type ListOptions struct { type ListOptions struct {
PageSize int // Items per server batch. With --all-pages, controls PageSize int // Items per server batch. With --all-pages, controls
// per-request load. Without, controls the single page size. // per-request load. Without, controls the single page size.
Status string // --status: filter by parse_status (server-side query param) Status string // --status: filter by parse_status (server-side query param)
// Limit caps the returned items client-side (default 30; 0 = no cap). // Limit caps the returned items client-side (default 30; 0 = no cap).
// Applied after pagination / --all-pages accumulation and sort. // Applied after pagination / --all-pages accumulation and sort.
Limit int Limit int
+3 -2
View File
@@ -128,7 +128,9 @@ func TestList_KBIDRequired(t *testing.T) {
} }
f := &cmdutil.Factory{ f := &cmdutil.Factory{
Config: func() (*config.Config, error) { return cfg, nil }, Config: func() (*config.Config, error) { return cfg, nil },
Client: func() (*sdk.Client, error) { return nil, errors.New("client should not be called when kb id is missing") }, Client: func() (*sdk.Client, error) {
return nil, errors.New("client should not be called when kb id is missing")
},
} }
cmd := NewCmdList(f) cmd := NewCmdList(f)
cmd.SetContext(context.Background()) cmd.SetContext(context.Background())
@@ -337,4 +339,3 @@ func TestList_AllPages_WithLimit_StopsAtLimit(t *testing.T) {
// Should have called pages 1..3 (60 items) then capped at 50. // Should have called pages 1..3 (60 items) then capped at 50.
assert.LessOrEqual(t, len(svc.calls), 3, "should not walk past the page that fills --limit") assert.LessOrEqual(t, len(svc.calls), 3, "should not walk past the page that fills --limit")
} }
-1
View File
@@ -163,4 +163,3 @@ func walkMatches(root, pattern string) ([]string, error) {
} }
return out, nil return out, nil
} }
-1
View File
@@ -191,4 +191,3 @@ func TestUploadRecursive_JSON_BareObject(t *testing.T) {
assert.True(t, typed.Silent, "JSON-path partial failure must be Silent") assert.True(t, typed.Silent, "JSON-path partial failure must be Silent")
assert.Equal(t, cmdutil.CodeServerError, typed.Code) assert.Equal(t, cmdutil.CodeServerError, typed.Code)
} }
-1
View File
@@ -450,4 +450,3 @@ func (s *realServices) GetSystemInfo(ctx context.Context) (*sdk.SystemInfo, erro
} }
return cli.GetSystemInfo(ctx) return cli.GetSystemInfo(ctx)
} }
+5 -5
View File
@@ -16,12 +16,12 @@ import (
// fakeEditSvc captures the (id, request) pair handed to UpdateKnowledgeBase // fakeEditSvc captures the (id, request) pair handed to UpdateKnowledgeBase
// and scripts the GetKnowledgeBase fetch used by the fetch-then-update path. // and scripts the GetKnowledgeBase fetch used by the fetch-then-update path.
type fakeEditSvc struct { type fakeEditSvc struct {
current *sdk.KnowledgeBase // returned by GetKnowledgeBase current *sdk.KnowledgeBase // returned by GetKnowledgeBase
currentErr error currentErr error
gotID string gotID string
gotReq *sdk.UpdateKnowledgeBaseRequest gotReq *sdk.UpdateKnowledgeBaseRequest
resp *sdk.KnowledgeBase resp *sdk.KnowledgeBase
err error err error
} }
func (f *fakeEditSvc) GetKnowledgeBase(_ context.Context, id string) (*sdk.KnowledgeBase, error) { func (f *fakeEditSvc) GetKnowledgeBase(_ context.Context, id string) (*sdk.KnowledgeBase, error) {
-1
View File
@@ -79,4 +79,3 @@ func TestEmpty_NotFound(t *testing.T) {
require.ErrorAs(t, err, &typed) require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code) assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code)
} }
-1
View File
@@ -139,4 +139,3 @@ func TestRoot_ContextFlagPropagation(t *testing.T) {
}) })
} }
} }
+3 -4
View File
@@ -65,9 +65,9 @@ func TestKBSearch_SortByNameLength(t *testing.T) {
require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, nil, svc)) require.NoError(t, runKBSearch(context.Background(), &KBSearchOptions{Query: "marketing", Limit: 20}, nil, svc))
got := out.String() got := out.String()
// Order: shortest name first. // Order: shortest name first.
iShort := strings.Index(got,"kb_short") iShort := strings.Index(got, "kb_short")
iMid := strings.Index(got,"kb_mid") iMid := strings.Index(got, "kb_mid")
iLong := strings.Index(got,"kb_long") iLong := strings.Index(got, "kb_long")
assert.Less(t, iShort, iMid) assert.Less(t, iShort, iMid)
assert.Less(t, iMid, iLong) assert.Less(t, iMid, iLong)
} }
@@ -116,4 +116,3 @@ func TestKBSearch_NetworkError(t *testing.T) {
require.ErrorAs(t, err, &typed) require.ErrorAs(t, err, &typed)
assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code) assert.Equal(t, cmdutil.CodeAuthUnauthenticated, typed.Code)
} }
-1
View File
@@ -80,4 +80,3 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
assert.False(t, svc.called) assert.False(t, svc.called)
assert.Contains(t, errBuf.String(), "Aborted") assert.Contains(t, errBuf.String(), "Aborted")
} }
-1
View File
@@ -261,4 +261,3 @@ func TestList_AllPages_WithLimit_StopsAtLimit(t *testing.T) {
assert.Equal(t, 50, got) assert.Equal(t, 50, got)
assert.LessOrEqual(t, len(svc.calls), 3, "must not fetch beyond what fills --limit") assert.LessOrEqual(t, len(svc.calls), 3, "must not fetch beyond what fills --limit")
} }
+1 -1
View File
@@ -21,7 +21,7 @@ import (
// - 401 on /api/v1/auth/login or /api/v1/auth/refresh: pass through // - 401 on /api/v1/auth/login or /api/v1/auth/refresh: pass through
// (otherwise a stale refresh token causes infinite recursion). // (otherwise a stale refresh token causes infinite recursion).
// - 401 with no initial token configured (api-key contexts): pass through // - 401 with no initial token configured (api-key contexts): pass through
// - api-key credentials have no refresh semantic. // - api-key credentials have no refresh semantic.
// - 401 with non-replayable request body (req.GetBody == nil): pass // - 401 with non-replayable request body (req.GetBody == nil): pass
// through. The SDK always uses bytes.Buffer bodies; this is a safety // through. The SDK always uses bytes.Buffer bodies; this is a safety
// net for hand-built requests. // net for hand-built requests.
+8 -8
View File
@@ -10,14 +10,14 @@ import (
// ConfirmDestructive guards a destructive operation (delete, force-overwrite) // ConfirmDestructive guards a destructive operation (delete, force-overwrite)
// behind explicit user approval. Behavior matrix: // behind explicit user approval. Behavior matrix:
// //
// yes=true → proceed (explicit user opt-in via -y/--yes) // yes=true → proceed (explicit user opt-in via -y/--yes)
// non-TTY OR jsonOut → return CodeInputConfirmationRequired (exit 10); // non-TTY OR jsonOut → return CodeInputConfirmationRequired (exit 10);
// no UI to prompt, agent/CI must re-invoke with -y // no UI to prompt, agent/CI must re-invoke with -y
// after the human explicitly approves // after the human explicitly approves
// TTY + interactive → prompt; user-yes proceeds, user-no returns // TTY + interactive → prompt; user-yes proceeds, user-no returns
// CodeUserAborted ("Aborted." to stderr) // CodeUserAborted ("Aborted." to stderr)
// prompter error → returns CodeInputMissingFlag (rare; stdin closed // prompter error → returns CodeInputMissingFlag (rare; stdin closed
// mid-prompt) // mid-prompt)
// //
// The non-TTY branch is the destructive-write protocol: high-risk writes // The non-TTY branch is the destructive-write protocol: high-risk writes
// always require explicit confirmation in scripted contexts, never silent // always require explicit confirmation in scripted contexts, never silent
+2 -2
View File
@@ -29,8 +29,8 @@ const (
CodeResourceLocked ErrorCode = "resource.locked" CodeResourceLocked ErrorCode = "resource.locked"
// input.* - flag and argument validation // input.* - flag and argument validation
CodeInputInvalidArgument ErrorCode = "input.invalid_argument" CodeInputInvalidArgument ErrorCode = "input.invalid_argument"
CodeInputMissingFlag ErrorCode = "input.missing_flag" CodeInputMissingFlag ErrorCode = "input.missing_flag"
// CodeInputConfirmationRequired marks a high-risk write that has no // CodeInputConfirmationRequired marks a high-risk write that has no
// interactive UI (non-TTY or --json) and was invoked without -y/--yes. // interactive UI (non-TTY or --json) and was invoked without -y/--yes.
// Mapped to exit code 10 (see cli/README.md). Agents must surface the // Mapped to exit code 10 (see cli/README.md). Agents must surface the
+5 -5
View File
@@ -9,10 +9,10 @@ import (
// ExitCode maps an error to the documented CLI exit code. // ExitCode maps an error to the documented CLI exit code.
// - 0 success // - 0 success
// - 1 generic / unknown typed error - fallback for: resource.already_exists, // - 1 generic / unknown typed error - fallback for: resource.already_exists,
// resource.locked, local.* (config_corrupt / keychain_denied / file_io / // resource.locked, local.* (config_corrupt / keychain_denied / file_io /
// context_not_found / kb_id_required / kb_not_found / projectlink_corrupt / // context_not_found / kb_id_required / kb_not_found / projectlink_corrupt /
// user_aborted / upload_file_not_found), mcp.*, server.session_create_failed, // user_aborted / upload_file_not_found), mcp.*, server.session_create_failed,
// sse.stream_aborted, and any code outside the named buckets below // sse.stream_aborted, and any code outside the named buckets below
// - 2 flag / argument problem (cobra parse / unknown subcommand) // - 2 flag / argument problem (cobra parse / unknown subcommand)
// - 3 auth.* // - 3 auth.*
// - 4 resource.not_found // - 4 resource.not_found
@@ -20,7 +20,7 @@ import (
// - 6 server.rate_limited // - 6 server.rate_limited
// - 7 server.* (other than rate_limited/session_create_failed) / network.* // - 7 server.* (other than rate_limited/session_create_failed) / network.*
// - 10 input.confirmation_required - high-risk write needs explicit -y // - 10 input.confirmation_required - high-risk write needs explicit -y
// (see cli/README.md) // (see cli/README.md)
// - 130 SIGINT (handled by Go runtime, not this function) // - 130 SIGINT (handled by Go runtime, not this function)
func ExitCode(err error) int { func ExitCode(err error) int {
if err == nil { if err == nil {
+2 -2
View File
@@ -25,8 +25,8 @@ import (
// Four closures: // Four closures:
// - Config: parses ~/.config/weknora/config.yaml (no network) // - Config: parses ~/.config/weknora/config.yaml (no network)
// - Client: constructs the SDK client; only Secrets is sync.Once-cached, // - Client: constructs the SDK client; only Secrets is sync.Once-cached,
// so callers should hold the returned *sdk.Client across // so callers should hold the returned *sdk.Client across
// multiple SDK calls within one invocation // multiple SDK calls within one invocation
// - Prompter: returns interactive prompter; agent mode returns AgentPrompter // - Prompter: returns interactive prompter; agent mode returns AgentPrompter
// - Secrets: builds the OS keyring / file fallback credential store the // - Secrets: builds the OS keyring / file fallback credential store the
// first time it is requested (probing the keyring at startup // first time it is requested (probing the keyring at startup
+1 -1
View File
@@ -50,7 +50,7 @@ const jsonNoOptSentinel = "\x00json-no-value"
// - `--json` → bare JSON payload, no field filter // - `--json` → bare JSON payload, no field filter
// - `--json=id,name` → each object restricted to the listed fields // - `--json=id,name` → each object restricted to the listed fields
// - `--jq <expr>` → apply a jq expression to the JSON; requires // - `--jq <expr>` → apply a jq expression to the JSON; requires
// --json to be set explicitly // --json to be set explicitly
// //
// `fields` is the set of available fields the user may pass; rendered in // `fields` is the set of available fields the user may pass; rendered in
// the command's help. Pass nil to skip the help annotation (uncommon). // the command's help. Pass nil to skip the help annotation (uncommon).
-1
View File
@@ -80,4 +80,3 @@ func applyBareFieldFilter(raw []byte, fields []string) ([]byte, error) {
return raw, nil return raw, nil
} }
} }
-1
View File
@@ -56,4 +56,3 @@ func TestWriteAtomicYAML_RoundTrip(t *testing.T) {
} }
} }
} }