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        error,
93        duration,
94    });
95}
96
97#[cfg(test)]
98#[allow(clippy::unwrap_used, clippy::expect_used)]
99mod tests {
100    use super::*;
101    use crate::drive::auth::{DriveCredentials, DriveScope};
102    use crate::utils::secret::Secret;
103
104    fn test_credentials() -> DriveCredentials {
105        DriveCredentials {
106            client_id: "client-1".to_string(),
107            client_secret: Secret::new("secret-1"),
108            refresh_token: Secret::new("refresh-1"),
109            scope: DriveScope::Metadata,
110        }
111    }
112
113    async fn client_with_bootstrapped_token(server: &wiremock::MockServer) -> DriveClient {
114        wiremock::Mock::given(wiremock::matchers::method("POST"))
115            .and(wiremock::matchers::path("/token"))
116            .respond_with(
117                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
118                    "access_token": "test-token",
119                    "expires_in": 3600,
120                })),
121            )
122            .mount(server)
123            .await;
124
125        let mut client = DriveClient::new(&server.uri(), &test_credentials()).unwrap();
126        crate::drive::client::test_support::replace_session(
127            &mut client,
128            &test_credentials(),
129            &format!("{}/token", server.uri()),
130        );
131        client
132    }
133
134    #[tokio::test]
135    async fn rename_fetches_old_name_then_renames() {
136        let server = wiremock::MockServer::start().await;
137        let client = client_with_bootstrapped_token(&server).await;
138        wiremock::Mock::given(wiremock::matchers::method("GET"))
139            .and(wiremock::matchers::path("/drive/v3/files/f1"))
140            .respond_with(
141                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
142                    "id": "f1", "name": "Old Name",
143                })),
144            )
145            .mount(&server)
146            .await;
147        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
148            .and(wiremock::matchers::path("/drive/v3/files/f1"))
149            .respond_with(
150                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
151                    "id": "f1", "name": "New Name",
152                })),
153            )
154            .mount(&server)
155            .await;
156
157        let outcome = rename(&client, "f1", "New Name").await.unwrap();
158        assert_eq!(outcome.file_id, "f1");
159        assert_eq!(outcome.old_name, "Old Name");
160        assert_eq!(outcome.new_name, "New Name");
161    }
162
163    #[tokio::test]
164    async fn rename_propagates_a_missing_file_error() {
165        let server = wiremock::MockServer::start().await;
166        let client = client_with_bootstrapped_token(&server).await;
167        wiremock::Mock::given(wiremock::matchers::method("GET"))
168            .and(wiremock::matchers::path("/drive/v3/files/missing"))
169            .respond_with(wiremock::ResponseTemplate::new(404).set_body_string("not found"))
170            .mount(&server)
171            .await;
172
173        let err = rename(&client, "missing", "New Name").await.unwrap_err();
174        assert!(err.to_string().contains("404"));
175    }
176
177    #[tokio::test]
178    async fn rename_propagates_a_files_update_error_after_a_successful_get() {
179        let server = wiremock::MockServer::start().await;
180        let client = client_with_bootstrapped_token(&server).await;
181        wiremock::Mock::given(wiremock::matchers::method("GET"))
182            .and(wiremock::matchers::path("/drive/v3/files/f1"))
183            .respond_with(
184                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
185                    "id": "f1", "name": "Old Name",
186                })),
187            )
188            .mount(&server)
189            .await;
190        wiremock::Mock::given(wiremock::matchers::method("PATCH"))
191            .and(wiremock::matchers::path("/drive/v3/files/f1"))
192            .respond_with(
193                wiremock::ResponseTemplate::new(403).set_body_json(serde_json::json!({
194                    "error": {
195                        "message": "Insufficient Permission",
196                        "errors": [{"reason": "insufficientPermissions"}],
197                    }
198                })),
199            )
200            .mount(&server)
201            .await;
202
203        let err = rename(&client, "f1", "New Name").await.unwrap_err();
204        assert!(
205            err.to_string().contains("drive auth login --write"),
206            "{err}"
207        );
208    }
209}