omni-dev 0.46.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, Datadog, Gmail, and Drive.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! CLI commands for `omni-dev drive sheets write`/`append`/`clear`.
//!
//! Three clap structs over one engine call. They share `run_write`, so the
//! gate wiring, `--dry-run` handling, output rendering and request logging
//! cannot drift between them.

use std::io::Read as _;

use anyhow::{Context, Result};
use clap::{Parser, ValueEnum};

use crate::cli::drive::format::{output_as, sanitize_for_terminal, OutputFormat};
use crate::cli::drive::helpers;
use crate::cli::drive::sheets::values::{self, ValuesFormat};
use crate::drive::client::DriveClient;
use crate::drive::sheets::api::ValueInputOption;
use crate::drive::sheets::client::SheetsClient;
use crate::drive::sheets::write::{describe, write, WriteOptions, WriteVerb};

/// `--input`'s value set — a thin CLI-layer copy of [`ValueInputOption`],
/// keeping `clap` out of the engine (mirrors
/// `crate::cli::drive::permissions::check::OperationArg`).
#[derive(Debug, Clone, Copy, Default, ValueEnum)]
#[value(rename_all = "kebab-case")]
pub enum InputArg {
    /// Parse values as if typed into the UI: `=SUM(A1:A3)` becomes a
    /// formula, `2026-09-06` a date, `1,234` a number.
    #[default]
    UserEntered,
    /// Store every value verbatim as text; a leading `=` stays literal.
    Raw,
}

impl From<InputArg> for ValueInputOption {
    fn from(arg: InputArg) -> Self {
        match arg {
            InputArg::UserEntered => Self::UserEntered,
            InputArg::Raw => Self::Raw,
        }
    }
}

/// Overwrites the cells of a range.
///
/// Drops a cell's rich-text runs even when the value is unchanged; see
/// `docs/drive.md`.
#[derive(Parser)]
pub struct WriteCommand {
    /// Spreadsheet id (the `/d/<ID>/` segment of a Sheets URL).
    pub spreadsheet_id: String,

    /// A1 range to write, optionally carrying its own `Sheet!` prefix.
    #[arg(long, value_name = "A1")]
    pub range: Option<String>,

    /// Sheet (tab) title. Supplies the prefix for a bare `--range`.
    /// Conflicts with a `--range` that already names a sheet.
    #[arg(long, value_name = "NAME")]
    pub sheet: Option<String>,

    /// Values to write: a local file path, or `-` to read stdin. CSV unless
    /// the path ends in `.json`/`.tsv` or `--values-format` says otherwise.
    #[arg(long, value_name = "PATH|-")]
    pub values: String,

    /// How to parse `--values`. `auto` infers from the file extension.
    #[arg(long = "values-format", value_enum, default_value_t = ValuesFormat::Auto)]
    pub values_format: ValuesFormat,

    /// How the API interprets the values. `user-entered` (the default)
    /// parses formulas, dates and numbers the way typing them into the UI
    /// would; `raw` stores every value verbatim as text.
    #[arg(long, value_enum, default_value_t = InputArg::UserEntered)]
    pub input: InputArg,

    /// Reports the gate verdict and the parsed dimensions without calling
    /// the Sheets API.
    #[arg(long)]
    pub dry_run: bool,

    #[command(flatten)]
    pub lease: crate::cli::drive::helpers::LeaseTokenArg,

    /// Output format.
    #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Table)]
    pub output: OutputFormat,
}

/// Appends rows after the last row of a range's table.
///
/// Presumably drops rich-text runs on an existing cell like `sheets write`
/// does, though this hasn't been measured; see `docs/drive.md`.
#[derive(Parser)]
pub struct AppendCommand {
    /// Spreadsheet id (the `/d/<ID>/` segment of a Sheets URL).
    pub spreadsheet_id: String,

    /// A1 range identifying the table to append to, optionally carrying its
    /// own `Sheet!` prefix.
    #[arg(long, value_name = "A1")]
    pub range: Option<String>,

    /// Sheet (tab) title. Supplies the prefix for a bare `--range`.
    #[arg(long, value_name = "NAME")]
    pub sheet: Option<String>,

    /// Rows to append: a local file path, or `-` to read stdin.
    #[arg(long, value_name = "PATH|-")]
    pub values: String,

    /// How to parse `--values`. `auto` infers from the file extension.
    #[arg(long = "values-format", value_enum, default_value_t = ValuesFormat::Auto)]
    pub values_format: ValuesFormat,

    /// How the API interprets the values (see `drive sheets write`).
    #[arg(long, value_enum, default_value_t = InputArg::UserEntered)]
    pub input: InputArg,

    /// Reports the gate verdict and the parsed dimensions without calling
    /// the Sheets API.
    #[arg(long)]
    pub dry_run: bool,

    #[command(flatten)]
    pub lease: crate::cli::drive::helpers::LeaseTokenArg,

    /// Output format.
    #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Table)]
    pub output: OutputFormat,
}

/// Clears a range's values, leaving formatting intact.
#[derive(Parser)]
pub struct ClearCommand {
    /// Spreadsheet id (the `/d/<ID>/` segment of a Sheets URL).
    pub spreadsheet_id: String,

    /// A1 range to clear, optionally carrying its own `Sheet!` prefix.
    #[arg(long, value_name = "A1")]
    pub range: Option<String>,

    /// Sheet (tab) title. Supplies the prefix for a bare `--range`, or
    /// clears the whole tab on its own.
    #[arg(long, value_name = "NAME")]
    pub sheet: Option<String>,

    /// Reports the gate verdict without calling the Sheets API.
    #[arg(long)]
    pub dry_run: bool,

    #[command(flatten)]
    pub lease: crate::cli::drive::helpers::LeaseTokenArg,

    /// Output format.
    #[arg(short = 'o', long, value_enum, default_value_t = OutputFormat::Table)]
    pub output: OutputFormat,
}

impl WriteCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let values = read_values(&self.values, self.values_format)?;
        let opts = WriteOptions {
            spreadsheet_id: self.spreadsheet_id,
            verb: WriteVerb::Write,
            range: self.range,
            sheet: self.sheet,
            values,
            input: self.input.into(),
            dry_run: self.dry_run,
            lease_token: self.lease.lease,
            ledger_path: helpers::resolve_ledger_path(self.dry_run)?,
        };
        run_write(client, &opts, &self.output).await
    }
}

impl AppendCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let values = read_values(&self.values, self.values_format)?;
        let opts = WriteOptions {
            spreadsheet_id: self.spreadsheet_id,
            verb: WriteVerb::Append,
            range: self.range,
            sheet: self.sheet,
            values,
            input: self.input.into(),
            dry_run: self.dry_run,
            lease_token: self.lease.lease,
            ledger_path: helpers::resolve_ledger_path(self.dry_run)?,
        };
        run_write(client, &opts, &self.output).await
    }
}

impl ClearCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let opts = WriteOptions {
            spreadsheet_id: self.spreadsheet_id,
            verb: WriteVerb::Clear,
            range: self.range,
            sheet: self.sheet,
            values: Vec::new(),
            input: ValueInputOption::default(),
            dry_run: self.dry_run,
            lease_token: self.lease.lease,
            ledger_path: helpers::resolve_ledger_path(self.dry_run)?,
        };
        run_write(client, &opts, &self.output).await
    }
}

/// Reads and parses `--values` from a path or stdin.
///
/// Shared with `sheets create`, which takes the same flag.
pub(crate) fn read_values(source: &str, format: ValuesFormat) -> Result<Vec<Vec<String>>> {
    let content = if source == "-" {
        // Bounded at the cap + 1 so an unbounded stream is never buffered
        // past it before being refused — there's no upfront size to stat
        // for a pipe, unlike the file branch below. Mirrors
        // `crate::cli::drive::edit`'s `read_stdin_content`.
        let mut buf = Vec::new();
        std::io::stdin()
            .take(crate::drive::files_api::MAX_UPLOAD_BYTES + 1)
            .read_to_end(&mut buf)
            .context("Failed to read --values from stdin")?;
        anyhow::ensure!(
            buf.len() as u64 <= crate::drive::files_api::MAX_UPLOAD_BYTES,
            "--values from stdin is over the {} byte cap",
            crate::drive::files_api::MAX_UPLOAD_BYTES
        );
        String::from_utf8(buf).context("--values from stdin is not valid UTF-8")?
    } else {
        // Bounded by the same cap `drive upload`/`edit` use, so a stray
        // multi-gigabyte file is refused rather than buffered.
        let metadata = std::fs::metadata(source)
            .with_context(|| format!("Failed to stat --values file {source}"))?;
        anyhow::ensure!(
            metadata.len() <= crate::drive::files_api::MAX_UPLOAD_BYTES,
            "--values file {source} is {} bytes, over the {} byte cap",
            metadata.len(),
            crate::drive::files_api::MAX_UPLOAD_BYTES
        );
        std::fs::read_to_string(source)
            .with_context(|| format!("Failed to read --values file {source}"))?
    };
    values::parse(&content, format.resolve(source))
}

/// Runs the engine and renders the outcome.
///
/// Split from each `execute` so tests can inject a wiremock client and
/// pre-built options directly, without touching the filesystem or the
/// credential-loading path.
///
/// Takes an options struct rather than loose parameters: `clippy.toml` caps
/// arguments at 7 and this would otherwise sit at 8.
async fn run_write(client: &DriveClient, opts: &WriteOptions, output: &OutputFormat) -> Result<()> {
    let sheets = SheetsClient::from_drive_client(client)?;
    let rules = helpers::active_account_rules()?;
    let outcome = write(client, &sheets, opts, &rules).await;
    if output_as(&outcome, output)? {
        return Ok(());
    }
    // The rendered line carries a Drive-supplied file name and, on a
    // `Blocked`, the deciding rule's id. `describe` lives in the engine
    // layer and stays free of the CLI, so the sanitizing happens here —
    // on the whole line, since none of its own literals contain a
    // control character for the filter to eat.
    println!("{}", sanitize_for_terminal(&describe(&outcome)));
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn input_arg_maps_onto_the_engine_option() {
        assert_eq!(
            ValueInputOption::from(InputArg::UserEntered),
            ValueInputOption::UserEntered
        );
        assert_eq!(ValueInputOption::from(InputArg::Raw), ValueInputOption::Raw);
    }

    #[test]
    fn input_arg_defaults_to_user_entered() {
        // The one default whose wrong value silently mangles data: `raw`
        // would store `=SUM(A1:A3)` as literal text.
        assert_eq!(
            ValueInputOption::from(InputArg::default()),
            ValueInputOption::UserEntered
        );
    }

    #[test]
    fn read_values_parses_a_csv_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("cells.csv");
        std::fs::write(&path, "a,b\nc,d\n").unwrap();
        let rows = read_values(path.to_str().unwrap(), ValuesFormat::Auto).unwrap();
        assert_eq!(rows, vec![vec!["a", "b"], vec!["c", "d"]]);
    }

    #[test]
    fn read_values_infers_json_from_the_extension() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("cells.json");
        std::fs::write(&path, r#"[["a",1]]"#).unwrap();
        let rows = read_values(path.to_str().unwrap(), ValuesFormat::Auto).unwrap();
        assert_eq!(rows, vec![vec!["a", "1"]]);
    }

    #[test]
    fn read_values_reports_a_missing_file_clearly() {
        let err = read_values("/definitely/not/here.csv", ValuesFormat::Auto).unwrap_err();
        assert!(err.to_string().contains("Failed to stat"), "{err}");
    }

    #[test]
    fn read_values_refuses_a_file_over_the_upload_cap() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("huge.csv");
        let oversize = vec![b'a'; (crate::drive::files_api::MAX_UPLOAD_BYTES + 1) as usize];
        std::fs::write(&path, oversize).unwrap();
        let err = read_values(path.to_str().unwrap(), ValuesFormat::Auto).unwrap_err();
        assert!(err.to_string().contains("over the"), "{err}");
    }

    // ── `execute`/`run_write`, against a wiremock Drive+Sheets backend ──

    use crate::drive::auth::{DriveCredentials, DriveGrantedScopes};
    use crate::drive::sheets::client::SHEETS_API_URL;
    use crate::utils::secret::Secret;

    fn test_credentials() -> DriveCredentials {
        DriveCredentials {
            client_id: "client-1".to_string(),
            client_secret: Secret::new("secret-1"),
            refresh_token: Secret::new("refresh-1"),
            scope: DriveGrantedScopes::READONLY,
        }
    }

    /// A `DriveClient` pointed at `server`, whose token endpoint is already
    /// mocked. Callers must additionally point `SHEETS_API_URL` at the same
    /// server, since `run_write` derives its `SheetsClient` internally from
    /// the real process environment.
    async fn client_with_bootstrapped_token(server: &wiremock::MockServer) -> DriveClient {
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path("/token"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "access_token": "test-token",
                    "expires_in": 3600,
                })),
            )
            .mount(server)
            .await;

        let mut client = DriveClient::new(&server.uri(), &test_credentials()).unwrap();
        crate::drive::client::test_support::replace_session(
            &mut client,
            &test_credentials(),
            &format!("{}/token", server.uri()),
        );
        client
    }

    /// `version: "1"` throughout — matches [`seed_ledger_lease`]'s default,
    /// so a test that seeds a lease and mounts a file via this helper has a
    /// live, non-stale lease by construction (ADR-0080 §9).
    fn mount_file(id: &str, mime_type: &str, parents: &[&str]) -> wiremock::Mock {
        let parents: Vec<&str> = parents.to_vec();
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path(format!("/drive/v3/files/{id}")))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": id, "name": id, "mimeType": mime_type, "parents": parents,
                    "version": "1",
                })),
            )
    }

    /// Seeds a live lease for `spreadsheet_id` at `version` into the ledger
    /// path `resolve_ledger_path`/`ledger::ledger_path` will themselves
    /// resolve to (i.e. under the `HOME` a prior `EnvGuard::clear_credentials`
    /// call already redirected) — for tests exercising `Command::execute`
    /// itself, which resolves its own ledger path rather than taking one as
    /// a parameter the way the engine-level tests do.
    fn seed_ledger_lease(spreadsheet_id: &str, version: &str) -> String {
        let ledger_path = crate::drive::lease::ledger::ledger_path().unwrap();
        crate::drive::test_support::seed_lease(&ledger_path, spreadsheet_id, version)
    }

    fn mount_folder(id: &str) -> wiremock::Mock {
        mount_file(id, "application/vnd.google-apps.folder", &[])
    }

    fn allow_write_rule_settings() -> serde_json::Value {
        serde_json::json!({
            "rules": [{
                "folder_id": "parent-1",
                "recursive": true,
                "allow": ["sheets-write"],
            }],
        })
    }

    fn write_opts(dry_run: bool) -> WriteOptions {
        WriteOptions {
            spreadsheet_id: "sheet-1".to_string(),
            verb: WriteVerb::Write,
            range: Some("A1:B2".to_string()),
            sheet: None,
            values: vec![vec!["a".to_string(), "b".to_string()]],
            input: InputArg::UserEntered.into(),
            dry_run,
            // Both callers of this helper are refused before the lease
            // check ever runs (default-deny with no rules written) — a
            // nonexistent ledger path never gets touched.
            lease_token: None,
            ledger_path: std::path::PathBuf::from("/nonexistent/lease-ledger.jsonl"),
        }
    }

    #[tokio::test]
    async fn run_write_reports_blocked_by_default_policy() {
        let guard = crate::drive::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();

        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        std::env::set_var(SHEETS_API_URL, server.uri());
        mount_file(
            "sheet-1",
            crate::drive::types::GOOGLE_SHEET_MIME_TYPE,
            &["parent-1"],
        )
        .mount(&server)
        .await;
        mount_folder("parent-1").mount(&server).await;
        // No settings written: the gate defaults to deny, so no Sheets
        // endpoint should ever be called.

        run_write(&client, &write_opts(false), &OutputFormat::Table)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn run_write_json_output_short_circuits_before_the_table_line() {
        let guard = crate::drive::test_support::EnvGuard::take();
        let _dir = guard.clear_credentials();

        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        std::env::set_var(SHEETS_API_URL, server.uri());
        mount_file(
            "sheet-1",
            crate::drive::types::GOOGLE_SHEET_MIME_TYPE,
            &["parent-1"],
        )
        .mount(&server)
        .await;
        mount_folder("parent-1").mount(&server).await;

        run_write(&client, &write_opts(false), &OutputFormat::Json)
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn write_command_execute_calls_values_update() {
        let guard = crate::drive::test_support::EnvGuard::take();
        let dir = guard.clear_credentials();
        let settings_path = dir.path().join(".omni-dev").join("settings.json");
        crate::utils::settings::Settings::upsert_drive_account(
            &settings_path,
            "work",
            &[("write_permissions", allow_write_rule_settings())],
        )
        .unwrap();

        let values_path = dir.path().join("cells.csv");
        std::fs::write(&values_path, "a,b\n").unwrap();

        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        std::env::set_var(SHEETS_API_URL, server.uri());
        mount_file(
            "sheet-1",
            crate::drive::types::GOOGLE_SHEET_MIME_TYPE,
            &["parent-1"],
        )
        .mount(&server)
        .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("PUT"))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"updatedCells": 2})),
            )
            .mount(&server)
            .await;
        let lease = Some(seed_ledger_lease("sheet-1", "1"));

        let cmd = WriteCommand {
            spreadsheet_id: "sheet-1".to_string(),
            range: Some("A1:B2".to_string()),
            sheet: None,
            values: values_path.to_str().unwrap().to_string(),
            values_format: ValuesFormat::Auto,
            input: InputArg::UserEntered,
            dry_run: false,
            lease: crate::cli::drive::helpers::LeaseTokenArg { lease },
            output: OutputFormat::Table,
        };
        cmd.execute(&client).await.unwrap();
    }

    #[tokio::test]
    async fn append_command_execute_calls_values_append() {
        let guard = crate::drive::test_support::EnvGuard::take();
        let dir = guard.clear_credentials();
        let settings_path = dir.path().join(".omni-dev").join("settings.json");
        crate::utils::settings::Settings::upsert_drive_account(
            &settings_path,
            "work",
            &[("write_permissions", allow_write_rule_settings())],
        )
        .unwrap();

        let values_path = dir.path().join("cells.csv");
        std::fs::write(&values_path, "a,b\n").unwrap();

        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        std::env::set_var(SHEETS_API_URL, server.uri());
        mount_file(
            "sheet-1",
            crate::drive::types::GOOGLE_SHEET_MIME_TYPE,
            &["parent-1"],
        )
        .mount(&server)
        .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/v4/spreadsheets/sheet-1/values/A1:B2:append",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "updates": {"updatedRange": "A1:B2", "updatedCells": 2},
                })),
            )
            .mount(&server)
            .await;
        let lease = Some(seed_ledger_lease("sheet-1", "1"));

        let cmd = AppendCommand {
            spreadsheet_id: "sheet-1".to_string(),
            range: Some("A1:B2".to_string()),
            sheet: None,
            values: values_path.to_str().unwrap().to_string(),
            values_format: ValuesFormat::Auto,
            input: InputArg::UserEntered,
            dry_run: false,
            lease: crate::cli::drive::helpers::LeaseTokenArg { lease },
            output: OutputFormat::Table,
        };
        cmd.execute(&client).await.unwrap();
    }

    #[tokio::test]
    async fn clear_command_execute_calls_values_clear() {
        let guard = crate::drive::test_support::EnvGuard::take();
        let dir = guard.clear_credentials();
        let settings_path = dir.path().join(".omni-dev").join("settings.json");
        crate::utils::settings::Settings::upsert_drive_account(
            &settings_path,
            "work",
            &[("write_permissions", allow_write_rule_settings())],
        )
        .unwrap();

        let server = wiremock::MockServer::start().await;
        let client = client_with_bootstrapped_token(&server).await;
        std::env::set_var(SHEETS_API_URL, server.uri());
        mount_file(
            "sheet-1",
            crate::drive::types::GOOGLE_SHEET_MIME_TYPE,
            &["parent-1"],
        )
        .mount(&server)
        .await;
        mount_folder("parent-1").mount(&server).await;
        wiremock::Mock::given(wiremock::matchers::method("POST"))
            .and(wiremock::matchers::path(
                "/v4/spreadsheets/sheet-1/values/A1:B2:clear",
            ))
            .respond_with(
                wiremock::ResponseTemplate::new(200)
                    .set_body_json(serde_json::json!({"clearedRange": "A1:B2"})),
            )
            .mount(&server)
            .await;
        let lease = Some(seed_ledger_lease("sheet-1", "1"));

        let cmd = ClearCommand {
            spreadsheet_id: "sheet-1".to_string(),
            range: Some("A1:B2".to_string()),
            sheet: None,
            dry_run: false,
            lease: crate::cli::drive::helpers::LeaseTokenArg { lease },
            output: OutputFormat::Table,
        };
        cmd.execute(&client).await.unwrap();
    }
}