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
//! CLI commands for `omni-dev drive sheets add-named-range`/
//! `update-named-range`/`delete-named-range`/`list-named-ranges` (issue
//! #1796).
//!
//! The first three are gated by
//! [`DriveOperation::SheetsStructure`](crate::drive::write_gate::DriveOperation::SheetsStructure)
//! — see [ADR-0081](../../../../docs/adrs/adr-0081.md) §2 for why
//! `delete-named-range` stays here rather than joining `sheets-delete`.
//! `list-named-ranges` is a plain read, ungated like `sheets
//! list-protections`.

use anyhow::Result;
use clap::Parser;

use crate::cli::drive::format::{output_as, sanitize_for_terminal, OutputFormat};
use crate::cli::drive::helpers;
use crate::drive::client::DriveClient;
use crate::drive::sheets::api::SheetsApi;
use crate::drive::sheets::client::SheetsClient;
use crate::drive::sheets::named_range::{
    describe_lines, named_range, NamedRangeOptions, NamedRangeVerb,
};
use crate::drive::sheets::{render_grid_range, sheet_title_by_id};

/// Adds a named range (or, with `--whole-sheet`, one covering an entire
/// sheet).
#[derive(Parser)]
pub struct AddNamedRangeCommand {
    /// Spreadsheet id (the `/d/<ID>/` segment of a Sheets URL).
    pub spreadsheet_id: String,

    /// The name to create. Must be unique workbook-wide.
    #[arg(long, value_name = "NAME")]
    pub name: String,

    /// A1 range the name refers to, optionally carrying its own `Sheet!`
    /// prefix. Mutually exclusive with `--whole-sheet`.
    #[arg(long, value_name = "A1")]
    pub range: Option<String>,

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

    /// Cover the entire sheet named by `--sheet`, rather than a range
    /// within it.
    #[arg(long)]
    pub whole_sheet: bool,

    #[command(flatten)]
    pub write: helpers::StructureWriteArgs,
}

impl AddNamedRangeCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let opts = NamedRangeOptions {
            spreadsheet_id: self.spreadsheet_id,
            verb: NamedRangeVerb::AddNamedRange {
                name: self.name,
                sheet: self.sheet,
                range: self.range,
                whole_sheet: self.whole_sheet,
            },
            dry_run: self.write.dry_run,
            lease_token: self.write.lease.lease,
            ledger_path: helpers::resolve_ledger_path(self.write.dry_run)?,
        };
        run_named_range(client, &opts, &self.write.output).await
    }
}

/// Changes an existing named range's name and/or the range it covers. The
/// target is resolved by `--name` (case-insensitive exact match) or `--id`
/// — exactly one is required — see `drive sheets list-named-ranges` to find
/// either. `--id` is the escape hatch when `--name` matches more than one
/// named range (issue #1975): the ambiguity refusal lists the candidate
/// ids.
#[derive(Parser)]
#[command(group(clap::ArgGroup::new("target").args(["name", "id"]).required(true)))]
pub struct UpdateNamedRangeCommand {
    /// Spreadsheet id (the `/d/<ID>/` segment of a Sheets URL).
    pub spreadsheet_id: String,

    /// The existing name to change, by case-insensitive exact match.
    /// Mutually exclusive with `--id`.
    #[arg(long, value_name = "NAME")]
    pub name: Option<String>,

    /// The existing named range's id, by exact match. Mutually exclusive
    /// with `--name`. Find it with `drive sheets list-named-ranges`.
    #[arg(long, value_name = "ID")]
    pub id: Option<String>,

    /// The new name, when renaming.
    #[arg(long, value_name = "NAME")]
    pub new_name: Option<String>,

    /// A1 range for the new target, optionally carrying its own `Sheet!`
    /// prefix. Mutually exclusive with `--whole-sheet`. Omitting this,
    /// `--sheet` and `--whole-sheet` together keeps the existing range
    /// unchanged — this command may be a rename only.
    #[arg(long, value_name = "A1")]
    pub range: Option<String>,

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

    /// Re-point at the entire sheet named by `--sheet`, rather than a range
    /// within it.
    #[arg(long)]
    pub whole_sheet: bool,

    #[command(flatten)]
    pub write: helpers::StructureWriteArgs,
}

impl UpdateNamedRangeCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let opts = NamedRangeOptions {
            spreadsheet_id: self.spreadsheet_id,
            verb: NamedRangeVerb::UpdateNamedRange {
                name: self.name,
                id: self.id,
                new_name: self.new_name,
                sheet: self.sheet,
                range: self.range,
                whole_sheet: self.whole_sheet,
            },
            dry_run: self.write.dry_run,
            lease_token: self.write.lease.lease,
            ledger_path: helpers::resolve_ledger_path(self.write.dry_run)?,
        };
        run_named_range(client, &opts, &self.write.output).await
    }
}

/// Removes a named range. The target is resolved by `--name`
/// (case-insensitive exact match) or `--id` — exactly one is required —
/// see `drive sheets list-named-ranges` to find either. `--id` is the
/// escape hatch when `--name` matches more than one named range (issue
/// #1975): the ambiguity refusal lists the candidate ids.
///
/// Every cell formula referencing the removed name starts evaluating to
/// `#REF!` (conditional formatting, data validation and chart references
/// are not scanned). `--dry-run` (and the real run, before mutating)
/// reports the count and A1 locations of every such cell formula — read it
/// before running for real.
#[derive(Parser)]
#[command(group(clap::ArgGroup::new("target").args(["name", "id"]).required(true)))]
pub struct DeleteNamedRangeCommand {
    /// Spreadsheet id (the `/d/<ID>/` segment of a Sheets URL).
    pub spreadsheet_id: String,

    /// The existing name to remove, by case-insensitive exact match.
    /// Mutually exclusive with `--id`.
    #[arg(long, value_name = "NAME")]
    pub name: Option<String>,

    /// The existing named range's id, by exact match. Mutually exclusive
    /// with `--name`. Find it with `drive sheets list-named-ranges`.
    #[arg(long, value_name = "ID")]
    pub id: Option<String>,

    /// Reports the gate verdict and the referencing-formula preview,
    /// without calling `spreadsheets.batchUpdate`.
    #[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 DeleteNamedRangeCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let opts = NamedRangeOptions {
            spreadsheet_id: self.spreadsheet_id,
            verb: NamedRangeVerb::DeleteNamedRange {
                name: self.name,
                id: self.id,
            },
            dry_run: self.dry_run,
            lease_token: self.lease.lease,
            ledger_path: helpers::resolve_ledger_path(self.dry_run)?,
        };
        run_named_range(client, &opts, &self.output).await
    }
}

/// Lists the named ranges in a spreadsheet.
///
/// Read-only and ungated, like `sheets list-protections` — needed so
/// `update-named-range`/`delete-named-range` are usable at all, since a
/// named range's current extent is otherwise invisible from the CLI.
#[derive(Parser)]
pub struct ListNamedRangesCommand {
    /// Spreadsheet id (the `/d/<ID>/` segment of a Sheets URL).
    pub spreadsheet_id: String,

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

impl ListNamedRangesCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let sheets = SheetsClient::from_drive_client(client)?;
        let api = SheetsApi::new(&sheets);
        let workbook = api
            .get_spreadsheet_with_named_ranges(&self.spreadsheet_id)
            .await?;
        if output_as(&workbook, &self.output)? {
            return Ok(());
        }
        let mut rows = Vec::new();
        for named in &workbook.named_ranges {
            let id = named.named_range_id.as_deref().unwrap_or("?");
            let sheet = sheet_title_by_id(&workbook, named.range.sheet_id)
                .unwrap_or_else(|| "?".to_string());
            rows.push(format!(
                "id {id}: {}  {}  sheet={sheet:?}",
                named.name,
                render_grid_range(&named.range)
            ));
        }
        helpers::print_list(&rows, "No named ranges.");
        Ok(())
    }
}

async fn run_named_range(
    client: &DriveClient,
    opts: &NamedRangeOptions,
    output: &OutputFormat,
) -> Result<()> {
    let sheets = SheetsClient::from_drive_client(client)?;
    let rules = helpers::active_account_rules()?;
    let outcome = named_range(client, &sheets, opts, &rules).await;
    if output_as(&outcome, output)? {
        return Ok(());
    }
    let lines: Vec<String> = describe_lines(&outcome)
        .into_iter()
        .map(|line| sanitize_for_terminal(&line))
        .collect();
    println!("{}", lines.join("\n"));
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::drive::auth::{DriveCredentials, DriveGrantedScopes};
    use crate::drive::sheets::client::SHEETS_API_URL;
    use crate::utils::secret::Secret;

    // `render_grid_range`/`sheet_title_by_id` are tested in `grid_range.rs`,
    // the module they're shared from.

    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,
        }
    }

    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
    }

    #[tokio::test]
    async fn list_named_ranges_prints_every_named_range() {
        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());
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/v4/spreadsheets/sheet-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "spreadsheetId": "sheet-1",
                    "properties": {"title": "Budget"},
                    "sheets": [{"properties": {"sheetId": 0, "title": "Sheet1"}}],
                    "namedRanges": [
                        {
                            "namedRangeId": "id-1",
                            "name": "Foo",
                            "range": {
                                "sheetId": 0,
                                "startRowIndex": 0,
                                "endRowIndex": 5,
                                "startColumnIndex": 0,
                                "endColumnIndex": 2,
                            },
                        },
                        {"namedRangeId": "id-2", "name": "Bar", "range": {"sheetId": 0}},
                    ],
                })),
            )
            .mount(&server)
            .await;

        let cmd = ListNamedRangesCommand {
            spreadsheet_id: "sheet-1".to_string(),
            output: crate::cli::drive::format::OutputFormat::Table,
        };
        assert!(cmd.execute(&client).await.is_ok());
    }

    #[tokio::test]
    async fn list_named_ranges_yaml_output_short_circuits_before_printing_lines() {
        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());
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/v4/spreadsheets/sheet-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "spreadsheetId": "sheet-1",
                    "properties": {"title": "Budget"},
                    "sheets": [{"properties": {"sheetId": 0, "title": "Sheet1"}}],
                    "namedRanges": [],
                })),
            )
            .mount(&server)
            .await;

        let cmd = ListNamedRangesCommand {
            spreadsheet_id: "sheet-1".to_string(),
            output: crate::cli::drive::format::OutputFormat::Yaml,
        };
        assert!(cmd.execute(&client).await.is_ok());
    }

    /// Mounts a Drive-file/parent-folder pair with no write-permission rules
    /// configured (`active_account_rules()` reads an unconfigured account —
    /// see `client_with_bootstrapped_token`'s `EnvGuard::clear_credentials`
    /// caller), so the gate refuses by default policy. That's enough to
    /// drive `Add`/`Update`/`DeleteNamedRangeCommand::execute` (and thus
    /// `run_named_range`) through their full CLI-level path — building
    /// `NamedRangeOptions`, calling `named_range`, and rendering the
    /// `describe_lines` output — without needing a lease or a workbook
    /// fetch, which a `Blocked` verdict never reaches.
    async fn mount_ungated_target(server: &wiremock::MockServer) {
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/sheet-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "sheet-1",
                    "name": "Budget",
                    "mimeType": crate::drive::types::GOOGLE_SHEET_MIME_TYPE,
                    "parents": ["folder-1"],
                })),
            )
            .mount(server)
            .await;
        wiremock::Mock::given(wiremock::matchers::method("GET"))
            .and(wiremock::matchers::path("/drive/v3/files/folder-1"))
            .respond_with(
                wiremock::ResponseTemplate::new(200).set_body_json(serde_json::json!({
                    "id": "folder-1",
                    "name": "folder-1",
                    "mimeType": "application/vnd.google-apps.folder",
                    "parents": [],
                })),
            )
            .mount(server)
            .await;
    }

    #[tokio::test]
    async fn add_named_range_command_runs_end_to_end() {
        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_ungated_target(&server).await;

        let cmd = AddNamedRangeCommand {
            spreadsheet_id: "sheet-1".to_string(),
            name: "Foo".to_string(),
            range: Some("A1:A5".to_string()),
            sheet: Some("Q1".to_string()),
            whole_sheet: false,
            write: helpers::StructureWriteArgs {
                dry_run: true,
                lease: crate::cli::drive::helpers::LeaseTokenArg { lease: None },
                output: crate::cli::drive::format::OutputFormat::Table,
            },
        };
        assert!(cmd.execute(&client).await.is_ok());
    }

    #[tokio::test]
    async fn update_named_range_command_runs_end_to_end() {
        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_ungated_target(&server).await;

        let cmd = UpdateNamedRangeCommand {
            spreadsheet_id: "sheet-1".to_string(),
            name: Some("Foo".to_string()),
            id: None,
            new_name: Some("Bar".to_string()),
            range: None,
            sheet: None,
            whole_sheet: false,
            write: helpers::StructureWriteArgs {
                dry_run: true,
                lease: crate::cli::drive::helpers::LeaseTokenArg { lease: None },
                output: crate::cli::drive::format::OutputFormat::Table,
            },
        };
        assert!(cmd.execute(&client).await.is_ok());
    }

    /// The `--id` selector's own end-to-end pass — mirrors
    /// `update_named_range_command_runs_end_to_end` but selects by id
    /// instead of by name (issue #1975).
    #[tokio::test]
    async fn update_named_range_command_by_id_runs_end_to_end() {
        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_ungated_target(&server).await;

        let cmd = UpdateNamedRangeCommand {
            spreadsheet_id: "sheet-1".to_string(),
            name: None,
            id: Some("id-1".to_string()),
            new_name: Some("Bar".to_string()),
            range: None,
            sheet: None,
            whole_sheet: false,
            write: helpers::StructureWriteArgs {
                dry_run: true,
                lease: crate::cli::drive::helpers::LeaseTokenArg { lease: None },
                output: crate::cli::drive::format::OutputFormat::Table,
            },
        };
        assert!(cmd.execute(&client).await.is_ok());
    }

    #[tokio::test]
    async fn delete_named_range_command_runs_end_to_end() {
        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_ungated_target(&server).await;

        let cmd = DeleteNamedRangeCommand {
            spreadsheet_id: "sheet-1".to_string(),
            name: Some("Foo".to_string()),
            id: None,
            dry_run: true,
            lease: crate::cli::drive::helpers::LeaseTokenArg { lease: None },
            output: crate::cli::drive::format::OutputFormat::Yaml,
        };
        assert!(cmd.execute(&client).await.is_ok());
    }

    /// The `--id` selector's own end-to-end pass — mirrors
    /// `delete_named_range_command_runs_end_to_end` but selects by id
    /// instead of by name (issue #1975).
    #[tokio::test]
    async fn delete_named_range_command_by_id_runs_end_to_end() {
        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_ungated_target(&server).await;

        let cmd = DeleteNamedRangeCommand {
            spreadsheet_id: "sheet-1".to_string(),
            name: None,
            id: Some("id-1".to_string()),
            dry_run: true,
            lease: crate::cli::drive::helpers::LeaseTokenArg { lease: None },
            output: crate::cli::drive::format::OutputFormat::Yaml,
        };
        assert!(cmd.execute(&client).await.is_ok());
    }

    /// clap's `ArgGroup` refuses `--name`/`--id` together and neither, for
    /// both `update-named-range` and `delete-named-range` (issue #1975).
    #[test]
    fn update_and_delete_named_range_require_exactly_one_of_name_or_id() {
        let err = UpdateNamedRangeCommand::try_parse_from(["update-named-range", "sheet-1"])
            .map(|_| ())
            .unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);

        let err = UpdateNamedRangeCommand::try_parse_from([
            "update-named-range",
            "sheet-1",
            "--name",
            "Foo",
            "--id",
            "id-1",
            "--new-name",
            "Bar",
        ])
        .map(|_| ())
        .unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);

        let err = DeleteNamedRangeCommand::try_parse_from(["delete-named-range", "sheet-1"])
            .map(|_| ())
            .unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);

        let err = DeleteNamedRangeCommand::try_parse_from([
            "delete-named-range",
            "sheet-1",
            "--name",
            "Foo",
            "--id",
            "id-1",
        ])
        .map(|_| ())
        .unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
    }
}