omni-dev 0.41.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
//! Shared output-format types for the CLI.
//!
//! One `-o/--output <format>` convention is used across the whole CLI surface
//! (issue #1125). This module owns the machine-readable [`OutputFormat`] enum
//! and the rendering machinery (`write_output`/`output_as` and the
//! [`JsonlSerialize`] trait); command modules bind `-o/--output` to this enum
//! and delegate serialization here, rendering their own `Table` branch when
//! `output_as` returns `Ok(false)`.
//!
//! Atlassian-specific `JsonlSerialize` impls for its collection wrapper types
//! live in [`crate::cli::atlassian::format`] (they need the wrapper types); this
//! module carries only the trait, the blanket `Vec<T>` impl, and the generic
//! helpers.

use std::io::Write;

use anyhow::{Context, Result};
use clap::ValueEnum;
use serde::Serialize;

/// Display format for list/table commands.
#[derive(Clone, Debug, Default, ValueEnum)]
pub enum OutputFormat {
    /// Human-readable table.
    #[default]
    Table,
    /// JSON.
    Json,
    /// YAML (single document).
    Yaml,
    /// YAML stream (`---`-separated multi-document).
    Yamls,
    /// JSON Lines: one compact JSON object per line, streaming-friendly.
    Jsonl,
}

/// A two-way `-o/--output` selector for commands that render either a
/// human-readable table or machine-readable JSON (no YAML/JSONL variants).
///
/// Used by the daemon-facing status/list commands that historically took a
/// boolean `--json` flag (issue #1125).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, ValueEnum)]
#[value(rename_all = "lowercase")]
pub enum TableOrJson {
    /// Human-readable table.
    #[default]
    Table,
    /// Pretty-printed JSON.
    Json,
}

/// Writes a value as newline-terminated JSON Lines.
///
/// For collection-like types, implementations emit one JSON object per
/// contained item. For scalar types, implementations emit the value as a
/// single JSON line.
pub trait JsonlSerialize {
    /// Writes the value as JSONL to `out`, newline-terminated.
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()>;
}

/// Strips control characters (C0, DEL, C1) from a server- or
/// writer-supplied string before it reaches the terminal.
///
/// Every CSI escape sequence starts with ESC (a C0 control character), so
/// this neutralizes embedded ANSI escape sequences at the source without
/// needing sequence-aware parsing; it also strips embedded newlines that
/// could otherwise be used to spoof extra output rows. The one place a
/// newline legitimately appears in rendered output is the record separator
/// the renderer itself writes between rows — never a value coming from a
/// sanitized field (#1137).
///
/// Also strips the bidirectional-control code points (LRE/RLE/PDF/LRO/RLO,
/// LRI/RLI/FSI/PDI, LRM/RLM) — a Trojan-Source-style spoofing vector
/// (CVE-2021-42574) distinct from escape injection, since a terminal that
/// honors them can visually reorder rendered text (e.g. a filename crafted
/// so `evil.exe` displays as `exe.live`). These are the only code points
/// pulled from Unicode category `Cf`; the rest of `Cf` (e.g. ZWJ in emoji
/// sequences, joiners in Arabic/Indic text) is left alone since stripping
/// it would mangle otherwise-valid international text (#1552).
pub fn sanitize_for_terminal(s: &str) -> String {
    s.chars()
        .filter(|c| !c.is_control() && !is_bidi_control(*c))
        .collect()
}

/// True for the Unicode bidirectional-control code points: LRE/RLE/PDF/LRO/RLO
/// (U+202A–U+202E), LRI/RLI/FSI/PDI (U+2066–U+2069), and LRM/RLM (U+200E/U+200F).
fn is_bidi_control(c: char) -> bool {
    matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}' | '\u{200E}' | '\u{200F}')
}

/// Writes each item in an iterator as a single compact JSON line.
pub fn write_items_jsonl<'a, I, T>(items: I, out: &mut dyn Write) -> Result<()>
where
    I: IntoIterator<Item = &'a T>,
    T: Serialize + 'a,
{
    for item in items {
        let line = serde_json::to_string(item).context("Failed to serialize as JSON")?;
        writeln!(out, "{line}").context("Failed to write JSONL line")?;
    }
    Ok(())
}

/// Writes a single serializable value as one compact JSON line.
pub fn write_scalar_jsonl<T: Serialize>(item: &T, out: &mut dyn Write) -> Result<()> {
    let line = serde_json::to_string(item).context("Failed to serialize as JSON")?;
    writeln!(out, "{line}").context("Failed to write JSONL line")?;
    Ok(())
}

impl<T: Serialize> JsonlSerialize for Vec<T> {
    fn write_jsonl(&self, out: &mut dyn Write) -> Result<()> {
        write_items_jsonl(self.iter(), out)
    }
}

/// Writes `data` to `out` in the requested format.
///
/// Returns `Ok(true)` when `data` was written (json/yaml/yamls/jsonl), `Ok(false)`
/// when `format` is `Table` (the caller is expected to render its own table).
pub fn write_output<T: Serialize + JsonlSerialize>(
    data: &T,
    format: &OutputFormat,
    out: &mut dyn Write,
) -> Result<bool> {
    match format {
        OutputFormat::Table => Ok(false),
        OutputFormat::Json => {
            let rendered =
                serde_json::to_string_pretty(data).context("Failed to serialize as JSON")?;
            writeln!(out, "{rendered}").context("Failed to write JSON output")?;
            Ok(true)
        }
        OutputFormat::Yaml => {
            let rendered = serde_yaml::to_string(data).context("Failed to serialize as YAML")?;
            write!(out, "{rendered}").context("Failed to write YAML output")?;
            Ok(true)
        }
        OutputFormat::Yamls => {
            let rendered = format_yaml_stream(data)?;
            write!(out, "{rendered}").context("Failed to write YAML stream output")?;
            Ok(true)
        }
        OutputFormat::Jsonl => {
            data.write_jsonl(out)?;
            Ok(true)
        }
    }
}

/// Serializes a single YAML value as one `---`-prefixed document.
fn yaml_stream_doc(value: &serde_yaml::Value) -> Result<String> {
    let s = serde_yaml::to_string(value).context("Failed to serialize YAML stream item")?;
    Ok(format!("---\n{s}"))
}

/// Serializes data as a YAML multi-document stream.
///
/// If the serialized value is a sequence, each element is emitted as its own
/// `---`-prefixed YAML document. Otherwise the whole value is emitted as a
/// single `---`-prefixed document. The result always ends with a newline.
fn format_yaml_stream<T: Serialize>(data: &T) -> Result<String> {
    match serde_yaml::to_value(data).context("Failed to serialize as YAML stream")? {
        serde_yaml::Value::Sequence(items) => items.iter().map(yaml_stream_doc).collect(),
        other => yaml_stream_doc(&other),
    }
}

/// Serializes data in the requested output format to stdout.
/// Returns `Ok(true)` if data was printed (json/yaml/yamls/jsonl), `Ok(false)`
/// if the caller should handle table output.
pub fn output_as<T: Serialize + JsonlSerialize>(data: &T, format: &OutputFormat) -> Result<bool> {
    let stdout = std::io::stdout();
    let mut handle = stdout.lock();
    write_output(data, format, &mut handle)
}

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

    // ── sanitize_for_terminal ──────────────────────────────────────

    #[test]
    fn sanitize_for_terminal_leaves_clean_string_unchanged() {
        assert_eq!(sanitize_for_terminal("report.pdf"), "report.pdf");
    }

    #[test]
    fn sanitize_for_terminal_strips_ansi_escape_sequence() {
        assert_eq!(sanitize_for_terminal("evil\x1b[31mrepo"), "evil[31mrepo");
    }

    #[test]
    fn sanitize_for_terminal_strips_c0_c1_and_del_control_bytes() {
        let input = "a\rb\x07c\u{7f}d\u{9b}e";
        assert_eq!(sanitize_for_terminal(input), "abcde");
    }

    #[test]
    fn sanitize_for_terminal_strips_embedded_newlines() {
        assert_eq!(sanitize_for_terminal("line1\nline2"), "line1line2");
    }

    #[test]
    fn sanitize_for_terminal_strips_bidi_override_characters() {
        let input = "evil\u{202E}exe.live";
        assert_eq!(sanitize_for_terminal(input), "evilexe.live");
    }

    #[test]
    fn sanitize_for_terminal_strips_all_bidi_control_code_points() {
        let input = "a\u{202A}b\u{202B}c\u{202C}d\u{202D}e\u{202E}f\u{2066}g\u{2067}h\u{2068}i\u{2069}j\u{200E}k\u{200F}l";
        assert_eq!(sanitize_for_terminal(input), "abcdefghijkl");
    }

    #[test]
    fn sanitize_for_terminal_leaves_other_format_characters_unchanged() {
        // Zero-width joiner (used in emoji ZWJ sequences) is `Cf` but not a
        // bidi control, so it must survive.
        let input = "\u{1F468}\u{200D}\u{1F469}";
        assert_eq!(sanitize_for_terminal(input), input);
    }

    #[test]
    fn output_default_is_table() {
        assert!(matches!(OutputFormat::default(), OutputFormat::Table));
    }

    #[test]
    fn output_json_variant() {
        assert!(matches!(OutputFormat::Json, OutputFormat::Json));
    }

    #[test]
    fn output_yaml_variant() {
        assert!(matches!(OutputFormat::Yaml, OutputFormat::Yaml));
    }

    #[test]
    fn output_yamls_variant() {
        assert!(matches!(OutputFormat::Yamls, OutputFormat::Yamls));
    }

    #[test]
    fn output_jsonl_variant() {
        assert!(matches!(OutputFormat::Jsonl, OutputFormat::Jsonl));
    }

    #[test]
    fn output_debug_format() {
        assert_eq!(format!("{:?}", OutputFormat::Jsonl), "Jsonl");
    }

    #[test]
    fn output_clone() {
        let format = OutputFormat::Jsonl;
        let cloned = format;
        assert!(matches!(cloned, OutputFormat::Jsonl));
    }

    // ── output_as ──────────────────────────────────────────────────

    #[test]
    fn output_as_table_returns_false() {
        let data = vec![1, 2, 3];
        assert!(!output_as(&data, &OutputFormat::Table).unwrap());
    }

    #[test]
    fn output_as_json_returns_true() {
        let data = vec![1, 2, 3];
        assert!(output_as(&data, &OutputFormat::Json).unwrap());
    }

    #[test]
    fn output_as_yaml_returns_true() {
        let data = vec![1, 2, 3];
        assert!(output_as(&data, &OutputFormat::Yaml).unwrap());
    }

    #[test]
    fn output_as_yamls_returns_true() {
        let data = vec![1, 2, 3];
        assert!(output_as(&data, &OutputFormat::Yamls).unwrap());
    }

    #[test]
    fn output_as_jsonl_returns_true() {
        let data = vec![1, 2, 3];
        assert!(output_as(&data, &OutputFormat::Jsonl).unwrap());
    }

    // ── write_items_jsonl / Vec impl ───────────────────────────────

    #[test]
    fn vec_jsonl_empty_emits_nothing() {
        let data: Vec<i32> = vec![];
        let mut buf = Vec::new();
        data.write_jsonl(&mut buf).unwrap();
        assert_eq!(buf, b"");
    }

    #[test]
    fn vec_jsonl_emits_one_line_per_item() {
        let data = vec![1_i32, 2, 3];
        let mut buf = Vec::new();
        data.write_jsonl(&mut buf).unwrap();
        assert_eq!(String::from_utf8(buf).unwrap(), "1\n2\n3\n");
    }

    #[test]
    fn vec_jsonl_emits_compact_objects() {
        #[derive(Serialize)]
        struct Item {
            key: &'static str,
            val: u32,
        }
        let data = vec![Item { key: "a", val: 1 }, Item { key: "b", val: 2 }];
        let mut buf = Vec::new();
        data.write_jsonl(&mut buf).unwrap();
        let out = String::from_utf8(buf).unwrap();
        assert_eq!(
            out,
            "{\"key\":\"a\",\"val\":1}\n{\"key\":\"b\",\"val\":2}\n"
        );
    }

    #[test]
    fn write_items_jsonl_over_slice() {
        let data = [10_i32, 20];
        let mut buf = Vec::new();
        write_items_jsonl(data.iter(), &mut buf).unwrap();
        assert_eq!(String::from_utf8(buf).unwrap(), "10\n20\n");
    }

    #[test]
    fn write_scalar_jsonl_emits_one_line() {
        #[derive(Serialize)]
        struct Scalar {
            name: &'static str,
        }
        let item = Scalar { name: "solo" };
        let mut buf = Vec::new();
        write_scalar_jsonl(&item, &mut buf).unwrap();
        assert_eq!(String::from_utf8(buf).unwrap(), "{\"name\":\"solo\"}\n");
    }

    // ── format_yaml_stream ─────────────────────────────────────────

    #[derive(serde::Serialize)]
    struct Issue {
        key: &'static str,
        summary: &'static str,
    }

    #[test]
    fn yaml_stream_emits_one_doc_per_sequence_item() {
        let data = vec![
            Issue {
                key: "PROJ-1",
                summary: "Fix login",
            },
            Issue {
                key: "PROJ-2",
                summary: "Add feature",
            },
        ];
        let out = format_yaml_stream(&data).unwrap();
        assert_eq!(
            out,
            "---\nkey: PROJ-1\nsummary: Fix login\n---\nkey: PROJ-2\nsummary: Add feature\n"
        );
    }

    #[test]
    fn yaml_stream_empty_sequence_emits_nothing() {
        let data: Vec<Issue> = vec![];
        let out = format_yaml_stream(&data).unwrap();
        assert_eq!(out, "");
    }

    #[test]
    fn yaml_stream_single_item_sequence() {
        let data = vec![Issue {
            key: "PROJ-1",
            summary: "Fix login",
        }];
        let out = format_yaml_stream(&data).unwrap();
        assert_eq!(out, "---\nkey: PROJ-1\nsummary: Fix login\n");
    }

    #[test]
    fn yaml_stream_non_sequence_emits_single_doc() {
        let data = Issue {
            key: "PROJ-1",
            summary: "Fix login",
        };
        let out = format_yaml_stream(&data).unwrap();
        assert_eq!(out, "---\nkey: PROJ-1\nsummary: Fix login\n");
    }

    #[test]
    fn yaml_stream_scalar_emits_single_doc() {
        let data: i32 = 42;
        let out = format_yaml_stream(&data).unwrap();
        assert_eq!(out, "---\n42\n");
    }

    #[test]
    fn yaml_stream_nested_sequences_treat_outer_only() {
        let data = vec![vec![1, 2], vec![3, 4]];
        let out = format_yaml_stream(&data).unwrap();
        assert_eq!(out, "---\n- 1\n- 2\n---\n- 3\n- 4\n");
    }

    #[test]
    fn yaml_stream_round_trips_via_safe_load_all() {
        use serde::Deserialize;

        let data = vec![
            Issue {
                key: "PROJ-1",
                summary: "Fix login",
            },
            Issue {
                key: "PROJ-2",
                summary: "Add feature",
            },
        ];
        let out = format_yaml_stream(&data).unwrap();

        let docs: Vec<serde_yaml::Value> = serde_yaml::Deserializer::from_str(&out)
            .map(serde_yaml::Value::deserialize)
            .collect::<Result<_, _>>()
            .unwrap();

        assert_eq!(docs.len(), 2);
        assert_eq!(docs[0]["key"], serde_yaml::Value::from("PROJ-1"));
        assert_eq!(docs[1]["key"], serde_yaml::Value::from("PROJ-2"));
    }

    // ── write_output ───────────────────────────────────────────────

    #[test]
    fn write_output_table_returns_false_and_writes_nothing() {
        let data = vec![1_i32, 2];
        let mut buf = Vec::new();
        let wrote = write_output(&data, &OutputFormat::Table, &mut buf).unwrap();
        assert!(!wrote);
        assert!(buf.is_empty());
    }

    #[test]
    fn write_output_json_emits_pretty_array() {
        let data = vec![1_i32, 2, 3];
        let mut buf = Vec::new();
        let wrote = write_output(&data, &OutputFormat::Json, &mut buf).unwrap();
        assert!(wrote);
        let out = String::from_utf8(buf).unwrap();
        assert!(out.starts_with('['));
        assert!(out.contains("  1,\n"));
        assert!(out.ends_with("]\n"));
    }

    #[test]
    fn write_output_yaml_emits_list() {
        let data = vec![1_i32, 2];
        let mut buf = Vec::new();
        let wrote = write_output(&data, &OutputFormat::Yaml, &mut buf).unwrap();
        assert!(wrote);
        let out = String::from_utf8(buf).unwrap();
        assert_eq!(out, "- 1\n- 2\n");
    }

    #[test]
    fn write_output_yamls_emits_yaml_stream() {
        let data = vec![1_i32, 2];
        let mut buf = Vec::new();
        let wrote = write_output(&data, &OutputFormat::Yamls, &mut buf).unwrap();
        assert!(wrote);
        let out = String::from_utf8(buf).unwrap();
        assert_eq!(out, "---\n1\n---\n2\n");
    }

    #[test]
    fn write_output_jsonl_emits_one_line_per_item() {
        let data = vec![1_i32, 2, 3];
        let mut buf = Vec::new();
        let wrote = write_output(&data, &OutputFormat::Jsonl, &mut buf).unwrap();
        assert!(wrote);
        assert_eq!(String::from_utf8(buf).unwrap(), "1\n2\n3\n");
    }

    struct FailingWriter;

    impl Write for FailingWriter {
        fn write(&mut self, _buf: &[u8]) -> std::io::Result<usize> {
            Err(std::io::Error::other("boom"))
        }
        fn flush(&mut self) -> std::io::Result<()> {
            Err(std::io::Error::other("boom"))
        }
    }

    #[test]
    fn write_output_propagates_write_errors() {
        let data = vec![1_i32];
        let mut writer = FailingWriter;

        assert!(write_output(&data, &OutputFormat::Json, &mut writer).is_err());
        assert!(write_output(&data, &OutputFormat::Yaml, &mut writer).is_err());
        assert!(write_output(&data, &OutputFormat::Yamls, &mut writer).is_err());
        assert!(write_output(&data, &OutputFormat::Jsonl, &mut writer).is_err());
        assert!(writer.write(b"x").is_err());
        assert!(writer.flush().is_err());
    }

    struct FailingSerialize;

    impl Serialize for FailingSerialize {
        fn serialize<S>(&self, _serializer: S) -> std::result::Result<S::Ok, S::Error>
        where
            S: serde::Serializer,
        {
            Err(serde::ser::Error::custom("serialize failed"))
        }
    }

    impl JsonlSerialize for FailingSerialize {
        fn write_jsonl(&self, _out: &mut dyn Write) -> Result<()> {
            Ok(())
        }
    }

    #[test]
    fn write_output_propagates_json_serialize_errors() {
        let mut buf = Vec::new();
        let err = write_output(&FailingSerialize, &OutputFormat::Json, &mut buf).unwrap_err();
        assert!(err.to_string().contains("Failed to serialize as JSON"));
    }

    #[test]
    fn write_output_propagates_yaml_serialize_errors() {
        let mut buf = Vec::new();
        let err = write_output(&FailingSerialize, &OutputFormat::Yaml, &mut buf).unwrap_err();
        assert!(err.to_string().contains("Failed to serialize as YAML"));
    }

    #[test]
    fn failing_serialize_jsonl_impl_is_a_noop() {
        let mut buf = Vec::new();
        FailingSerialize.write_jsonl(&mut buf).unwrap();
        assert!(buf.is_empty());
    }
}