feat(cli): doc download + upload --recursive
Roadmap items 3-9 (download) and 3-10 (recursive upload).
SDK addition (additive, non-breaking):
- OpenKnowledgeFile(ctx, id) (filename, body io.ReadCloser, err) —
the new primitive that returns the body as a stream plus the
server-suggested Content-Disposition filename. The existing path-
form DownloadKnowledgeFile is now a thin wrapper (also gained
partial-file-on-error cleanup, a pre-existing bug exposed by the
reshape).
doc download <id>:
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 <file>` for destination; `--clobber` for
overwrite control.
- Default: writes to cwd under the server-suggested filename. If the
server didn't send one, errors with input.missing_flag.
- --output FILE / -O FILE: writes to FILE. Refuses overwrite without
--clobber.
- --output -: stream to stdout (binary-safe).
- Partial writes on error are cleaned up.
doc upload --recursive <dir> --glob '*.pdf':
NOTE on upstream parity: `gh release upload` does NOT support
--recursive (verified — it takes individual file args only). `aws s3
cp --recursive` does, but uses `--include`/`--exclude` glob pattern
pairs rather than a single `--glob`. weknora's single positive `--glob`
is a deliberate simplification, not a direct mirror of either tool.
- Walks the tree, filters by base-name glob, uploads each match
sequentially. Per-file line output: OK / FAIL with the underlying
error. Exit 0 only on full success; on partial failure returns the
first failure's typed code so callers can branch. Rejects --name
with --recursive.
- --dry-run lists matches without uploading.
- --json emits {kb_id, uploaded[], failed[]} envelope at completion.
Bugs caught in the post-commit reviewer round:
- SECURITY: server-supplied filename was used in os.Rename without
sanitization. A malicious / buggy server returning
"../../etc/shadow" could escape cwd. Now filepath.Base'd; "." / "/"
/ "" rejected. Regression test added.
- Wasted-bytes path eliminated via the SDK reshape: the CLI now
inspects filename and applies refuseIfExists BEFORE streaming.
Two-phase temp+rename gone.
- refuseIfExists(path, clobber) helper extracted.
- --json honored in --recursive (uploadOutcome was JSON-tagged but
the envelope was never emitted).
7 + 7 unit tests for download (+ path-traversal regression) and
recursive upload (+ JSON envelope regression).
Roadmap: 3-9, 3-10.
This commit is contained in:
+51
-18
@@ -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 {
|
||||
|
||||
Reference in New Issue
Block a user