Skip to content

fix(drive): use title for default download filename - #2089

Open
wittam-01 wants to merge 1 commit into
mainfrom
fix/drive-download-default-filename
Open

fix(drive): use title for default download filename#2089
wittam-01 wants to merge 1 commit into
mainfrom
fix/drive-download-default-filename

Conversation

@wittam-01

@wittam-01 wittam-01 commented Jul 28, 2026

Copy link
Copy Markdown
Collaborator

Summary

Fix drive +download default naming when --output is omitted. The command now resolves metadata title before starting the download and saves with Content-Disposition filename > metadata title > token.

Changes

  • Add conditional metadata title lookup for omitted --output, so missing metadata permission fails before the download stream starts.
  • Resolve the default save name from response filename, metadata title, then token while keeping explicit --output behavior unchanged.
  • Add unit tests, dry-run E2E coverage, and update the lark-drive download reference.

Test Plan

  • Unit tests pass: go test ./shortcuts/drive -run 'TestDriveDownload(UsesContentDispositionWhenOutputOmitted|FallsBackToMetadataTitleWhenOutputOmitted|FallsBackToTokenWhenOutputOmittedAndMetadataEmpty|MetadataErrorBeforeDownloadWhenOutputOmitted|RejectsOverwriteWithoutFlag|AllowsOverwriteFlag)' -count=1\n- [x] Dry-run E2E passes with a locally built binary: LARK_CLI_BIN=/Users/bytedance/go/src/github.com/larksuite/cli/tmp/lark-cli-drive-download-default go test ./tests/cli_e2e/drive -run 'TestDriveDownloadDryRun_(DefaultNamePlansMetadataBeforeDownload|ExplicitOutputSkipsMetadata)' -count=1\n- [x] git diff --cached --check\n\n## Related Issues\n- None\n

Summary by CodeRabbit

  • New Features
    • When --output is omitted, Drive downloads now use a safe default filename/path automatically.
    • Filename priority: Content-Disposition filename, then Drive metadata title, then the file token.
    • Metadata lookup and additional planning happen only when needed for the default output; explicit --output skips it.
    • Safer handling for invalid/unsafe paths, including preventing overwrites of existing files without --overwrite.
  • Documentation
    • Updated drive +download notes for the token-only flow’s default save location.
  • Tests
    • Expanded unit and CLI e2e coverage for naming fallbacks, scope enforcement, dry-run API planning, and validation/error behavior.

@github-actions github-actions Bot added domain/ccm PR touches the ccm domain size/M Single-domain feat or fix with limited business impact labels Jul 28, 2026
@coderabbitai

coderabbitai Bot commented Jul 28, 2026

Copy link
Copy Markdown

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: a3587938-585e-42cc-9f10-c971d7278239

📥 Commits

Reviewing files that changed from the base of the PR and between 21daea2 and e31740f.

📒 Files selected for processing (5)
  • shortcuts/drive/drive_download.go
  • shortcuts/drive/drive_io_test.go
  • skills/lark-drive/references/lark-drive-download.md
  • tests/cli_e2e/drive/coverage.md
  • tests/cli_e2e/drive/drive_download_dryrun_test.go
🚧 Files skipped from review as they are similar to previous changes (5)
  • skills/lark-drive/references/lark-drive-download.md
  • tests/cli_e2e/drive/coverage.md
  • tests/cli_e2e/drive/drive_download_dryrun_test.go
  • shortcuts/drive/drive_download.go
  • shortcuts/drive/drive_io_test.go

📝 Walkthrough

Walkthrough

drive +download now derives omitted output filenames from Content-Disposition, Drive metadata titles, or file tokens. Metadata lookup is conditional on --output, planned during dry runs, performed before download, and covered by unit, e2e, and documentation updates.

Changes

Drive download output flow

Layer / File(s) Summary
Default output naming contract
shortcuts/drive/drive_download.go
Adds filename sanitization and default path precedence, plus conditional metadata scope and output validation handling.
Metadata and download execution
shortcuts/drive/drive_download.go
Plans and performs metadata lookup when output is omitted, resolves the final path after download headers are available, and validates overwrite behavior.
Behavior validation and documentation
shortcuts/drive/drive_io_test.go, tests/cli_e2e/drive/*, skills/lark-drive/references/lark-drive-download.md
Adds coverage for metadata ordering, filename fallbacks, explicit output behavior, required permissions, and command documentation.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant DriveDownload
  participant DriveMetadataAPI
  participant DriveDownloadAPI
  participant FileSystem
  User->>DriveDownload: Run download without --output
  DriveDownload->>DriveMetadataAPI: Query metadata title
  DriveDownload->>DriveDownloadAPI: Request file content
  DriveDownloadAPI-->>DriveDownload: Return content and filename header
  DriveDownload->>FileSystem: Resolve and save output path
Loading

Possibly related PRs

  • larksuite/cli#339: Related changes to DriveDownload output handling and FileIO-based validation.

Suggested labels: bugfix

Suggested reviewers: fangshuyu-768

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title is clear and related, though it only mentions the metadata title and not the full default-name fallback flow.
Description check ✅ Passed The description follows the required template and includes summary, changes, test plan, and related issues.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/drive-download-default-filename

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 28, 2026

Copy link
Copy Markdown

🚀 PR Preview Install Guide

🧰 CLI update

npm i -g https://pkg.pr.new/larksuite/cli/@larksuite/cli@e31740fa44d2a30b3517ba94a3a12cd66f94be46

🧩 Skill update

npx skills add larksuite/cli#fix/drive-download-default-filename -y -g

@codecov

codecov Bot commented Jul 28, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.54839% with 4 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.20%. Comparing base (b0b1ca4) to head (e31740f).
⚠️ Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
shortcuts/drive/drive_download.go 93.54% 2 Missing and 2 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2089      +/-   ##
==========================================
+ Coverage   75.16%   75.20%   +0.04%     
==========================================
  Files         912      913       +1     
  Lines       96475    96707     +232     
==========================================
+ Hits        72517    72732     +215     
- Misses      18381    18386       +5     
- Partials     5577     5589      +12     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
shortcuts/drive/drive_download.go (1)

46-55: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consolidate the Drive metadata scope constant.

driveMetadataReadScope is this file-only copy of the shared drive metadata scope already used across many Drive shortcuts. Define/export it from shortcuts/common or another shared location and reuse it here.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/drive/drive_download.go` around lines 46 - 55, Consolidate the
duplicated driveMetadataReadScope constant by defining or exporting the shared
Drive metadata scope from shortcuts/common (or the existing shared Drive scope
location), then update DriveDownload and other references to reuse that symbol.
Remove the file-local copy while preserving the existing ConditionalScopes
behavior.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@shortcuts/drive/drive_download.go`:
- Around line 21-44: Update driveDownloadFallbackFileName and
driveDownloadDefaultOutputPath to reject "/" in addition to the existing empty,
"." and ".." checks, falling back to fileToken before returning or appending an
extension.

In `@shortcuts/drive/drive_io_test.go`:
- Around line 1714-1744: Strengthen
TestDriveDownloadMetadataErrorBeforeDownloadWhenOutputOmitted by asserting
problem.Subtype alongside problem.Category and problem.Code. Verify it is the
expected authorization subtype, or at minimum non-empty if no specific subtype
constant is available, while preserving the existing typed-error validation.

In `@tests/cli_e2e/drive/drive_download_dryrun_test.go`:
- Line 1: Add live E2E coverage alongside the existing dry-run tests in
drive_download_dryrun_test.go for drive +download filename resolution:
create/upload a fixture with a known title, download without an explicit output
path against the live backend, assert the resolved filename and file contents,
and clean up all created resources using the available bot credentials. Update
the corresponding coverage.md row/notes to reflect the new live workflow and
remove the “no live file fixture workflow yet” caveat only after the test is
implemented.

---

Nitpick comments:
In `@shortcuts/drive/drive_download.go`:
- Around line 46-55: Consolidate the duplicated driveMetadataReadScope constant
by defining or exporting the shared Drive metadata scope from shortcuts/common
(or the existing shared Drive scope location), then update DriveDownload and
other references to reuse that symbol. Remove the file-local copy while
preserving the existing ConditionalScopes behavior.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: a289514b-00f9-41e4-94fe-a2636810964e

📥 Commits

Reviewing files that changed from the base of the PR and between b0b1ca4 and 40fefc3.

📒 Files selected for processing (5)
  • shortcuts/drive/drive_download.go
  • shortcuts/drive/drive_io_test.go
  • skills/lark-drive/references/lark-drive-download.md
  • tests/cli_e2e/drive/coverage.md
  • tests/cli_e2e/drive/drive_download_dryrun_test.go

Comment thread shortcuts/drive/drive_download.go
Comment thread shortcuts/drive/drive_io_test.go
@@ -0,0 +1,90 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🟠 Major | 🏗️ Heavy lift

Missing live E2E coverage for the drive +download filename-resolution behavior change. As per path instructions for tests/cli_e2e/**/*.go, "New flows or behavior changes require live E2E coverage with a self-contained create/use/cleanup workflow and bot credentials where applicable." The new default-filename-resolution behavior (Content-Disposition → metadata title → token precedence, metadata fetched before download) is only exercised via dry-run mocks; coverage.md itself acknowledges no live fixture workflow exists yet.

  • tests/cli_e2e/drive/drive_download_dryrun_test.go#L1-91: add a live workflow test (e.g., upload a fixture file with a known title/no explicit output, run drive +download for real, and assert the saved filename/content against the live backend, with create/use/cleanup) alongside the existing dry-run tests.
  • tests/cli_e2e/drive/coverage.md#L34-34: update the row/notes once the live workflow test lands; until then, the "no live file fixture workflow yet" caveat should stay explicit rather than implying full coverage.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/cli_e2e/drive/drive_download_dryrun_test.go` at line 1, Add live E2E
coverage alongside the existing dry-run tests in drive_download_dryrun_test.go
for drive +download filename resolution: create/upload a fixture with a known
title, download without an explicit output path against the live backend, assert
the resolved filename and file contents, and clean up all created resources
using the available bot credentials. Update the corresponding coverage.md
row/notes to reflect the new live workflow and remove the “no live file fixture
workflow yet” caveat only after the test is implemented.

Source: Coding guidelines

Comment thread skills/lark-drive/references/lark-drive-download.md Outdated
Comment thread shortcuts/drive/drive_download.go Outdated
@wittam-01
wittam-01 force-pushed the fix/drive-download-default-filename branch from 40fefc3 to 21daea2 Compare July 29, 2026 09:00

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
shortcuts/drive/drive_io_test.go (1)

1808-1812: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Avoid t.Fatal inside the OnMatch callback.

OnMatch runs inside RoundTrip, which is not guaranteed to execute on the test goroutine; t.Fatal there calls runtime.Goexit on the wrong goroutine and can hang or mask the failure. Record the ordering and assert after the command returns (or use t.Errorf).

♻️ Suggested adjustment
+	var metaSeenBeforeDownload bool
 		OnMatch: func(req *http.Request) {
-			if len(metaStub.CapturedBody) == 0 {
-				t.Fatal("metadata title lookup must happen before download")
-			}
+			metaSeenBeforeDownload = len(metaStub.CapturedBody) > 0
 		},

Then assert metaSeenBeforeDownload after mountAndRunDrive returns.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@shortcuts/drive/drive_io_test.go` around lines 1808 - 1812, Replace the
t.Fatal call inside the OnMatch callback with a goroutine-safe ordering record,
such as setting metaSeenBeforeDownload when the metadata body is captured before
download. After mountAndRunDrive returns, assert the recorded ordering on the
test goroutine, preserving the requirement that metadata lookup precedes
download.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@skills/lark-drive/references/lark-drive-download.md`:
- Around line 14-15: Update the token-only usage documentation for `lark-cli
drive +download` to state that omitting `--output` requires the Drive metadata
read scope, and document the automatic filename precedence as
Content-Disposition filename, then metadata title, then file token.

In `@tests/cli_e2e/drive/coverage.md`:
- Line 34: Update the Metrics block in coverage.md to reflect 15 covered out of
32 leaf commands and the corresponding percentage, then add a Summary bullet for
the newly covered drive +download command describing its dry-run
metadata-planning and explicit-output behavior.

---

Nitpick comments:
In `@shortcuts/drive/drive_io_test.go`:
- Around line 1808-1812: Replace the t.Fatal call inside the OnMatch callback
with a goroutine-safe ordering record, such as setting metaSeenBeforeDownload
when the metadata body is captured before download. After mountAndRunDrive
returns, assert the recorded ordering on the test goroutine, preserving the
requirement that metadata lookup precedes download.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: c6e193d4-30f8-452e-bcb9-be7ca01e3f4c

📥 Commits

Reviewing files that changed from the base of the PR and between 40fefc3 and 21daea2.

📒 Files selected for processing (5)
  • shortcuts/drive/drive_download.go
  • shortcuts/drive/drive_io_test.go
  • skills/lark-drive/references/lark-drive-download.md
  • tests/cli_e2e/drive/coverage.md
  • tests/cli_e2e/drive/drive_download_dryrun_test.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • tests/cli_e2e/drive/drive_download_dryrun_test.go
  • shortcuts/drive/drive_download.go

Comment thread skills/lark-drive/references/lark-drive-download.md
Comment thread tests/cli_e2e/drive/coverage.md
@wittam-01
wittam-01 force-pushed the fix/drive-download-default-filename branch from 21daea2 to e31740f Compare July 29, 2026 09:25
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

domain/ccm PR touches the ccm domain size/M Single-domain feat or fix with limited business impact

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant