1use std::time::{Duration, Instant};
11
12use anyhow::Result;
13use serde::Serialize;
14
15use crate::cli::drive::format::{write_scalar_jsonl, JsonlSerialize};
16use crate::drive::client::DriveClient;
17use crate::drive::files_api::FilesApi;
18use crate::request_log::{self, DriveMutationOutcome};
19
20#[derive(Debug, Clone, Serialize)]
22pub struct RenameOutcome {
23 pub file_id: String,
25 pub old_name: String,
27 pub new_name: String,
29}
30
31impl JsonlSerialize for RenameOutcome {
32 fn write_jsonl(&self, out: &mut dyn std::io::Write) -> Result<()> {
33 write_scalar_jsonl(self, out)
34 }
35}
36
37pub async fn rename(client: &DriveClient, file_id: &str, new_name: &str) -> Result<RenameOutcome> {
47 let started = Instant::now();
48 let result = rename_inner(client, file_id, new_name).await;
49 record_attempt(file_id, new_name, &result, started.elapsed());
50 result
51}
52
53async fn rename_inner(
54 client: &DriveClient,
55 file_id: &str,
56 new_name: &str,
57) -> Result<RenameOutcome> {
58 let files = FilesApi::new(client);
59 let existing = files.get_metadata(file_id).await?;
60 files.rename(file_id, new_name).await?;
61 Ok(RenameOutcome {
62 file_id: file_id.to_string(),
63 old_name: existing.name,
64 new_name: new_name.to_string(),
65 })
66}
67
68fn record_attempt(
71 file_id: &str,
72 new_name: &str,
73 result: &Result<RenameOutcome>,
74 duration: Duration,
75) {
76 let (status, error) = match result {
77 Ok(_) => ("renamed".to_string(), None),
78 Err(err) => ("failed".to_string(), Some(err.to_string())),
79 };
80 request_log::record_drive_mutation(DriveMutationOutcome {
81 operation: "rename",
82 file_id: file_id.to_string(),
83 file_name: new_name.to_string(),
86 status,
87 added_principals: Vec::new(),
90 removed_principals: Vec::new(),
91 crosses_drive_boundary: false,
92 resolved_folder_id: None,
94 decided_by_folder_id: None,
95 decided_by_depth: None,
96 error,
97 duration,
98 });
99}
100
101#[cfg(test)]
102#[allow(clippy::unwrap_used, clippy::expect_used)]
103mod tests {
104 use super::*;
105 use crate::drive::auth::{DriveCredentials, DriveGrantedScopes};
106 use crate::utils::secret::Secret;
107
108 fn test_credentials() -> DriveCredentials {
109 DriveCredentials {
110 client_id: "client-1".to_string(),
111 client_secret: Secret::new("secret-1"),
112 refresh_token: Secret::new("refresh-1"),
113 scope: DriveGrantedScopes::METADATA,
114 }
115 }
116
117 async fn client_with_bootstrapped_token(server: &wiremock::MockServer) -> DriveClient {
118 wiremock::Mock::given(wiremock::matchers::method("POST"))
119 .and(wiremock::matchers::path("/token"))
120 .respond_with(
121 wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
122 "access_token": "test-token",
123 "expires_in": 3600,
124 })),
125 )
126 .mount(server)
127 .await;
128
129 let mut client = DriveClient::new(&server.uri(), &test_credentials()).unwrap();
130 crate::drive::client::test_support::replace_session(
131 &mut client,
132 &test_credentials(),
133 &format!("{}/token", server.uri()),
134 );
135 client
136 }
137
138 #[tokio::test]
139 async fn rename_fetches_old_name_then_renames() {
140 let server = wiremock::MockServer::start().await;
141 let client = client_with_bootstrapped_token(&server).await;
142 wiremock::Mock::given(wiremock::matchers::method("GET"))
143 .and(wiremock::matchers::path("/drive/v3/files/f1"))
144 .respond_with(
145 wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
146 "id": "f1", "name": "Old Name",
147 })),
148 )
149 .mount(&server)
150 .await;
151 wiremock::Mock::given(wiremock::matchers::method("PATCH"))
152 .and(wiremock::matchers::path("/drive/v3/files/f1"))
153 .respond_with(
154 wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
155 "id": "f1", "name": "New Name",
156 })),
157 )
158 .mount(&server)
159 .await;
160
161 let outcome = rename(&client, "f1", "New Name").await.unwrap();
162 assert_eq!(outcome.file_id, "f1");
163 assert_eq!(outcome.old_name, "Old Name");
164 assert_eq!(outcome.new_name, "New Name");
165 }
166
167 #[tokio::test]
168 async fn rename_propagates_a_missing_file_error() {
169 let server = wiremock::MockServer::start().await;
170 let client = client_with_bootstrapped_token(&server).await;
171 wiremock::Mock::given(wiremock::matchers::method("GET"))
172 .and(wiremock::matchers::path("/drive/v3/files/missing"))
173 .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("not found"))
174 .mount(&server)
175 .await;
176
177 let err = rename(&client, "missing", "New Name").await.unwrap_err();
178 assert!(err.to_string().contains("404"));
179 }
180
181 #[tokio::test]
182 async fn rename_propagates_a_files_update_error_after_a_successful_get() {
183 let server = wiremock::MockServer::start().await;
184 let client = client_with_bootstrapped_token(&server).await;
185 wiremock::Mock::given(wiremock::matchers::method("GET"))
186 .and(wiremock::matchers::path("/drive/v3/files/f1"))
187 .respond_with(
188 wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
189 "id": "f1", "name": "Old Name",
190 })),
191 )
192 .mount(&server)
193 .await;
194 wiremock::Mock::given(wiremock::matchers::method("PATCH"))
195 .and(wiremock::matchers::path("/drive/v3/files/f1"))
196 .respond_with(
197 wiremock::ResponseTemplate::new(403).set_body_json(serde_json::json!({
198 "error": {
199 "message": "Insufficient Permission",
200 "errors": [{"reason": "insufficientPermissions"}],
201 }
202 })),
203 )
204 .mount(&server)
205 .await;
206
207 let err = rename(&client, "f1", "New Name").await.unwrap_err();
208 assert!(
209 err.to_string().contains("drive auth login --write"),
210 "{err}"
211 );
212 }
213}