From 73a88b4f0afc2a815a6746c79dc0f026acd936b5 Mon Sep 17 00:00:00 2001 From: nullkey Date: Tue, 12 May 2026 23:41:05 +0800 Subject: [PATCH] feat(cli): api --input + completion smoke MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit api (3-11): - `--input ` reads the request body from disk; `--input -` reads from stdin. Matches gh CLI canonical naming verified against the gh manual ("The file to use as body for the HTTP request — use \"-\" to read from standard input"). `--data` / `--input` are mutually exclusive. - Options.StdinReader (defaults to iostreams.IO.In) for test injection. completion (3-13 smoke only — release-artifact ship deferred to release milestone): - Smoke test asserts cobra's auto-registered bash/zsh/fish/powershell scripts produce non-trivially-sized output with the per-shell signature (#compdef / complete -c weknora / etc.). Guards against cobra bumps silently breaking completion for one shell. 3-14 doctor --no-cache: already implemented (factory.go:297) with TestDoctor_NoCache_BypassesCache covering it — verified, no change needed. Roadmap: 3-11, 3-13 (smoke), 3-14 (verified). --- cli/cmd/api/api.go | 64 +++++++++++++++++++++++++------------- cli/cmd/api/api_test.go | 29 +++++++++++++++-- cli/cmd/completion_test.go | 46 +++++++++++++++++++++++++++ 3 files changed, 115 insertions(+), 24 deletions(-) create mode 100644 cli/cmd/completion_test.go diff --git a/cli/cmd/api/api.go b/cli/cmd/api/api.go index 2c943526..2d9c91b9 100644 --- a/cli/cmd/api/api.go +++ b/cli/cmd/api/api.go @@ -1,12 +1,11 @@ // Package api implements the `weknora api` raw HTTP passthrough command. // -// Mirrors `gh api` ergonomics: 1 positional (path) + `-X/--method` flag, -// default GET (auto-promoted to POST when a body is supplied via --data / -// --data-file). The two body-source flags are mutually exclusive. Default -// raw response body to stdout; --json wraps in CLI envelope. Reuses -// sdk.Client.Raw which already applies tenant + auth headers; v0.2 does not -// support --header (SDK Raw signature lacks header param) — that's planned -// for v0.3. +// Mirrors `gh api` ergonomics (verified against the gh manual): one +// positional (path) + `-X/--method` flag, default GET (auto-promoted to +// POST when a body is supplied via --data or --input). The two body- +// source flags are mutually exclusive. Default raw response body to +// stdout; --json wraps in CLI envelope. Reuses sdk.Client.Raw which +// already applies tenant + auth headers. package api import ( @@ -29,12 +28,13 @@ import ( // Options captures `weknora api` flag state. type Options struct { - Method string - Data string - DataFile string - JSONOut bool - DryRun bool - Yes bool + Method string + Data string + Input string // --input: file path, "-" for stdin + JSONOut bool + DryRun bool + Yes bool + StdinReader io.Reader // overridden by tests; defaults to iostreams.IO.In } // Service is the narrow SDK surface this command depends on. The production @@ -53,7 +53,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command { Short: "Make a raw API request to the WeKnora server", Long: `Send an HTTP request through the SDK and print the response. -The default method is GET; passing --data / --data-file auto-promotes it to +The default method is GET; passing --data / --input auto-promotes it to POST. Use -X/--method to override (DELETE / PUT / PATCH / HEAD). Auth, tenant, and request-id headers are applied automatically from the @@ -89,20 +89,42 @@ Examples: } cmd.Flags().StringVarP(&opts.Method, "method", "X", "", "HTTP method (default: GET, or POST when a body is supplied)") cmd.Flags().StringVarP(&opts.Data, "data", "d", "", "Request body as raw string (e.g. JSON)") - cmd.Flags().StringVar(&opts.DataFile, "data-file", "", "Read request body from file") + cmd.Flags().StringVar(&opts.Input, "input", "", "Read request body from file (use `-` for stdin); gh CLI parity") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Wrap response in JSON envelope (status/headers/body)") - cmd.MarkFlagsMutuallyExclusive("data", "data-file") + cmd.MarkFlagsMutuallyExclusive("data", "input") agent.SetAgentHelp(cmd, "Raw HTTP passthrough to the WeKnora server. Use when no typed command exists for the endpoint. Headers (auth / tenant / request-id) are injected from the active context.") return cmd } +// readInput reads opts.Input and returns its contents. "-" reads from +// opts.StdinReader (or iostreams.IO.In as the production default). +// Mirrors gh `api --input -` for piped JSON payloads. +func readInput(opts *Options) ([]byte, error) { + if opts.Input == "-" { + r := opts.StdinReader + if r == nil { + r = iostreams.IO.In + } + b, err := io.ReadAll(r) + if err != nil { + return nil, cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read request body from stdin") + } + return b, nil + } + b, err := os.ReadFile(opts.Input) + if err != nil { + return nil, cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read input file %s", opts.Input) + } + return b, nil +} + // resolveMethod implements gh's auto-method behavior: explicit -X wins; // otherwise body presence promotes GET → POST. func resolveMethod(opts *Options) string { if opts.Method != "" { return strings.ToUpper(opts.Method) } - if opts.Data != "" || opts.DataFile != "" { + if opts.Data != "" || opts.Input != "" { return "POST" } return "GET" @@ -124,16 +146,16 @@ func runAPI(ctx context.Context, opts *Options, svc Service, method, path string return cmdutil.NewError(cmdutil.CodeInputInvalidArgument, fmt.Sprintf("path must start with /: %s", path)) } - // Resolve request body. --data and --data-file are mutually exclusive at + // Resolve request body. --data and --input are mutually exclusive at // the cobra layer; the second branch is reachable only when --data is // empty. var body any if opts.Data != "" { body = json.RawMessage(opts.Data) - } else if opts.DataFile != "" { - contents, err := os.ReadFile(opts.DataFile) + } else if opts.Input != "" { + contents, err := readInput(opts) if err != nil { - return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "read data file %s", opts.DataFile) + return err } body = json.RawMessage(contents) } diff --git a/cli/cmd/api/api_test.go b/cli/cmd/api/api_test.go index ed1d6c7a..ddbd6ea2 100644 --- a/cli/cmd/api/api_test.go +++ b/cli/cmd/api/api_test.go @@ -117,7 +117,9 @@ func TestAPI_PostWithData(t *testing.T) { } } -func TestAPI_DataFile(t *testing.T) { +// TestAPI_InputFile verifies --input reads the request body from +// disk. gh CLI parity (verified against gh manual: `--input `). +func TestAPI_InputFile(t *testing.T) { _, _ = iostreams.SetForTest(t) tmp := filepath.Join(t.TempDir(), "body.json") payload := `{"k":"from-file"}` @@ -131,12 +133,33 @@ func TestAPI_DataFile(t *testing.T) { }) defer stop() - opts := &Options{DataFile: tmp} + opts := &Options{Input: tmp} if err := runAPI(context.Background(), opts, cli, "POST", "/api/v1/x"); err != nil { t.Fatalf("runAPI: %v", err) } if string(seenBody) != payload { - t.Errorf("body from --data-file: got %q, want %q", seenBody, payload) + t.Errorf("body from --input: got %q, want %q", seenBody, payload) + } +} + +// TestAPI_InputDash_Stdin verifies the gh-style "--input -" form: the +// payload comes from opts.StdinReader (production-default iostreams.IO.In). +func TestAPI_InputDash_Stdin(t *testing.T) { + _, _ = iostreams.SetForTest(t) + var seenBody []byte + cli, stop := newTestClient(t, func(w http.ResponseWriter, r *http.Request) { + seenBody, _ = io.ReadAll(r.Body) + _, _ = w.Write([]byte(`{}`)) + }) + defer stop() + + payload := `{"k":"from-stdin"}` + opts := &Options{Input: "-", StdinReader: strings.NewReader(payload)} + if err := runAPI(context.Background(), opts, cli, "POST", "/api/v1/x"); err != nil { + t.Fatalf("runAPI: %v", err) + } + if string(seenBody) != payload { + t.Errorf("body from --input -: got %q, want %q", seenBody, payload) } } diff --git a/cli/cmd/completion_test.go b/cli/cmd/completion_test.go new file mode 100644 index 00000000..42c002ea --- /dev/null +++ b/cli/cmd/completion_test.go @@ -0,0 +1,46 @@ +package cmd + +import ( + "bytes" + "strings" + "testing" + + "github.com/Tencent/WeKnora/cli/internal/cmdutil" +) + +// TestCompletion_AllShells smoke-tests cobra's auto-registered completion +// command. The output is shell-specific bytecode/script; the test just +// asserts each shell produces a non-trivially-sized script and references +// the binary name. Guards against future cobra bumps silently breaking +// completion for one shell. +func TestCompletion_AllShells(t *testing.T) { + cases := []struct { + shell string + mustContain string // signature byte sequence specific to the shell + minSizeBytes int + }{ + {"bash", "bash completion", 1024}, + {"zsh", "#compdef", 1024}, + {"fish", "complete -c weknora", 1024}, + {"powershell", "Register-ArgumentCompleter", 1024}, + } + for _, tc := range cases { + t.Run(tc.shell, func(t *testing.T) { + cmd := NewRootCmd(&cmdutil.Factory{}) + var buf bytes.Buffer + cmd.SetOut(&buf) + cmd.SetErr(&buf) + cmd.SetArgs([]string{"completion", tc.shell}) + if err := cmd.Execute(); err != nil { + t.Fatalf("completion %s: %v", tc.shell, err) + } + if buf.Len() < tc.minSizeBytes { + t.Errorf("%s script suspiciously short: %d bytes", tc.shell, buf.Len()) + } + if !strings.Contains(buf.String(), tc.mustContain) { + t.Errorf("%s script missing signature %q (first 200 bytes: %q)", + tc.shell, tc.mustContain, buf.String()[:min(200, buf.Len())]) + } + }) + } +}