diff --git a/cli/cmd/doc/doc.go b/cli/cmd/doc/doc.go index 2ab4cba5..0080fb60 100644 --- a/cli/cmd/doc/doc.go +++ b/cli/cmd/doc/doc.go @@ -1,4 +1,5 @@ -// Package doc implements the `weknora doc` subtree (list / upload / delete). +// Package doc implements the `weknora doc` subtree (list / upload / download +// / delete). Upload also supports --recursive / --glob for bulk ingestion. // // "Doc" is the CLI noun; the underlying SDK type is `Knowledge`. The renaming // is deliberate: end-users think of a knowledge entry as the document they @@ -22,6 +23,7 @@ func NewCmd(f *cmdutil.Factory) *cobra.Command { } cmd.AddCommand(NewCmdList(f)) cmd.AddCommand(NewCmdUpload(f)) + cmd.AddCommand(NewCmdDownload(f)) cmd.AddCommand(NewCmdDelete(f)) return cmd } diff --git a/cli/cmd/doc/download.go b/cli/cmd/doc/download.go new file mode 100644 index 00000000..8be2e9fd --- /dev/null +++ b/cli/cmd/doc/download.go @@ -0,0 +1,157 @@ +package doc + +import ( + "context" + "errors" + "fmt" + "io" + "os" + "path/filepath" + + "github.com/spf13/cobra" + + "github.com/Tencent/WeKnora/cli/internal/agent" + "github.com/Tencent/WeKnora/cli/internal/cmdutil" + "github.com/Tencent/WeKnora/cli/internal/iostreams" +) + +// DownloadOptions captures `weknora doc download` flag state. +type DownloadOptions struct { + Output string // --output / -O: target path, "-" for stdout, "" for server-suggested filename + Clobber bool // --clobber: allow overwrite of an existing file +} + +// DownloadService is the narrow SDK surface this command depends on. The +// CLI calls OpenKnowledgeFile so it can inspect the server-suggested +// filename and refuse-to-overwrite *before* streaming any bytes. +type DownloadService interface { + OpenKnowledgeFile(ctx context.Context, knowledgeID string) (string, io.ReadCloser, error) +} + +// NewCmdDownload builds `weknora doc download `. Borrows shape from +// `gh release download` — positional id, output flag, `-` sentinel for +// stdout. Flag names match gh canon verified against the gh manual: +// `-O, --output ` for destination, `--clobber` for overwrite +// control. +func NewCmdDownload(f *cmdutil.Factory) *cobra.Command { + opts := &DownloadOptions{} + cmd := &cobra.Command{ + Use: "download ", + Short: "Download a document by ID", + Long: `Streams the document bytes to disk (or stdout with --output -). + +Default behavior (no --output): writes to the cwd under the filename the +server suggests via Content-Disposition. If the server doesn't suggest +one, the command errors and asks for --output FILE explicitly. + +Existing files are NOT overwritten unless --clobber is passed.`, + Example: ` weknora doc download doc_abc # writes ./ + weknora doc download doc_abc -O report.pdf + weknora doc download doc_abc --output - # stream to stdout (binary safe) + weknora doc download doc_abc -O report.pdf --clobber`, + Args: cobra.ExactArgs(1), + RunE: func(c *cobra.Command, args []string) error { + cli, err := f.Client() + if err != nil { + return err + } + return runDownload(c.Context(), opts, cli, args[0]) + }, + } + cmd.Flags().StringVarP(&opts.Output, "output", "O", "", `Output path; "-" for stdout. Defaults to the server-suggested filename.`) + cmd.Flags().BoolVar(&opts.Clobber, "clobber", false, "Overwrite the output file if it already exists") + agent.SetAgentHelp(cmd, "Downloads a document. Agents that pipe the bytes should pass --output - (stdout). The exit code is 0 on success, 1 on resource.not_found, 5 on missing --output when the server didn't supply a filename.") + return cmd +} + +func runDownload(ctx context.Context, opts *DownloadOptions, svc DownloadService, id string) error { + suggested, body, err := svc.OpenKnowledgeFile(ctx, id) + if err != nil { + return cmdutil.Wrapf(cmdutil.ClassifyHTTPError(err), err, "download %s", id) + } + defer body.Close() + + dest, err := resolveDownloadDest(opts, suggested) + if err != nil { + return err + } + if dest == "-" { + _, err := io.Copy(iostreams.IO.Out, body) + return err + } + if err := refuseIfExists(dest, opts.Clobber); err != nil { + return err + } + return streamToFile(body, dest) +} + +// resolveDownloadDest returns the final destination ("-" for stdout, an +// absolute or relative path otherwise) after applying the --output flag +// and sanitizing the server-suggested name. A server that returns a path- +// like filename (..\, /etc/foo) is rejected — only the basename is +// accepted. +func resolveDownloadDest(opts *DownloadOptions, suggested string) (string, error) { + if opts.Output == "-" { + return "-", nil + } + if opts.Output != "" { + return opts.Output, nil + } + if suggested == "" { + return "", &cmdutil.Error{ + Code: cmdutil.CodeInputMissingFlag, + Message: "server did not supply a filename and --output is unset", + Hint: "pass --output FILE (or --output - for stdout)", + } + } + base := filepath.Base(suggested) + if base == "" || base == "." || base == string(filepath.Separator) { + return "", &cmdutil.Error{ + Code: cmdutil.CodeInputInvalidArgument, + Message: fmt.Sprintf("server returned an unusable filename %q", suggested), + Hint: "pass --output FILE explicitly", + } + } + return base, nil +} + +// refuseIfExists returns CodeInputInvalidArgument when path is present on +// disk and clobber is false. Missing-file is success. +func refuseIfExists(path string, clobber bool) error { + if clobber { + return nil + } + _, err := os.Stat(path) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "stat %s", path) + } + return &cmdutil.Error{ + Code: cmdutil.CodeInputInvalidArgument, + Message: fmt.Sprintf("%s already exists", path), + Hint: "pass --clobber to overwrite", + } +} + +// streamToFile copies body into a newly-created file at path. On any +// streaming error the partial file is removed so callers don't see a +// truncated artifact at the user-visible path. +func streamToFile(body io.Reader, path string) error { + f, err := os.Create(path) + if err != nil { + return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "create %s", path) + } + if _, err := io.Copy(f, body); err != nil { + _ = f.Close() + _ = os.Remove(path) + return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "write %s", path) + } + if err := f.Close(); err != nil { + _ = os.Remove(path) + return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "close %s", path) + } + fmt.Fprintf(iostreams.IO.Err, "✓ Saved %s\n", path) + return nil +} diff --git a/cli/cmd/doc/download_test.go b/cli/cmd/doc/download_test.go new file mode 100644 index 00000000..4a17f515 --- /dev/null +++ b/cli/cmd/doc/download_test.go @@ -0,0 +1,136 @@ +package doc + +import ( + "context" + "errors" + "io" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/Tencent/WeKnora/cli/internal/cmdutil" + "github.com/Tencent/WeKnora/cli/internal/iostreams" +) + +// fakeDownloadSvc scripts an OpenKnowledgeFile response. The fake returns +// a ReadCloser over `content` and reports `filename` as the server- +// suggested name. +type fakeDownloadSvc struct { + content string + filename string + err error + gotID string +} + +func (f *fakeDownloadSvc) OpenKnowledgeFile(_ context.Context, id string) (string, io.ReadCloser, error) { + f.gotID = id + if f.err != nil { + return "", nil, f.err + } + return f.filename, io.NopCloser(strings.NewReader(f.content)), nil +} + +func TestDownload_DefaultUsesServerFilename(t *testing.T) { + _, _ = iostreams.SetForTest(t) + tmp := t.TempDir() + prevWD, _ := os.Getwd() + require.NoError(t, os.Chdir(tmp)) + defer os.Chdir(prevWD) + + svc := &fakeDownloadSvc{content: "PDF-1.4 bytes", filename: "report.pdf"} + require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, svc, "doc_abc")) + + got, err := os.ReadFile(filepath.Join(tmp, "report.pdf")) + require.NoError(t, err) + assert.Equal(t, "PDF-1.4 bytes", string(got)) +} + +func TestDownload_OutFile(t *testing.T) { + _, _ = iostreams.SetForTest(t) + dest := filepath.Join(t.TempDir(), "out.bin") + svc := &fakeDownloadSvc{content: "hello", filename: "ignored.txt"} + require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: dest}, svc, "doc_abc")) + + got, err := os.ReadFile(dest) + require.NoError(t, err) + assert.Equal(t, "hello", string(got)) +} + +func TestDownload_OutDash_Stdout(t *testing.T) { + out, _ := iostreams.SetForTest(t) + svc := &fakeDownloadSvc{content: "binary payload", filename: "report.pdf"} + require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: "-"}, svc, "doc_abc")) + assert.Equal(t, "binary payload", out.String()) +} + +func TestDownload_NoFilenameFromServer_DefaultPath_Errors(t *testing.T) { + _, _ = iostreams.SetForTest(t) + svc := &fakeDownloadSvc{content: "x", filename: ""} + err := runDownload(context.Background(), &DownloadOptions{}, svc, "doc_abc") + require.Error(t, err) + var typed *cmdutil.Error + require.ErrorAs(t, err, &typed) + assert.Equal(t, cmdutil.CodeInputMissingFlag, typed.Code) + assert.Contains(t, typed.Hint, "--output") +} + +func TestDownload_NotFound(t *testing.T) { + _, _ = iostreams.SetForTest(t) + svc := &fakeDownloadSvc{err: errors.New("HTTP error 404: not found")} + err := runDownload(context.Background(), &DownloadOptions{Output: filepath.Join(t.TempDir(), "x")}, svc, "doc_missing") + require.Error(t, err) + var typed *cmdutil.Error + require.ErrorAs(t, err, &typed) + assert.Equal(t, cmdutil.CodeResourceNotFound, typed.Code) +} + +func TestDownload_RefusesOverwrite(t *testing.T) { + _, _ = iostreams.SetForTest(t) + dest := filepath.Join(t.TempDir(), "exists.bin") + require.NoError(t, os.WriteFile(dest, []byte("OLD"), 0o644)) + + svc := &fakeDownloadSvc{content: "NEW", filename: ""} + err := runDownload(context.Background(), &DownloadOptions{Output: dest}, svc, "doc_abc") + require.Error(t, err) + var typed *cmdutil.Error + require.ErrorAs(t, err, &typed) + assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code) + got, _ := os.ReadFile(dest) + assert.Equal(t, "OLD", string(got), "must not overwrite without --clobber") +} + +// TestDownload_RejectsServerPathTraversal proves that a malicious or buggy +// server cannot escape the cwd via Content-Disposition: only the basename +// of the suggested filename is accepted. +func TestDownload_RejectsServerPathTraversal(t *testing.T) { + _, _ = iostreams.SetForTest(t) + tmp := t.TempDir() + prevWD, _ := os.Getwd() + require.NoError(t, os.Chdir(tmp)) + defer os.Chdir(prevWD) + + // The server sends "../../etc/shadow" — we accept only "shadow" and + // write to cwd. + svc := &fakeDownloadSvc{content: "exfil", filename: "../../etc/shadow"} + require.NoError(t, runDownload(context.Background(), &DownloadOptions{}, svc, "doc_abc")) + + // File must land inside cwd; parent dirs untouched. + got, err := os.ReadFile(filepath.Join(tmp, "shadow")) + require.NoError(t, err) + assert.Equal(t, "exfil", string(got)) +} + +func TestDownload_ForceOverwrites(t *testing.T) { + _, _ = iostreams.SetForTest(t) + dest := filepath.Join(t.TempDir(), "exists.bin") + require.NoError(t, os.WriteFile(dest, []byte("OLD"), 0o644)) + + svc := &fakeDownloadSvc{content: "NEW", filename: ""} + require.NoError(t, runDownload(context.Background(), &DownloadOptions{Output: dest, Clobber: true}, svc, "doc_abc")) + got, _ := os.ReadFile(dest) + assert.Equal(t, "NEW", string(got)) +} diff --git a/cli/cmd/doc/upload.go b/cli/cmd/doc/upload.go index 1f056bf5..cc7086a5 100644 --- a/cli/cmd/doc/upload.go +++ b/cli/cmd/doc/upload.go @@ -21,9 +21,11 @@ const uploadChannel = "api" // UploadOptions captures `weknora doc upload` flags. type UploadOptions struct { - Name string - JSONOut bool - DryRun bool + Name string + Recursive bool // --recursive: positional arg is a directory; walk + upload each match + Glob string // --glob: filename pattern under --recursive (default "*") + JSONOut bool + DryRun bool } // UploadService is the narrow SDK surface this command depends on. @@ -53,23 +55,33 @@ Pass --name to override the recorded file name (useful when the local file has a generic name like "report.pdf" but you want to surface it as e.g. "Q3 Marketing Report.pdf" in the UI). -v0.2 ships single-file upload only; --recursive / --glob and progress UI are -planned for v0.3.`, +Use --recursive --glob to upload a directory tree (see Examples).`, Example: ` weknora doc upload report.pdf weknora doc upload notes.md --kb a32a63ff-fb36-4874-bcaa-30f48570a694 weknora doc upload notes.md --kb my-kb - weknora doc upload q3.pdf --name "Q3 Marketing Report.pdf"`, + weknora doc upload q3.pdf --name "Q3 Marketing Report.pdf" + weknora doc upload ./docs --recursive --glob '*.pdf'`, Args: cobra.ExactArgs(1), RunE: func(c *cobra.Command, args []string) error { path := args[0] - if err := validateUploadPath(path); err != nil { - return err - } opts.DryRun = cmdutil.IsDryRun(c) kbID, err := f.ResolveKB(c) if err != nil { return err } + if opts.Recursive { + if opts.DryRun { + return runUploadRecursive(c.Context(), opts, nil, kbID, path) + } + cli, err := f.Client() + if err != nil { + return err + } + return runUploadRecursive(c.Context(), opts, cli, kbID, path) + } + if err := validateUploadPath(path); err != nil { + return err + } if opts.DryRun { return runUpload(c.Context(), opts, nil, kbID, path) } @@ -82,8 +94,10 @@ planned for v0.3.`, } cmd.Flags().String("kb", "", "Knowledge base UUID or name (overrides env / project link)") cmd.Flags().StringVar(&opts.Name, "name", "", "Custom file name to record (defaults to base name)") + cmd.Flags().BoolVar(&opts.Recursive, "recursive", false, "Treat the positional argument as a directory to walk") + cmd.Flags().StringVar(&opts.Glob, "glob", "*", "Filename pattern to filter when --recursive (e.g. '*.pdf')") cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope") - agent.SetAgentHelp(cmd, "Uploads one local file to the resolved KB. Refuses non-regular files (dir / symlink). Returns data: Knowledge object with id, parse_status. Pass --kb outside a linked project.") + agent.SetAgentHelp(cmd, "Uploads to the resolved KB. Default: one regular file (refuses dir/non-regular). With --recursive: walks the directory, filters by --glob, uploads each match sequentially with per-file OK/FAIL output. Exit 1 on any per-file failure, exit 0 only on full success. Returns data: single Knowledge object (default) or aggregate report (recursive).") return cmd } diff --git a/cli/cmd/doc/upload_recursive.go b/cli/cmd/doc/upload_recursive.go new file mode 100644 index 00000000..dae5f07b --- /dev/null +++ b/cli/cmd/doc/upload_recursive.go @@ -0,0 +1,170 @@ +package doc + +import ( + "context" + "fmt" + "io/fs" + "os" + "path/filepath" + + "github.com/Tencent/WeKnora/cli/internal/cmdutil" + "github.com/Tencent/WeKnora/cli/internal/format" + "github.com/Tencent/WeKnora/cli/internal/iostreams" +) + +// uploadOutcome is one entry in the recursive upload's per-file report. +type uploadOutcome struct { + Path string `json:"path"` + ID string `json:"id,omitempty"` + Error string `json:"error,omitempty"` +} + +// runUploadRecursive walks dir, filters by Glob, and uploads each match +// sequentially. Per-file errors do NOT abort the walk — they accumulate +// and the final return aggregates them so the user sees the full picture +// in one run. Exit semantics: nil error on full success, a typed *cmdutil.Error +// when ≥1 file failed (the typed code mirrors the first failure's +// classification so callers can still branch). +func runUploadRecursive(ctx context.Context, opts *UploadOptions, svc UploadService, kbID, dir string) error { + if opts.Name != "" { + return &cmdutil.Error{ + Code: cmdutil.CodeInputInvalidArgument, + Message: "--name cannot be combined with --recursive (one name can't apply to N files)", + Hint: "drop --name or upload files one at a time", + } + } + info, err := os.Stat(dir) + if err != nil { + if os.IsNotExist(err) { + return cmdutil.Wrapf(cmdutil.CodeUploadFileNotFound, err, "directory not found: %s", dir) + } + return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "stat %s", dir) + } + if !info.IsDir() { + return &cmdutil.Error{ + Code: cmdutil.CodeInputInvalidArgument, + Message: fmt.Sprintf("not a directory: %s (drop --recursive to upload a single file)", dir), + } + } + + // Sanity-check the pattern up front so a typo doesn't show up as "no + // files matched" per-file. Cobra populates --glob; tests pass it + // explicitly — no in-function default needed. + if _, err := filepath.Match(opts.Glob, ""); err != nil { + return &cmdutil.Error{ + Code: cmdutil.CodeInputInvalidArgument, + Message: fmt.Sprintf("invalid --glob %q: %v", opts.Glob, err), + } + } + + matches, err := walkMatches(dir, opts.Glob) + if err != nil { + return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "walk %s", dir) + } + if len(matches) == 0 { + if opts.JSONOut { + return format.WriteEnvelope(iostreams.IO.Out, format.Success( + recursiveResult{KBID: kbID}, &format.Meta{KBID: kbID})) + } + fmt.Fprintf(iostreams.IO.Out, "(no files matched %q under %s)\n", opts.Glob, dir) + return nil + } + + if opts.DryRun { + previews := make([]uploadOutcome, 0, len(matches)) + for _, m := range matches { + previews = append(previews, uploadOutcome{Path: m}) + } + return cmdutil.EmitDryRun(opts.JSONOut, + recursiveResult{KBID: kbID, Uploaded: previews}, + &format.Meta{KBID: kbID}, + &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("upload %d file(s) to kb %s", len(matches), kbID)}) + } + + var uploaded, failed []uploadOutcome + var firstFailCode cmdutil.ErrorCode + for _, p := range matches { + k, err := svc.CreateKnowledgeFromFile(ctx, kbID, p, nil, nil, "", uploadChannel) + if err != nil { + code := cmdutil.ClassifyHTTPError(err) + if firstFailCode == "" { + firstFailCode = code + } + failed = append(failed, uploadOutcome{Path: p, Error: err.Error()}) + fmt.Fprintf(iostreams.IO.Out, "FAIL %s: %v\n", filepath.Base(p), err) + continue + } + id := "" + if k != nil { + id = k.ID + } + uploaded = append(uploaded, uploadOutcome{Path: p, ID: id}) + fmt.Fprintf(iostreams.IO.Out, "OK %s (id: %s)\n", filepath.Base(p), id) + } + + if opts.JSONOut { + result := recursiveResult{KBID: kbID, Uploaded: uploaded, Failed: failed} + risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("upload %d file(s) to kb %s", len(matches), kbID)} + if err := format.WriteEnvelope(iostreams.IO.Out, + format.SuccessWithRisk(result, &format.Meta{KBID: kbID}, risk)); err != nil { + return err + } + } else { + fmt.Fprintf(iostreams.IO.Out, "Uploaded %d, Failed %d\n", len(uploaded), len(failed)) + } + + if len(failed) > 0 { + return &cmdutil.Error{ + Code: firstFailCode, + Message: fmt.Sprintf("%d of %d uploads failed", len(failed), len(matches)), + } + } + return nil +} + +// recursiveResult is the JSON shape emitted under data when --recursive is +// combined with --json. Mirrors the human-mode per-file output: a list of +// successes (Uploaded) and a list of failures (Failed), each with the +// originating path so agents can re-try only the failed entries. +type recursiveResult struct { + KBID string `json:"kb_id"` + Uploaded []uploadOutcome `json:"uploaded,omitempty"` + Failed []uploadOutcome `json:"failed,omitempty"` +} + +// walkMatches returns every regular file under root whose base name matches +// pattern. Order is filepath.WalkDir's lexical order (stdlib guarantee on +// every supported FS), which is deterministic for test assertions. +func walkMatches(root, pattern string) ([]string, error) { + var out []string + err := filepath.WalkDir(root, func(p string, d fs.DirEntry, err error) error { + if err != nil { + return err + } + if d.IsDir() { + return nil + } + // Skip non-regular files (sockets, devices); the SDK can't upload + // them and they'd show as opaque server errors. + info, ierr := d.Info() + if ierr != nil { + return ierr + } + if !info.Mode().IsRegular() { + return nil + } + ok, merr := filepath.Match(pattern, d.Name()) + if merr != nil { + return merr + } + if ok { + out = append(out, p) + } + return nil + }) + if err != nil { + return nil, err + } + return out, nil +} + diff --git a/cli/cmd/doc/upload_recursive_test.go b/cli/cmd/doc/upload_recursive_test.go new file mode 100644 index 00000000..3fb181b9 --- /dev/null +++ b/cli/cmd/doc/upload_recursive_test.go @@ -0,0 +1,183 @@ +package doc + +import ( + "context" + "errors" + "os" + "path/filepath" + "sort" + "strings" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + + "github.com/Tencent/WeKnora/cli/internal/cmdutil" + "github.com/Tencent/WeKnora/cli/internal/iostreams" + sdk "github.com/Tencent/WeKnora/client" +) + +// scriptedUploadSvc records every CreateKnowledgeFromFile call and returns +// per-path scripted results. +type scriptedUploadSvc struct { + results map[string]struct { + k *sdk.Knowledge + err error + } + called []string +} + +func (s *scriptedUploadSvc) CreateKnowledgeFromFile( + _ context.Context, + _, filePath string, + _ map[string]string, + _ *bool, + _, _ string, +) (*sdk.Knowledge, error) { + s.called = append(s.called, filepath.Base(filePath)) + r, ok := s.results[filepath.Base(filePath)] + if !ok { + return &sdk.Knowledge{ID: "doc_" + filepath.Base(filePath), FileName: filepath.Base(filePath)}, nil + } + return r.k, r.err +} + +func mkTree(t *testing.T, base string, names ...string) { + t.Helper() + for _, n := range names { + full := filepath.Join(base, n) + require.NoError(t, os.MkdirAll(filepath.Dir(full), 0o755)) + require.NoError(t, os.WriteFile(full, []byte("x"), 0o644)) + } +} + +func TestUploadRecursive_WalksAllFiles(t *testing.T) { + out, _ := iostreams.SetForTest(t) + dir := t.TempDir() + mkTree(t, dir, "a.pdf", "b.pdf", "sub/c.pdf") + + svc := &scriptedUploadSvc{} + opts := &UploadOptions{Recursive: true, Glob: "*"} + require.NoError(t, runUploadRecursive(context.Background(), opts, svc, "kb_xxx", dir)) + + sort.Strings(svc.called) + assert.Equal(t, []string{"a.pdf", "b.pdf", "c.pdf"}, svc.called) + got := out.String() + for _, w := range []string{"a.pdf", "b.pdf", "c.pdf", "Uploaded 3"} { + assert.Contains(t, got, w) + } +} + +func TestUploadRecursive_GlobFilter(t *testing.T) { + _, _ = iostreams.SetForTest(t) + dir := t.TempDir() + mkTree(t, dir, "doc.pdf", "ignore.txt", "sub/keep.pdf", "sub/also-ignore.md") + + svc := &scriptedUploadSvc{} + opts := &UploadOptions{Recursive: true, Glob: "*.pdf"} + require.NoError(t, runUploadRecursive(context.Background(), opts, svc, "kb_xxx", dir)) + + sort.Strings(svc.called) + assert.Equal(t, []string{"doc.pdf", "keep.pdf"}, svc.called) +} + +func TestUploadRecursive_PartialFailure_Exits1(t *testing.T) { + out, _ := iostreams.SetForTest(t) + dir := t.TempDir() + mkTree(t, dir, "ok.pdf", "bad.pdf") + + svc := &scriptedUploadSvc{results: map[string]struct { + k *sdk.Knowledge + err error + }{ + "bad.pdf": {err: errors.New("HTTP error 500: internal")}, + }} + opts := &UploadOptions{Recursive: true, Glob: "*"} + err := runUploadRecursive(context.Background(), opts, svc, "kb_xxx", dir) + require.Error(t, err) + + var typed *cmdutil.Error + require.ErrorAs(t, err, &typed) + // CodeServerError preserves the 500 classification of the underlying + // SDK error — the recursive wrapper just aggregates. + assert.Equal(t, cmdutil.CodeServerError, typed.Code) + + got := out.String() + assert.Contains(t, got, "OK") // ok.pdf still succeeded + assert.Contains(t, got, "FAIL") + assert.Contains(t, got, "Uploaded 1") + assert.Contains(t, got, "Failed 1") +} + +func TestUploadRecursive_NoMatches(t *testing.T) { + out, _ := iostreams.SetForTest(t) + dir := t.TempDir() + mkTree(t, dir, "only.txt") + + svc := &scriptedUploadSvc{} + opts := &UploadOptions{Recursive: true, Glob: "*.pdf"} + require.NoError(t, runUploadRecursive(context.Background(), opts, svc, "kb_xxx", dir)) + assert.Len(t, svc.called, 0) + assert.Contains(t, strings.ToLower(out.String()), "no files matched") +} + +func TestUploadRecursive_NotADirectory(t *testing.T) { + _, _ = iostreams.SetForTest(t) + path := writeTempFile(t, "single.pdf") + svc := &scriptedUploadSvc{} + err := runUploadRecursive(context.Background(), &UploadOptions{Recursive: true, Glob: "*"}, svc, "kb_xxx", path) + require.Error(t, err) + var typed *cmdutil.Error + require.ErrorAs(t, err, &typed) + assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code) + assert.Contains(t, typed.Message, "directory") +} + +func TestUploadRecursive_RejectsNameFlag(t *testing.T) { + _, _ = iostreams.SetForTest(t) + dir := t.TempDir() + mkTree(t, dir, "a.pdf") + svc := &scriptedUploadSvc{} + opts := &UploadOptions{Recursive: true, Glob: "*", Name: "single-name.pdf"} + err := runUploadRecursive(context.Background(), opts, svc, "kb_xxx", dir) + require.Error(t, err) + var typed *cmdutil.Error + require.ErrorAs(t, err, &typed) + assert.Equal(t, cmdutil.CodeInputInvalidArgument, typed.Code) + assert.Contains(t, typed.Message, "--name") +} + +func TestUploadRecursive_JSON_Envelope(t *testing.T) { + out, _ := iostreams.SetForTest(t) + dir := t.TempDir() + mkTree(t, dir, "ok.pdf", "bad.pdf") + + svc := &scriptedUploadSvc{results: map[string]struct { + k *sdk.Knowledge + err error + }{ + "bad.pdf": {err: errors.New("HTTP error 500: internal")}, + }} + opts := &UploadOptions{Recursive: true, Glob: "*", JSONOut: true} + err := runUploadRecursive(context.Background(), opts, svc, "kb_xxx", dir) + require.Error(t, err) // partial failure → typed error + + body := out.String() + assert.Contains(t, body, `"kb_id":"kb_xxx"`) + assert.Contains(t, body, `"uploaded":`) + assert.Contains(t, body, `"failed":`) + assert.Contains(t, body, `ok.pdf`) + assert.Contains(t, body, `bad.pdf`) +} + +func TestUploadRecursive_DryRun(t *testing.T) { + out, _ := iostreams.SetForTest(t) + dir := t.TempDir() + mkTree(t, dir, "a.pdf", "b.pdf") + svc := &scriptedUploadSvc{} + opts := &UploadOptions{Recursive: true, Glob: "*", DryRun: true} + require.NoError(t, runUploadRecursive(context.Background(), opts, svc, "kb_xxx", dir)) + assert.Len(t, svc.called, 0, "dry-run must not call SDK") + got := out.String() + assert.Contains(t, got, "would upload 2") +} diff --git a/client/knowledge.go b/client/knowledge.go index fb31acfa..99ed14dc 100644 --- a/client/knowledge.go +++ b/client/knowledge.go @@ -11,6 +11,7 @@ import ( "errors" "fmt" "io" + "mime" "mime/multipart" "net/http" "net/url" @@ -368,35 +369,67 @@ func (c *Client) DeleteKnowledge(ctx context.Context, knowledgeID string) error return parseResponse(resp, &response) } -// DownloadKnowledgeFile downloads a knowledge file to the specified local path +// DownloadKnowledgeFile downloads a knowledge file to the specified local path. +// On any error after the file is opened, the partial file is removed so a +// failed download doesn't leave a corrupt artifact at destPath. +// +// Callers wanting more control (stream to stdout, validate filename before +// touching disk) should use OpenKnowledgeFile and io.Copy directly. func (c *Client) DownloadKnowledgeFile(ctx context.Context, knowledgeID string, destPath string) error { - path := fmt.Sprintf("/api/v1/knowledge/%s/download", knowledgeID) - resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil) + _, body, err := c.OpenKnowledgeFile(ctx, knowledgeID) if err != nil { return err } - defer resp.Body.Close() + defer body.Close() - // Check for HTTP errors - if resp.StatusCode < 200 || resp.StatusCode >= 300 { - body, _ := io.ReadAll(resp.Body) - return fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body)) - } - - // Create destination file out, err := os.Create(destPath) if err != nil { return fmt.Errorf("failed to create file: %w", err) } - defer out.Close() - - // Copy response body to file - _, err = io.Copy(out, resp.Body) - if err != nil { - return fmt.Errorf("failed to write file: %w", err) + if _, err := io.Copy(out, body); err != nil { + _ = out.Close() + _ = os.Remove(destPath) + return fmt.Errorf("failed to copy response body: %w", err) } + return out.Close() +} - return nil +// OpenKnowledgeFile starts a download for the given knowledge entry and +// returns the server-suggested filename (parsed from Content-Disposition; +// empty when the server didn't send one) and a streaming reader for the +// body. Callers MUST Close the returned reader. +// +// Used by `weknora doc download` so the CLI can inspect the filename +// before opening the destination file — avoids streaming the full body +// to a temp file just to discover the request would have been rejected +// (overwrite without --force, missing --out for unnamed downloads, etc.). +func (c *Client) OpenKnowledgeFile(ctx context.Context, knowledgeID string) (string, io.ReadCloser, error) { + path := fmt.Sprintf("/api/v1/knowledge/%s/download", knowledgeID) + resp, err := c.doRequest(ctx, http.MethodGet, path, nil, nil) + if err != nil { + return "", nil, err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + body, _ := io.ReadAll(resp.Body) + _ = resp.Body.Close() + return "", nil, fmt.Errorf("HTTP error %d: %s", resp.StatusCode, string(body)) + } + filename := filenameFromContentDisposition(resp.Header.Get("Content-Disposition")) + return filename, resp.Body, nil +} + +// filenameFromContentDisposition extracts the filename parameter from a +// Content-Disposition header. Returns "" on any parse failure or missing +// parameter — callers fall back to their own default in that case. +func filenameFromContentDisposition(h string) string { + if h == "" { + return "" + } + _, params, err := mime.ParseMediaType(h) + if err != nil { + return "" + } + return params["filename"] } func (c *Client) UpdateKnowledge(ctx context.Context, knowledge *Knowledge) error {