omni-dev 0.44.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
//! CLI commands for `omni-dev drive sheets add-dimension-group`/
//! `update-dimension-group`/`delete-dimension-group`/`list-dimension-groups`
//! (issue #1833).
//!
//! The first three are gated by
//! [`DriveOperation::SheetsStructure`](crate::drive::write_gate::DriveOperation::SheetsStructure)
//! (ADR-0084, following ADR-0082's own reasoning). `list-dimension-groups`
//! is a plain read, ungated like `list-bandings`.

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

use crate::cli::drive::format::{output_as, sanitize_for_terminal, OutputFormat};
use crate::cli::drive::helpers;
use crate::cli::drive::sheets::format::DimensionArg;
use crate::drive::client::DriveClient;
use crate::drive::sheets::api::SheetsApi;
use crate::drive::sheets::client::SheetsClient;
use crate::drive::sheets::dimension_group::{
    describe_lines, dimension_group, DimensionGroupOptions, DimensionGroupVerb,
};

/// Adds a new outline group — the collapsible +/- grouping bar — over a
/// span of rows or columns.
///
/// No client-side depth cap: the server derives the new group's depth from
/// how the span overlaps existing groups on the same axis, and no maximum
/// is documented; only the span itself is validated against the sheet's
/// current extent, matching `auto-resize-dimension`'s own flag shape.
#[derive(Parser)]
pub struct AddDimensionGroupCommand {
    /// Spreadsheet id (the `/d/<ID>/` segment of a Sheets URL).
    pub spreadsheet_id: String,

    /// Title of the sheet to modify.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// Rows or columns.
    #[arg(long, value_enum)]
    pub dimension: DimensionArg,

    /// 1-based first row/column, inclusive.
    #[arg(long, value_name = "N")]
    pub start: i64,

    /// 1-based last row/column, inclusive.
    #[arg(long, value_name = "N")]
    pub end: i64,

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

impl AddDimensionGroupCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let opts = DimensionGroupOptions {
            spreadsheet_id: self.spreadsheet_id,
            verb: DimensionGroupVerb::AddDimensionGroup {
                sheet: self.sheet,
                dimension: self.dimension.engine(),
                start: self.start,
                end: self.end,
            },
            dry_run: self.write.dry_run,
            lease_token: self.write.lease.lease,
            ledger_path: helpers::resolve_ledger_path(self.write.dry_run)?,
        };
        run_dimension_group(client, &opts, &self.write.output).await
    }
}

/// Changes an existing group's `collapsed` state — the only field this
/// crate ever updates, since the span is the group's identity and the
/// depth is server-derived. The target span may match more than one group
/// (the API creates this when a group is added over a span equal to an
/// existing one); `--depth` disambiguates, discovered via
/// `drive sheets list-dimension-groups`.
#[derive(Parser)]
pub struct UpdateDimensionGroupCommand {
    /// Spreadsheet id (the `/d/<ID>/` segment of a Sheets URL).
    pub spreadsheet_id: String,

    /// Title of the sheet the group is on.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// Rows or columns.
    #[arg(long, value_enum)]
    pub dimension: DimensionArg,

    /// 1-based first row/column, inclusive — identifies the group together
    /// with `--end`.
    #[arg(long, value_name = "N")]
    pub start: i64,

    /// 1-based last row/column, inclusive.
    #[arg(long, value_name = "N")]
    pub end: i64,

    /// Disambiguates which group at that exact span to update, when more
    /// than one exists at different depths. Omit when only one exists.
    #[arg(long, value_name = "N")]
    pub depth: Option<i64>,

    /// The new collapsed state: `true` hides the group's rows/columns,
    /// `false` shows them.
    // Required, unlike `format-cells`' optional `--bold`-style flags:
    // `update-dimension-group` changes nothing else, so there is no
    // "leave it unset" case. `bool` with `ArgAction::Set`, not
    // `Option<bool>`, so clap requires a value rather than treating a bare
    // `--collapsed` as a switch.
    #[arg(long, value_name = "BOOL", action = clap::ArgAction::Set)]
    pub collapsed: bool,

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

impl UpdateDimensionGroupCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let opts = DimensionGroupOptions {
            spreadsheet_id: self.spreadsheet_id,
            verb: DimensionGroupVerb::UpdateDimensionGroup {
                sheet: self.sheet,
                dimension: self.dimension.engine(),
                start: self.start,
                end: self.end,
                depth: self.depth,
                collapsed: self.collapsed,
            },
            dry_run: self.write.dry_run,
            lease_token: self.write.lease.lease,
            ledger_path: helpers::resolve_ledger_path(self.write.dry_run)?,
        };
        run_dimension_group(client, &opts, &self.write.output).await
    }
}

/// Removes an outline group. Requires an **exact** span match among the
/// groups `list-dimension-groups` would show — the API's own partial-span
/// delete (which decrements an overlapping group's depth rather than
/// removing anything) is not exposed.
#[derive(Parser)]
pub struct DeleteDimensionGroupCommand {
    /// Spreadsheet id (the `/d/<ID>/` segment of a Sheets URL).
    pub spreadsheet_id: String,

    /// Title of the sheet the group is on.
    #[arg(long, value_name = "NAME")]
    pub sheet: String,

    /// Rows or columns.
    #[arg(long, value_enum)]
    pub dimension: DimensionArg,

    /// 1-based first row/column, inclusive — identifies the group together
    /// with `--end`.
    #[arg(long, value_name = "N")]
    pub start: i64,

    /// 1-based last row/column, inclusive.
    #[arg(long, value_name = "N")]
    pub end: i64,

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

impl DeleteDimensionGroupCommand {
    /// Runs the command against the shared Drive client.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let opts = DimensionGroupOptions {
            spreadsheet_id: self.spreadsheet_id,
            verb: DimensionGroupVerb::DeleteDimensionGroup {
                sheet: self.sheet,
                dimension: self.dimension.engine(),
                start: self.start,
                end: self.end,
            },
            dry_run: self.write.dry_run,
            lease_token: self.write.lease.lease,
            ledger_path: helpers::resolve_ledger_path(self.write.dry_run)?,
        };
        run_dimension_group(client, &opts, &self.write.output).await
    }
}

/// Lists the row and column outline groups in a spreadsheet.
///
/// Read-only and ungated, like `list-bandings` — needed so
/// `update-dimension-group`/`delete-dimension-group` are usable at all,
/// since a group's `(range, depth)` is otherwise invisible from the CLI.
#[derive(Parser)]
pub struct ListDimensionGroupsCommand {
    /// 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 ListDimensionGroupsCommand {
    /// 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_dimension_groups(&self.spreadsheet_id)
            .await?;
        if output_as(&workbook, &self.output)? {
            return Ok(());
        }
        let mut rows = Vec::new();
        for sheet in &workbook.sheets {
            for (axis, groups) in [
                ("rows", &sheet.row_groups),
                ("columns", &sheet.column_groups),
            ] {
                for group in groups {
                    let span = format!("{}:{}", group.range.start_index + 1, group.range.end_index);
                    rows.push(format!(
                        "{axis} {span}  depth={}  collapsed={}  sheet={}",
                        group.depth,
                        group.collapsed,
                        sheet.title()
                    ));
                }
            }
        }
        helpers::print_list(&rows, "No dimension groups.");
        Ok(())
    }
}

async fn run_dimension_group(
    client: &DriveClient,
    opts: &DimensionGroupOptions,
    output: &OutputFormat,
) -> Result<()> {
    let sheets = SheetsClient::from_drive_client(client)?;
    let rules = helpers::active_account_rules()?;
    let outcome = dimension_group(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;

    #[test]
    fn dimension_arg_converts_to_the_matching_dimension() {
        assert_eq!(
            DimensionArg::Rows.engine(),
            crate::drive::sheets::types::Dimension::Rows
        );
        assert_eq!(
            DimensionArg::Columns.engine(),
            crate::drive::sheets::types::Dimension::Columns
        );
    }

    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_dimension_groups_prints_every_group() {
        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"},
                        "rowGroups": [
                            {"range": {"sheetId": 0, "dimension": "ROWS", "startIndex": 4, "endIndex": 9}, "depth": 1},
                        ],
                        "columnGroups": [
                            {"range": {"sheetId": 0, "dimension": "COLUMNS", "startIndex": 0, "endIndex": 3}, "depth": 1, "collapsed": true},
                        ],
                    }],
                })),
            )
            .mount(&server)
            .await;

        let cmd = ListDimensionGroupsCommand {
            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_dimension_groups_reads_a_group_on_the_first_sheet_starting_at_row_one() {
        // Issue #1929: a row group on the first sheet (`sheetId: 0`)
        // starting at row 1 (`startIndex: 0`) has both fields omitted by
        // proto3 — contrast the fixture above, which spells every index
        // explicitly (`"sheetId": 0, ..., "startIndex": 0`) and so never
        // exercised this.
        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": {"title": "Sheet1"},
                        "rowGroups": [
                            {"range": {"dimension": "ROWS", "endIndex": 3}, "depth": 1},
                        ],
                    }],
                })),
            )
            .mount(&server)
            .await;

        let cmd = ListDimensionGroupsCommand {
            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_dimension_groups_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"}}],
                })),
            )
            .mount(&server)
            .await;

        let cmd = ListDimensionGroupsCommand {
            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, so the gate refuses by default policy. Enough to
    /// drive `Add`/`Update`/`DeleteDimensionGroupCommand::execute` (and
    /// thus `run_dimension_group`) through their full CLI-level path —
    /// building `DimensionGroupOptions`, calling `dimension_group`, 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;
    }

    fn no_lease() -> crate::cli::drive::helpers::LeaseTokenArg {
        crate::cli::drive::helpers::LeaseTokenArg { lease: None }
    }

    #[tokio::test]
    async fn add_dimension_group_command_reaches_the_engine_under_a_blocked_gate() {
        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 = AddDimensionGroupCommand {
            spreadsheet_id: "sheet-1".to_string(),
            sheet: "Sheet1".to_string(),
            dimension: DimensionArg::Rows,
            start: 1,
            end: 5,
            write: helpers::StructureWriteArgs {
                dry_run: false,
                lease: no_lease(),
                output: crate::cli::drive::format::OutputFormat::Table,
            },
        };
        assert!(cmd.execute(&client).await.is_ok());
    }

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

        let cmd = AddDimensionGroupCommand {
            spreadsheet_id: "sheet-1".to_string(),
            sheet: "Sheet1".to_string(),
            dimension: DimensionArg::Rows,
            start: 1,
            end: 5,
            write: helpers::StructureWriteArgs {
                dry_run: false,
                lease: no_lease(),
                output: crate::cli::drive::format::OutputFormat::Yaml,
            },
        };
        assert!(cmd.execute(&client).await.is_ok());
    }

    #[tokio::test]
    async fn update_dimension_group_command_reaches_the_engine_under_a_blocked_gate() {
        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 = UpdateDimensionGroupCommand {
            spreadsheet_id: "sheet-1".to_string(),
            sheet: "Sheet1".to_string(),
            dimension: DimensionArg::Rows,
            start: 1,
            end: 5,
            depth: None,
            collapsed: true,
            write: helpers::StructureWriteArgs {
                dry_run: false,
                lease: no_lease(),
                output: crate::cli::drive::format::OutputFormat::Table,
            },
        };
        assert!(cmd.execute(&client).await.is_ok());
    }

    #[tokio::test]
    async fn delete_dimension_group_command_reaches_the_engine_under_a_blocked_gate() {
        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 = DeleteDimensionGroupCommand {
            spreadsheet_id: "sheet-1".to_string(),
            sheet: "Sheet1".to_string(),
            dimension: DimensionArg::Rows,
            start: 1,
            end: 5,
            write: helpers::StructureWriteArgs {
                dry_run: false,
                lease: no_lease(),
                output: crate::cli::drive::format::OutputFormat::Table,
            },
        };
        assert!(cmd.execute(&client).await.is_ok());
    }
}