Skip to content

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

Merged
wittam-01 merged 1 commit into
mainfrom
fix/drive-download-default-filename
Jul 31, 2026
Merged

fix(drive): use title for default download filename#2089
wittam-01 merged 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 derive a safe default filename/path (sanitizing Content-Disposition, including slash-only and Windows-reserved characters), with priority: Content-Disposition filename → Drive metadata title → file token.
    • Metadata planning/scope checks are performed only for the default-output flow; explicit --output skips them.
    • Overwrite protection now applies to the computed default output (unless --overwrite is set).
    • Drive export filename sanitization now treats Windows reserved device names as invalid and falls back.
  • Documentation
    • Updated drive +download docs for the token-only default save location.
  • Tests
    • Expanded unit and CLI E2E coverage for default naming, dry-run behavior (API call order), scope enforcement, and related validation/error handling.

@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

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 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, shortcuts/drive/drive_export_common.go
Adds safe filename derivation, Windows reserved-name handling, conditional metadata scope, and output validation.
Metadata and download execution
shortcuts/drive/drive_download.go, shortcuts/drive/drive_io_test.go
Plans and performs metadata lookup when output is omitted, resolves the final path from response headers and metadata, and handles metadata failures and overwrite checks.
Behavior validation and documentation
shortcuts/drive/drive_io_test.go, tests/cli_e2e/drive/*, skills/lark-drive/references/lark-drive-download.md
Covers filename precedence, sanitization, dry-run request ordering, explicit output behavior, authorization, and documented default location.

Estimated code review effort: 4 (Complex) | ~45 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, validate, and save output path
Loading

Possibly related PRs

  • larksuite/cli#194: Extends shared Drive filename sanitization with Windows reserved-device-name handling.
  • larksuite/cli#339: Overlaps with DriveDownload output-path validation and save handling.

Suggested labels: bugfix

Suggested reviewers: fangshuyu-768

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.41% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the PR's main change: fixing default Drive download naming when --output is omitted.
Description check ✅ Passed The description follows the template with Summary, Changes, Test Plan, and Related Issues, and is sufficiently complete.
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 💡 1
📝 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@3fa8d23ad56cffdead082b9c50317dcdb45b4611

🧩 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 89.16667% with 13 lines in your changes missing coverage. Please review.
✅ Project coverage is 75.42%. Comparing base (fa9c30c) to head (3fa8d23).

Files with missing lines Patch % Lines
shortcuts/drive/drive_download.go 87.85% 8 Missing and 5 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #2089      +/-   ##
==========================================
+ Coverage   75.39%   75.42%   +0.03%     
==========================================
  Files         924      924              
  Lines       98005    98114     +109     
==========================================
+ Hits        73895    74007     +112     
+ Misses      18478    18474       -4     
- Partials     5632     5633       +1     

☔ 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
Comment thread tests/cli_e2e/drive/drive_download_dryrun_test.go
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 Outdated
@wittam-01
wittam-01 force-pushed the fix/drive-download-default-filename branch from 21daea2 to e31740f Compare July 29, 2026 09:25
Comment thread shortcuts/drive/drive_download.go Outdated
Comment thread shortcuts/drive/drive_download.go Outdated
@wittam-01
wittam-01 force-pushed the fix/drive-download-default-filename branch from e31740f to b682673 Compare July 30, 2026 07:20

@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.

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

117-126: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Merge the two identical outputPath != "" guards.

♻️ Proposed simplification
-		if outputPath != "" {
-			if _, resolveErr := runtime.ResolveSavePath(outputPath); resolveErr != nil {
-				return errs.NewValidationError(errs.SubtypeInvalidArgument, "unsafe output path: %s", resolveErr).WithParam("--output")
-			}
-		}
-		if outputPath != "" {
-			if _, statErr := runtime.FileIO().Stat(outputPath); statErr == nil && !overwrite {
-				return errs.NewValidationError(errs.SubtypeInvalidArgument, "output file already exists: %s (use --overwrite to replace)", outputPath).WithParam("--output")
-			}
-		}
+		if outputPath != "" {
+			if _, resolveErr := runtime.ResolveSavePath(outputPath); resolveErr != nil {
+				return errs.NewValidationError(errs.SubtypeInvalidArgument, "unsafe output path: %s", resolveErr).WithParam("--output")
+			}
+			if _, statErr := runtime.FileIO().Stat(outputPath); statErr == nil && !overwrite {
+				return errs.NewValidationError(errs.SubtypeInvalidArgument, "output file already exists: %s (use --overwrite to replace)", outputPath).WithParam("--output")
+			}
+		}
🤖 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 117 - 126, Merge the two
outputPath checks into a single outputPath != "" guard in the surrounding
download validation flow, keeping both ResolveSavePath validation and
existing-file/overwrite validation unchanged and in their current order.

105-109: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Step numbering is misleading when --output is provided.

The download step is always labelled [2], but it is the only planned call when --output is set. Consider deriving the prefix from whether the metadata step was planned.

🤖 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 105 - 109, Update the
download plan description in the drive download flow to derive its step prefix
from whether the metadata step was planned, so an output-only download is
numbered as the first step while retaining `[2]` when metadata is included. Use
the existing metadata-planning condition or symbol rather than hardcoding `[2]`.
🤖 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.

Nitpick comments:
In `@shortcuts/drive/drive_download.go`:
- Around line 117-126: Merge the two outputPath checks into a single outputPath
!= "" guard in the surrounding download validation flow, keeping both
ResolveSavePath validation and existing-file/overwrite validation unchanged and
in their current order.
- Around line 105-109: Update the download plan description in the drive
download flow to derive its step prefix from whether the metadata step was
planned, so an output-only download is numbered as the first step while
retaining `[2]` when metadata is included. Use the existing metadata-planning
condition or symbol rather than hardcoding `[2]`.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 586c9a91-2742-4eba-97cd-7a29ec0e8f3e

📥 Commits

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

📒 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)
  • skills/lark-drive/references/lark-drive-download.md
  • tests/cli_e2e/drive/coverage.md

@wittam-01
wittam-01 force-pushed the fix/drive-download-default-filename branch from b682673 to 0ad1a6a Compare July 30, 2026 08:39

@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: 1

🤖 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 37-45: The filename fallback in driveDownloadDefaultOutputPath
skips the metadata title when the header candidate is unusable. In
shortcuts/drive/drive_download.go lines 37-45, sanitize the metadata fallback
from driveDownloadFallbackFileName first, then use it before fileToken when
validating or replacing an invalid header filename, while preserving extension
handling. Update shortcuts/drive/drive_io_test.go lines 1605-1612 to expect
Metadata Title.txt for the invalid CON.txt header case.
🪄 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: 74912b24-cfc4-44da-af13-32b147d522bd

📥 Commits

Reviewing files that changed from the base of the PR and between b682673 and 0ad1a6a.

📒 Files selected for processing (7)
  • shortcuts/drive/drive_download.go
  • shortcuts/drive/drive_export_common.go
  • shortcuts/drive/drive_export_common_test.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)
  • skills/lark-drive/references/lark-drive-download.md
  • tests/cli_e2e/drive/coverage.md

Comment thread shortcuts/drive/drive_download.go Outdated
@wittam-01
wittam-01 force-pushed the fix/drive-download-default-filename branch from 0ad1a6a to f4b47fa Compare July 30, 2026 13:59
@wittam-01
wittam-01 force-pushed the fix/drive-download-default-filename branch from f4b47fa to 3fa8d23 Compare July 31, 2026 02:27
Comment thread shortcuts/drive/drive_download.go
Comment thread skills/lark-drive/references/lark-drive-download.md
@wittam-01
wittam-01 merged commit 946964e into main Jul 31, 2026
35 checks passed
@wittam-01
wittam-01 deleted the fix/drive-download-default-filename branch July 31, 2026 04:12
@liangshuo-1 liangshuo-1 mentioned this pull request Jul 31, 2026
3 tasks
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.

2 participants