-
Notifications
You must be signed in to change notification settings - Fork 1.2k
feat(drive): add +download, +export, and +move helpers #664
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Bot-Dev-RPA
wants to merge
1
commit into
googleworkspace:main
Choose a base branch
from
Bot-Dev-RPA:feat/drive-helpers-v2
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| --- | ||
| "@googleworkspace/cli": minor | ||
| --- | ||
|
|
||
| Add Drive helper commands: `+download` (download files by ID), `+export` (export Google Workspace docs to local formats), and `+move` (move files between folders) |
This file was deleted.
Oops, something went wrong.
135 changes: 135 additions & 0 deletions
135
crates/google-workspace-cli/src/helpers/drive/download.rs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,135 @@ | ||
| // Copyright 2026 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| use super::*; | ||
|
|
||
| /// Handle the `+download` subcommand. | ||
| pub(super) async fn handle_download(matches: &ArgMatches) -> Result<(), GwsError> { | ||
| let file_id = matches.get_one::<String>("file-id").unwrap(); | ||
| let output_path = matches.get_one::<String>("output"); | ||
|
|
||
| let dry_run = matches.get_flag("dry-run"); | ||
|
|
||
| if dry_run { | ||
| let info = json!({ | ||
| "dry_run": true, | ||
| "action": "download", | ||
| "file_id": file_id, | ||
| "output": output_path, | ||
| }); | ||
| println!( | ||
| "{}", | ||
| serde_json::to_string_pretty(&info).unwrap_or_default() | ||
| ); | ||
| return Ok(()); | ||
| } | ||
|
|
||
| let token = auth::get_token(&[DRIVE_READONLY_SCOPE]) | ||
| .await | ||
| .map_err(|e| GwsError::Auth(format!("Drive auth failed: {e}")))?; | ||
|
|
||
| let client = crate::client::build_client()?; | ||
| let encoded_id = encode_path_segment(file_id); | ||
|
|
||
| // Step 1: Fetch metadata for the real filename and MIME type | ||
| let metadata = fetch_file_metadata(&client, &token, &encoded_id, "name,mimeType,size").await?; | ||
|
|
||
| let remote_name = metadata | ||
| .get("name") | ||
| .and_then(|v| v.as_str()) | ||
| .unwrap_or("download"); | ||
|
|
||
| // Guard: Google Workspace files cannot be downloaded directly | ||
| if let Some(mime) = metadata.get("mimeType").and_then(|v| v.as_str()) { | ||
| if mime.starts_with(GOOGLE_APPS_MIME_PREFIX) { | ||
| return Err(GwsError::Validation(format!( | ||
| "File '{}' is a Google Workspace document ({}). \ | ||
| Use `gws drive +export` to export it to a local format (e.g., --format pdf).", | ||
| crate::output::sanitize_for_terminal(remote_name), | ||
| crate::output::sanitize_for_terminal(mime) | ||
| ))); | ||
| } | ||
| } | ||
|
|
||
| // Determine output file path and validate the final resolved path. | ||
| // The remote filename is untrusted (from Drive API), so validation must | ||
| // happen after path resolution, not just on the raw --output flag. | ||
| let dest = resolve_output_path(output_path.map(|s| s.as_str()), remote_name)?; | ||
| crate::validate::validate_safe_file_path(&dest.to_string_lossy(), "output path")?; | ||
|
|
||
| // Step 2: Download binary content | ||
| let download_url = format!( | ||
| "https://www.googleapis.com/drive/v3/files/{}", | ||
| encoded_id, | ||
| ); | ||
| let download_resp = crate::client::send_with_retry(|| { | ||
| client | ||
| .get(&download_url) | ||
| .query(&[("alt", "media")]) | ||
| .bearer_auth(&token) | ||
| }) | ||
| .await | ||
| .map_err(|e| GwsError::Other(anyhow::anyhow!("Download request failed: {e}")))?; | ||
|
|
||
| if !download_resp.status().is_success() { | ||
| let status = download_resp.status(); | ||
| let body = download_resp.text().await.unwrap_or_default(); | ||
| return Err(GwsError::Api { | ||
| code: status.as_u16(), | ||
| message: body, | ||
| reason: "download_failed".to_string(), | ||
| enable_url: None, | ||
| }); | ||
| } | ||
|
|
||
| let total_bytes = stream_to_file(download_resp, &dest).await?; | ||
|
|
||
| let result = json!({ | ||
| "status": "success", | ||
| "file": dest.display().to_string(), | ||
| "bytes": total_bytes, | ||
| "sourceFileId": file_id, | ||
| }); | ||
| println!( | ||
| "{}", | ||
| serde_json::to_string_pretty(&result).unwrap_or_default() | ||
| ); | ||
|
|
||
| Ok(()) | ||
| } | ||
|
|
||
| #[cfg(test)] | ||
| mod tests { | ||
| use clap::{Arg, Command}; | ||
|
|
||
| fn download_cmd() -> Command { | ||
| Command::new("download") | ||
| .arg(Arg::new("file-id").required(true).index(1)) | ||
| .arg(Arg::new("output").long("output").short('o').value_name("PATH")) | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_download_command_requires_file_id() { | ||
| assert!(download_cmd().try_get_matches_from(["download"]).is_err()); | ||
| } | ||
|
|
||
| #[test] | ||
| fn test_download_command_parses_args() { | ||
| let m = download_cmd() | ||
| .try_get_matches_from(["download", "abc123", "--output", "out.pdf"]) | ||
| .unwrap(); | ||
| assert_eq!(m.get_one::<String>("file-id").unwrap(), "abc123"); | ||
| assert_eq!(m.get_one::<String>("output").unwrap(), "out.pdf"); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.