Skip to main content

omni_dev/drive/
rename.rs

1//! Drive file rename.
2//!
3//! Renaming only ever touches a file's `name` field and never changes
4//! `parents`, so — unlike `move` — it can never change who can see the
5//! file. There is nothing to gate: rename always proceeds (subject to the
6//! usual API/auth failures), but it still goes through the same audit-log
7//! path `move` does, since "every move/rename must be logged" (#1557) is an
8//! invariant that applies to both operations equally.
9
10use 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/// The result of a successful rename.
21#[derive(Debug, Clone, Serialize)]
22pub struct RenameOutcome {
23    /// The Drive file id acted on.
24    pub file_id: String,
25    /// The file's name before this rename.
26    pub old_name: String,
27    /// The file's name after this rename.
28    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
37/// Renames `file_id` to `new_name`.
38///
39/// Fetches the current name first (`files.get`) — both an existence check
40/// and what lets the log show old→new — then calls `files.update`. Always
41/// records a [`DriveMutationOutcome`] via
42/// [`request_log::record_drive_mutation`], on both success and failure:
43/// logging happens here, inside the engine, rather than at the CLI call
44/// site, so the "every move/rename must be logged" invariant holds for
45/// every current and future caller (CLI today, a possible MCP tool later).
46pub 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
68/// Builds and writes the [`DriveMutationOutcome`] for one `rename` attempt.
69/// Split out from [`rename`] purely for readability — not otherwise reused.
70fn 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        // The target name — the best-known name whether or not `files.get`
84        // resolved the current one first.
85        file_name: new_name.to_string(),
86        status,
87        // Rename never changes `parents`, so it never has a visibility
88        // diff to report.
89        added_principals: Vec::new(),
90        removed_principals: Vec::new(),
91        crosses_drive_boundary: false,
92        // Rename is never gated by the folder write-permission gate.
93        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}