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
//! CLI command for `omni-dev drive docs read`.

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

use crate::cli::drive::format::{output_as, sanitize_for_terminal, OutputFormat};
use crate::drive::client::DriveClient;
use crate::drive::docs::api::{DocsApi, SuggestionsViewMode};
use crate::drive::docs::client::DocsClient;
use crate::drive::docs::read::{read, ReadOptions, ReadOutcome, SegmentContent};
use crate::drive::docs::structure::DocElement;
use crate::drive::docs::target;
use crate::drive::files_api::FilesApi;

/// Reads a document's structural elements with their index ranges.
///
/// `drive read --content` is the *prose* channel — it exports a Doc to
/// markdown. This is the *model* channel: it reports each element's
/// `[start, end)` index range, which is the only way to learn an index, and
/// the document's `revisionId`. An export is a one-way rendering with no
/// path back to either.
#[derive(Parser)]
pub struct ReadCommand {
    /// Document id (the `/d/<ID>/` segment of a Docs URL).
    pub document_id: String,

    /// Restrict output to one tab id (see `drive docs info`).
    #[arg(long)]
    pub tab: Option<String>,

    /// Which suggestion view the text and indices are reported against.
    #[arg(long, value_enum, default_value_t = SuggestionsViewArg::Default)]
    pub suggestions_view: SuggestionsViewArg,

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

/// `clap` mirror of the engine's [`SuggestionsViewMode`].
///
/// The same engine/CLI split `ValueRenderOption`/`RenderArg` and
/// `DriveOperation`/`OperationArg` use: the engine enum stays `clap`-free so
/// a non-CLI caller never depends on the argument parser.
#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum SuggestionsViewArg {
    /// Whatever the caller's access level implies.
    Default,
    /// Suggestions shown inline, as tracked changes.
    Inline,
    /// The document as it would be with every suggestion accepted.
    Accepted,
    /// The document as it would be with every suggestion rejected.
    Without,
}

impl From<SuggestionsViewArg> for SuggestionsViewMode {
    fn from(arg: SuggestionsViewArg) -> Self {
        match arg {
            SuggestionsViewArg::Default => Self::DefaultForCurrentAccess,
            SuggestionsViewArg::Inline => Self::Inline,
            SuggestionsViewArg::Accepted => Self::PreviewAccepted,
            SuggestionsViewArg::Without => Self::PreviewWithoutSuggestions,
        }
    }
}

impl ReadCommand {
    /// Runs the command, deriving a Docs client from the shared Drive one.
    pub async fn execute(self, client: &DriveClient) -> Result<()> {
        let docs = DocsClient::from_drive_client(client)?;
        let opts = ReadOptions {
            document_id: self.document_id,
            tab: self.tab,
            suggestions: self.suggestions_view.into(),
        };
        run_read(client, &docs, &opts, &self.output).await
    }
}

/// Reads the document and renders it.
///
/// Split from [`ReadCommand::execute`] so tests can inject wiremock clients
/// without going through the credential-loading path.
async fn run_read(
    drive: &DriveClient,
    docs: &DocsClient,
    opts: &ReadOptions,
    output: &OutputFormat,
) -> Result<()> {
    let outcome = match read(&DocsApi::new(docs), opts).await {
        Ok(outcome) => outcome,
        // Only now is a `files.get` worth spending — see
        // `target::explain_failure` for why classification is lazy.
        Err(err) => {
            return Err(target::explain_failure(
                &FilesApi::new(drive),
                &opts.document_id,
                "read",
                err,
            )
            .await)
        }
    };
    if output_as(&outcome, output)? {
        return Ok(());
    }
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();
    render_read_table(&outcome, &mut handle)
}

/// Renders one line per element, index-first, indented by nesting depth.
///
/// Element text is passed through `sanitize_for_terminal`, which is a
/// deliberate divergence from `sheets read`'s verbatim CSV. CSV is an
/// interchange format that must round-trip, so stripping control characters
/// there would corrupt real data; this is an *orientation* view whose whole
/// value is column alignment, and a soft line break (`\v`, which really does
/// occur inside Docs paragraph text) or an escape sequence in
/// server-controlled text would destroy it. `-o json` is the unsanitised
/// channel and is the one to use for content.
fn render_read_table(outcome: &ReadOutcome, out: &mut dyn std::io::Write) -> Result<()> {
    let ctx = "Failed to write docs read output";
    let multi_tab = outcome.tabs.len() > 1;

    for (position, tab) in outcome.tabs.iter().enumerate() {
        if multi_tab {
            if position > 0 {
                writeln!(out).context(ctx)?;
            }
            let id = tab.tab_id.as_deref().unwrap_or("(no id)");
            let title = tab.title.as_deref().unwrap_or("");
            writeln!(
                out,
                "# {} {}",
                sanitize_for_terminal(id),
                sanitize_for_terminal(title)
            )
            .context(ctx)?;
        }

        render_elements(&tab.elements, out)?;

        for (kind, segments) in tab.segments_by_kind() {
            render_segments(kind.as_str(), segments, out)?;
        }
    }
    Ok(())
}

/// Renders every header, footer or footnote segment of one kind, each under
/// its own `## <label> <segmentId>` block.
fn render_segments(
    label: &str,
    segments: &[SegmentContent],
    out: &mut dyn std::io::Write,
) -> Result<()> {
    let ctx = "Failed to write docs read output";
    for segment in segments {
        writeln!(
            out,
            "## {label} {}",
            sanitize_for_terminal(&segment.segment_id)
        )
        .context(ctx)?;
        render_elements(&segment.elements, out)?;
    }
    Ok(())
}

/// Renders one line per element, index-first, indented by nesting depth.
///
/// Element text is passed through `sanitize_for_terminal`, which is a
/// deliberate divergence from `sheets read`'s verbatim CSV. CSV is an
/// interchange format that must round-trip, so stripping control characters
/// there would corrupt real data; this is an *orientation* view whose whole
/// value is column alignment, and a soft line break (`\v`, which really does
/// occur inside Docs paragraph text) or an escape sequence in
/// server-controlled text would destroy it. `-o json` is the unsanitised
/// channel and is the one to use for content.
fn render_elements(elements: &[DocElement], out: &mut dyn std::io::Write) -> Result<()> {
    let ctx = "Failed to write docs read output";

    if elements.is_empty() {
        writeln!(out, "(empty)").context(ctx)?;
        return Ok(());
    }

    // Widths come from the data so the columns line up for this document
    // rather than for a hypothetical worst case.
    let start_w = elements
        .iter()
        .map(|e| e.start_index.to_string().len())
        .max()
        .unwrap_or(5)
        .max(5);
    let end_w = elements
        .iter()
        .map(|e| e.end_index.to_string().len())
        .max()
        .unwrap_or(3)
        .max(3);
    let kind_w = elements
        .iter()
        .map(|e| e.kind.as_str().len() + e.depth() * 2)
        .max()
        .unwrap_or(4)
        .max(4);
    let style_w = elements
        .iter()
        .filter_map(|e| e.style.as_ref().map(String::len))
        .max()
        .unwrap_or(5)
        .max(5);

    writeln!(
        out,
        "{:>start_w$}  {:>end_w$}  {:<kind_w$}  {:<style_w$}  TEXT",
        "START", "END", "KIND", "STYLE"
    )
    .context(ctx)?;

    for element in elements {
        let kind = format!("{}{}", "  ".repeat(element.depth()), element.kind.as_str());
        // A table's dimensions belong on its container row: it is the one
        // element kind whose text is empty by construction, so the column
        // would otherwise be dead space on exactly the row a reader most
        // wants to identify.
        let text = match (element.rows, element.columns) {
            (Some(rows), Some(cols)) => format!("{rows}x{cols}"),
            _ => sanitize_for_terminal(&element.text),
        };
        writeln!(
            out,
            "{:>start_w$}  {:>end_w$}  {:<kind_w$}  {:<style_w$}  {}",
            element.start_index,
            element.end_index,
            kind,
            element.style.as_deref().unwrap_or(""),
            text
        )
        .context(ctx)?;
    }
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::drive::docs::read::TabContent;
    use crate::drive::docs::structure::{DocElement, ElementKind};

    fn element(
        start: i64,
        end: i64,
        kind: ElementKind,
        path: Vec<usize>,
        style: Option<&str>,
        text: &str,
    ) -> DocElement {
        DocElement {
            start_index: start,
            end_index: end,
            kind,
            path,
            style: style.map(str::to_string),
            list_id: None,
            rows: None,
            columns: None,
            text: text.to_string(),
        }
    }

    fn outcome(tabs: Vec<TabContent>) -> ReadOutcome {
        ReadOutcome {
            document_id: "d1".to_string(),
            title: Some("Doc".to_string()),
            revision_id: Some("rev-1".to_string()),
            tabs,
        }
    }

    fn tab(id: Option<&str>, title: Option<&str>, elements: Vec<DocElement>) -> TabContent {
        TabContent {
            named_ranges: std::collections::BTreeMap::default(),
            tab_id: id.map(str::to_string),
            title: title.map(str::to_string),
            nesting_level: 0,
            elements,
            headers: Vec::new(),
            footers: Vec::new(),
            footnotes: Vec::new(),
        }
    }

    fn segment(id: &str, elements: Vec<DocElement>) -> SegmentContent {
        SegmentContent {
            segment_id: id.to_string(),
            elements,
        }
    }

    fn render(outcome: &ReadOutcome) -> String {
        let mut buf = Vec::new();
        render_read_table(outcome, &mut buf).unwrap();
        String::from_utf8(buf).unwrap()
    }

    #[test]
    fn render_emits_one_line_per_element_with_its_index_range() {
        let text = render(&outcome(vec![tab(
            None,
            None,
            vec![
                element(
                    1,
                    10,
                    ElementKind::Paragraph,
                    vec![0],
                    Some("HEADING_1"),
                    "Overview",
                ),
                element(
                    10,
                    20,
                    ElementKind::Paragraph,
                    vec![1],
                    Some("NORMAL_TEXT"),
                    "Body",
                ),
            ],
        )]));
        assert!(text.contains("START"), "{text}");
        assert!(text.contains("Overview"), "{text}");
        assert!(text.contains("HEADING_1"), "{text}");
        // One header line plus two element lines.
        assert_eq!(text.lines().count(), 3, "{text}");
    }

    #[test]
    fn render_indents_elements_nested_in_a_table() {
        let text = render(&outcome(vec![tab(
            None,
            None,
            vec![
                element(1, 40, ElementKind::Table, vec![0], None, ""),
                element(
                    3,
                    10,
                    ElementKind::Paragraph,
                    vec![0, 0, 0, 0],
                    None,
                    "Name",
                ),
            ],
        )]));
        let nested = text.lines().find(|l| l.contains("Name")).unwrap();
        assert!(nested.contains("      paragraph"), "{nested}");
    }

    #[test]
    fn render_shows_table_dimensions_on_the_container_row() {
        let mut table = element(1, 40, ElementKind::Table, vec![0], None, "");
        table.rows = Some(3);
        table.columns = Some(2);
        let text = render(&outcome(vec![tab(None, None, vec![table])]));
        assert!(text.contains("3x2"), "{text}");
    }

    /// The documented divergence from `sheets read`: this is an orientation
    /// view whose value is alignment, so control bytes are stripped rather
    /// than passed through.
    #[test]
    fn render_sanitizes_element_text() {
        let text = render(&outcome(vec![tab(
            None,
            None,
            vec![element(
                1,
                10,
                ElementKind::Paragraph,
                vec![0],
                None,
                "before\u{1b}[31mred\nnext",
            )],
        )]));
        assert!(!text.contains('\u{1b}'), "{text}");
        // One header line plus one element line — the embedded newline must
        // not have spawned a second row.
        assert_eq!(text.lines().count(), 2, "{text}");
    }

    #[test]
    fn multiple_tabs_get_a_commented_header_and_a_blank_separator() {
        let text = render(&outcome(vec![
            tab(
                Some("t.0"),
                Some("One"),
                vec![element(1, 5, ElementKind::Paragraph, vec![0], None, "a")],
            ),
            tab(
                Some("t.1"),
                Some("Two"),
                vec![element(1, 5, ElementKind::Paragraph, vec![0], None, "b")],
            ),
        ]));
        assert!(text.contains("# t.0 One"), "{text}");
        assert!(text.contains("# t.1 Two"), "{text}");
        assert!(text.contains("\n\n# t.1"), "{text}");
    }

    #[test]
    fn a_single_tab_renders_without_a_header_line() {
        let text = render(&outcome(vec![tab(
            Some("t.0"),
            Some("One"),
            vec![element(1, 5, ElementKind::Paragraph, vec![0], None, "a")],
        )]));
        assert!(!text.contains("# t.0"), "{text}");
    }

    #[test]
    fn an_empty_tab_says_so_rather_than_printing_a_bare_header() {
        let text = render(&outcome(vec![tab(None, None, vec![])]));
        assert!(text.contains("(empty)"), "{text}");
    }

    /// A document with no segments renders identically to today — no stray
    /// blocks for a tab that has none.
    #[test]
    fn a_tab_with_no_segments_renders_no_segment_blocks() {
        let text = render(&outcome(vec![tab(
            None,
            None,
            vec![element(1, 5, ElementKind::Paragraph, vec![0], None, "a")],
        )]));
        assert!(!text.contains("## header"), "{text}");
        assert!(!text.contains("## footer"), "{text}");
        assert!(!text.contains("## footnote"), "{text}");
    }

    #[test]
    fn headers_footers_and_footnotes_render_as_labeled_blocks_after_the_body() {
        let mut content = tab(
            None,
            None,
            vec![element(1, 5, ElementKind::Paragraph, vec![0], None, "body")],
        );
        content.headers = vec![segment(
            "h1",
            vec![element(
                0,
                8,
                ElementKind::Paragraph,
                vec![0],
                None,
                "Header",
            )],
        )];
        content.footers = vec![segment(
            "f1",
            vec![element(
                0,
                8,
                ElementKind::Paragraph,
                vec![0],
                None,
                "Footer",
            )],
        )];
        content.footnotes = vec![segment(
            "n1",
            vec![element(0, 5, ElementKind::Paragraph, vec![0], None, "Note")],
        )];
        let text = render(&outcome(vec![content]));

        assert!(text.contains("## header h1"), "{text}");
        assert!(text.contains("## footer f1"), "{text}");
        assert!(text.contains("## footnote n1"), "{text}");
        // Body block precedes the segment blocks.
        let body_pos = text.find("body").unwrap();
        let header_pos = text.find("## header").unwrap();
        assert!(body_pos < header_pos, "{text}");
    }

    #[test]
    fn suggestions_view_arg_maps_onto_the_engine_option() {
        for (arg, mode) in [
            (
                SuggestionsViewArg::Default,
                SuggestionsViewMode::DefaultForCurrentAccess,
            ),
            (SuggestionsViewArg::Inline, SuggestionsViewMode::Inline),
            (
                SuggestionsViewArg::Accepted,
                SuggestionsViewMode::PreviewAccepted,
            ),
            (
                SuggestionsViewArg::Without,
                SuggestionsViewMode::PreviewWithoutSuggestions,
            ),
        ] {
            assert_eq!(SuggestionsViewMode::from(arg), mode, "{arg:?}");
        }
    }
}