omni-dev 0.22.0

A powerful Git commit message analysis and amendment toolkit
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
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
//! Shared helpers for JIRA and Confluence CLI commands.

use std::fs;
use std::io::{self, Read, Write};

use anyhow::{Context, Result};

use crate::atlassian::adf::AdfDocument;
use crate::atlassian::api::AtlassianApi;
use crate::atlassian::auth;
use crate::atlassian::client::AtlassianClient;
use crate::atlassian::convert::markdown_to_adf;
use crate::atlassian::document::{content_item_to_document, JfmDocument};

use super::format::ContentFormat;

/// Fetches content and outputs it in the specified format.
pub async fn run_read(
    id: &str,
    output: Option<&str>,
    format: &ContentFormat,
    api: &dyn AtlassianApi,
    instance_url: &str,
) -> Result<()> {
    let item = api.get_content(id).await?;

    match format {
        ContentFormat::Adf => {
            let json =
                serde_json::to_string_pretty(&item.body_adf.unwrap_or(serde_json::Value::Null))
                    .context("Failed to serialize ADF JSON")?;
            output_text(&json, output)?;
        }
        ContentFormat::Jfm => {
            let doc = content_item_to_document(&item, instance_url)?;
            let rendered = doc.render()?;
            output_text(&rendered, output)?;

            if let Some(path) = output {
                eprintln!("Saved to: {path}");
            }
        }
    }

    Ok(())
}

/// Parses input content and converts it to ADF, returning the document and title.
pub fn prepare_write(file: Option<&str>, format: &ContentFormat) -> Result<(AdfDocument, String)> {
    let input = read_input(file)?;

    match format {
        ContentFormat::Jfm => {
            let doc = JfmDocument::parse(&input)?;
            let adf = markdown_to_adf(&doc.body)?;
            let title = doc.frontmatter.title().to_string();
            Ok((adf, title))
        }
        ContentFormat::Adf => {
            let adf = AdfDocument::from_json_str(&input)?;
            Ok((adf, String::new()))
        }
    }
}

/// Prints a dry-run summary without making any API calls.
pub fn print_dry_run(id: &str, adf: &AdfDocument, title: &str) -> Result<()> {
    println!("Dry run for {id}:");
    if !title.is_empty() {
        println!("  Title: {title}");
    }
    println!(
        "\nADF output:\n{}",
        serde_json::to_string_pretty(adf).context("Failed to serialize ADF")?
    );
    Ok(())
}

/// Prints a dry-run summary for issue creation.
pub fn print_create_dry_run(
    project: &str,
    issue_type: &str,
    summary: &str,
    adf: &AdfDocument,
    labels: &[String],
) -> Result<()> {
    println!("Dry run — would create issue:");
    println!("  Project:    {project}");
    println!("  Type:       {issue_type}");
    println!("  Summary:    {summary}");
    if !labels.is_empty() {
        println!("  Labels:     {}", labels.join(", "));
    }
    println!(
        "\nADF body:\n{}",
        serde_json::to_string_pretty(adf).context("Failed to serialize ADF")?
    );
    Ok(())
}

/// Confirms and pushes content to the target.
pub async fn run_write(
    id: &str,
    adf: &AdfDocument,
    title: &str,
    force: bool,
    api: &dyn AtlassianApi,
) -> Result<()> {
    if !force {
        println!("About to update {id}:");
        if !title.is_empty() {
            println!("  Title: {title}");
        }
        print!("\nApply changes? [y/N] ");
        io::stdout().flush()?;

        let mut answer = String::new();
        io::stdin().read_line(&mut answer)?;
        if !answer.trim().eq_ignore_ascii_case("y") {
            println!("Cancelled.");
            return Ok(());
        }
    }

    let title_ref = if title.is_empty() { None } else { Some(title) };

    api.update_content(id, adf, title_ref).await?;
    println!("Updated {id} successfully.");

    Ok(())
}

/// Interactive fetch-edit-push cycle.
pub async fn run_edit(id: &str, api: &dyn AtlassianApi, instance_url: &str) -> Result<()> {
    use tracing::debug;

    // 1. Fetch the content
    println!("Fetching {id}...");
    let item = api.get_content(id).await?;
    let original_title = item.title.clone();

    // 2. Convert to JFM document
    let doc = content_item_to_document(&item, instance_url)?;
    let original_content = doc.render()?;

    // 3. Write to temp file
    let temp_dir = tempfile::tempdir()?;
    let temp_file = temp_dir.path().join(format!("{id}.md"));
    fs::write(&temp_file, &original_content)?;

    println!("Saved to: {}", temp_file.display());

    // 4. Interactive loop
    loop {
        print!("\n[A]ccept, [S]how, [E]dit, or [Q]uit? [a/s/e/q] ");
        io::stdout().flush()?;

        let mut input = String::new();
        io::stdin().read_line(&mut input)?;

        match input.trim().to_lowercase().as_str() {
            "a" | "accept" => {
                let final_content =
                    fs::read_to_string(&temp_file).context("Failed to read temp file")?;

                if final_content == original_content {
                    println!("No changes detected.");
                    return Ok(());
                }

                let final_doc = JfmDocument::parse(&final_content)?;
                debug!(
                    "Parsed JFM document, body length: {} bytes",
                    final_doc.body.len()
                );

                let adf = markdown_to_adf(&final_doc.body)?;
                debug!(
                    "Converted to ADF with {} top-level nodes",
                    adf.content.len()
                );
                if tracing::enabled!(tracing::Level::TRACE) {
                    let adf_json = serde_json::to_string_pretty(&adf)
                        .unwrap_or_else(|e| format!("<serialization error: {e}>"));
                    tracing::trace!("ADF payload:\n{adf_json}");
                }

                let title_changed = final_doc.frontmatter.title() != original_title;
                let title_update = if title_changed {
                    Some(final_doc.frontmatter.title())
                } else {
                    None
                };

                api.update_content(id, &adf, title_update).await?;
                println!("Updated {id} successfully.");
                return Ok(());
            }
            "s" | "show" => {
                let content = fs::read_to_string(&temp_file).context("Failed to read temp file")?;
                println!("\n{content}");
            }
            "e" | "edit" => {
                open_editor(&temp_file)?;
            }
            "q" | "quit" => {
                println!("Cancelled.");
                return Ok(());
            }
            _ => {
                println!(
                    "Invalid choice. Enter 'a' to accept, 's' to show, 'e' to edit, or 'q' to quit."
                );
            }
        }
    }
}

/// Creates an authenticated Atlassian API client, returning the client and instance URL.
pub fn create_client() -> Result<(AtlassianClient, String)> {
    let credentials = auth::load_credentials()?;
    let client = AtlassianClient::from_credentials(&credentials)?;
    let instance_url = client.instance_url().to_string();
    Ok((client, instance_url))
}

/// Writes text to a file or stdout.
pub fn output_text(text: &str, file: Option<&str>) -> Result<()> {
    match file {
        Some(path) => {
            fs::write(path, text).with_context(|| format!("Failed to write to {path}"))?;
        }
        None => {
            print!("{text}");
        }
    }
    Ok(())
}

/// Reads input from a file path or stdin.
pub fn read_input(file: Option<&str>) -> Result<String> {
    match file {
        Some("-") | None => {
            let mut buf = String::new();
            io::stdin()
                .read_to_string(&mut buf)
                .context("Failed to read from stdin")?;
            Ok(buf)
        }
        Some(path) => {
            fs::read_to_string(path).with_context(|| format!("Failed to read file: {path}"))
        }
    }
}

/// Opens a file in the user's editor.
fn open_editor(file: &std::path::Path) -> Result<()> {
    use std::env;
    use std::process::Command;

    let editor = if let Ok(e) = env::var("OMNI_DEV_EDITOR").or_else(|_| env::var("EDITOR")) {
        e
    } else {
        print!("Neither OMNI_DEV_EDITOR nor EDITOR is set. Enter editor command: ");
        io::stdout().flush().context("Failed to flush stdout")?;
        let mut input = String::new();
        io::stdin()
            .read_line(&mut input)
            .context("Failed to read user input")?;
        input.trim().to_string()
    };

    if editor.is_empty() {
        println!("No editor specified. Returning to menu.");
        return Ok(());
    }

    let (editor_cmd, args) = crate::cli::git::formatting::parse_editor_command(&editor);

    let mut command = Command::new(editor_cmd);
    command.args(args);
    command.arg(file.to_string_lossy().as_ref());

    match command.status() {
        Ok(status) => {
            if status.success() {
                println!("Editor session completed.");
            } else {
                println!("Editor exited with non-zero status: {:?}", status.code());
            }
        }
        Err(e) => {
            println!("Failed to execute editor '{editor}': {e}");
        }
    }

    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::atlassian::api::{ContentItem, ContentMetadata};

    // ── Mock AtlassianApi ──────────────────────────────────────────

    struct MockApi {
        content: ContentItem,
        update_called: std::sync::Mutex<bool>,
    }

    impl MockApi {
        fn jira_issue(body_adf: Option<serde_json::Value>) -> Self {
            Self {
                content: ContentItem {
                    id: "PROJ-1".to_string(),
                    title: "Test Issue".to_string(),
                    body_adf,
                    metadata: ContentMetadata::Jira {
                        status: Some("Open".to_string()),
                        issue_type: Some("Bug".to_string()),
                        assignee: None,
                        priority: None,
                        labels: vec![],
                    },
                },
                update_called: std::sync::Mutex::new(false),
            }
        }

        fn confluence_page(body_adf: Option<serde_json::Value>) -> Self {
            Self {
                content: ContentItem {
                    id: "12345".to_string(),
                    title: "Test Page".to_string(),
                    body_adf,
                    metadata: ContentMetadata::Confluence {
                        space_key: "ENG".to_string(),
                        status: Some("current".to_string()),
                        version: Some(1),
                        parent_id: None,
                    },
                },
                update_called: std::sync::Mutex::new(false),
            }
        }

        fn was_update_called(&self) -> bool {
            *self.update_called.lock().unwrap()
        }
    }

    impl AtlassianApi for MockApi {
        fn get_content<'a>(
            &'a self,
            _id: &'a str,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<ContentItem>> + Send + 'a>>
        {
            Box::pin(async { Ok(self.content.clone()) })
        }

        fn update_content<'a>(
            &'a self,
            _id: &'a str,
            _body_adf: &'a AdfDocument,
            _title: Option<&'a str>,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<()>> + Send + 'a>> {
            *self.update_called.lock().unwrap() = true;
            Box::pin(async { Ok(()) })
        }

        fn verify_auth<'a>(
            &'a self,
        ) -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<String>> + Send + 'a>>
        {
            Box::pin(async { Ok("Test User".to_string()) })
        }

        fn backend_name(&self) -> &'static str {
            "mock"
        }
    }

    // ── output_text ────────────────────────────────────────────────

    #[test]
    fn output_text_to_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("output.txt");
        let path_str = file_path.to_str().unwrap();

        output_text("hello world", Some(path_str)).unwrap();

        let content = fs::read_to_string(&file_path).unwrap();
        assert_eq!(content, "hello world");
    }

    #[test]
    fn output_text_to_stdout() {
        assert!(output_text("test", None).is_ok());
    }

    #[test]
    fn output_text_overwrites_existing_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("output.txt");
        let path_str = file_path.to_str().unwrap();

        fs::write(&file_path, "old content").unwrap();
        output_text("new content", Some(path_str)).unwrap();

        let content = fs::read_to_string(&file_path).unwrap();
        assert_eq!(content, "new content");
    }

    #[test]
    fn output_text_invalid_path() {
        let result = output_text("data", Some("/nonexistent_dir/file.txt"));
        assert!(result.is_err());
    }

    // ── read_input ─────────────────────────────────────────────────

    #[test]
    fn read_input_from_file() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("issue.md");
        let content = "---\ntype: jira\ninstance: https://org.atlassian.net\nkey: PROJ-1\nsummary: Test\n---\n\nBody\n";
        fs::write(&file_path, content).unwrap();

        let result = read_input(Some(file_path.to_str().unwrap())).unwrap();
        assert_eq!(result, content);
    }

    #[test]
    fn read_input_missing_file() {
        let result = read_input(Some("/nonexistent/file.md"));
        assert!(result.is_err());
    }

    // ── open_editor ────────────────────────────────────────────────

    #[test]
    fn open_editor_with_true_command() {
        std::env::set_var("OMNI_DEV_EDITOR", "true");

        let temp_dir = tempfile::tempdir().unwrap();
        let file = temp_dir.path().join("test.md");
        fs::write(&file, "content").unwrap();

        let result = open_editor(&file);

        std::env::remove_var("OMNI_DEV_EDITOR");

        assert!(result.is_ok());
    }

    #[test]
    fn open_editor_with_nonexistent_command() {
        std::env::set_var("OMNI_DEV_EDITOR", "nonexistent_editor_binary_12345");

        let temp_dir = tempfile::tempdir().unwrap();
        let file = temp_dir.path().join("test.md");
        fs::write(&file, "content").unwrap();

        let result = open_editor(&file);

        std::env::remove_var("OMNI_DEV_EDITOR");

        assert!(result.is_ok());
    }

    // ── prepare_write ──────────────────────────────────────────────

    #[test]
    fn prepare_write_jfm_format() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("issue.md");
        let content = "---\ntype: jira\ninstance: https://org.atlassian.net\nkey: PROJ-1\nsummary: My Title\n---\n\nHello world\n";
        fs::write(&file_path, content).unwrap();

        let (adf, title) =
            prepare_write(Some(file_path.to_str().unwrap()), &ContentFormat::Jfm).unwrap();

        assert_eq!(title, "My Title");
        assert!(!adf.content.is_empty());
    }

    #[test]
    fn prepare_write_adf_format() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("issue.json");
        let adf_json = r#"{"version":1,"type":"doc","content":[{"type":"paragraph","content":[{"type":"text","text":"Hello"}]}]}"#;
        fs::write(&file_path, adf_json).unwrap();

        let (adf, title) =
            prepare_write(Some(file_path.to_str().unwrap()), &ContentFormat::Adf).unwrap();

        assert!(title.is_empty());
        assert_eq!(adf.content.len(), 1);
    }

    #[test]
    fn prepare_write_invalid_adf_json() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("bad.json");
        fs::write(&file_path, "not json").unwrap();

        let result = prepare_write(Some(file_path.to_str().unwrap()), &ContentFormat::Adf);
        assert!(result.is_err());
    }

    #[test]
    fn prepare_write_null_adf_input_yields_empty_doc() {
        let temp_dir = tempfile::tempdir().unwrap();
        let file_path = temp_dir.path().join("null.json");
        fs::write(&file_path, "null").unwrap();

        let (adf, title) =
            prepare_write(Some(file_path.to_str().unwrap()), &ContentFormat::Adf).unwrap();

        assert_eq!(adf, AdfDocument::default());
        assert!(title.is_empty());
    }

    #[test]
    fn prepare_write_missing_file() {
        let result = prepare_write(Some("/nonexistent/file.md"), &ContentFormat::Jfm);
        assert!(result.is_err());
    }

    // ── print_dry_run ──────────────────────────────────────────────

    #[test]
    fn print_dry_run_with_title() {
        let adf = AdfDocument::new();
        let result = print_dry_run("PROJ-1", &adf, "My Title");
        assert!(result.is_ok());
    }

    #[test]
    fn print_dry_run_without_title() {
        let adf = AdfDocument::new();
        let result = print_dry_run("PROJ-1", &adf, "");
        assert!(result.is_ok());
    }

    // ── run_read ───────────────────────────────────────────────

    #[tokio::test]
    async fn run_read_jfm_to_stdout() {
        let adf_body = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Hello"}]}]
        });
        let api = MockApi::jira_issue(Some(adf_body));

        let result = run_read(
            "PROJ-1",
            None,
            &ContentFormat::Jfm,
            &api,
            "https://org.atlassian.net",
        )
        .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn run_read_adf_to_stdout() {
        let adf_body = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": []
        });
        let api = MockApi::jira_issue(Some(adf_body));

        let result = run_read(
            "PROJ-1",
            None,
            &ContentFormat::Adf,
            &api,
            "https://org.atlassian.net",
        )
        .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn run_read_adf_null_body() {
        let api = MockApi::jira_issue(None);

        let result = run_read(
            "PROJ-1",
            None,
            &ContentFormat::Adf,
            &api,
            "https://org.atlassian.net",
        )
        .await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn run_read_jfm_to_file() {
        let adf_body = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Hello"}]}]
        });
        let api = MockApi::jira_issue(Some(adf_body));

        let temp_dir = tempfile::tempdir().unwrap();
        let out_path = temp_dir.path().join("out.md");

        let result = run_read(
            "PROJ-1",
            Some(out_path.to_str().unwrap()),
            &ContentFormat::Jfm,
            &api,
            "https://org.atlassian.net",
        )
        .await;
        assert!(result.is_ok());
        assert!(out_path.exists());
        let content = fs::read_to_string(&out_path).unwrap();
        assert!(content.contains("PROJ-1"));
    }

    #[tokio::test]
    async fn run_read_adf_to_file() {
        let adf_body = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": []
        });
        let api = MockApi::jira_issue(Some(adf_body));

        let temp_dir = tempfile::tempdir().unwrap();
        let out_path = temp_dir.path().join("out.json");

        let result = run_read(
            "PROJ-1",
            Some(out_path.to_str().unwrap()),
            &ContentFormat::Adf,
            &api,
            "https://org.atlassian.net",
        )
        .await;
        assert!(result.is_ok());
        assert!(out_path.exists());
    }

    #[tokio::test]
    async fn run_read_confluence_jfm() {
        let adf_body = serde_json::json!({
            "version": 1,
            "type": "doc",
            "content": [{"type": "paragraph", "content": [{"type": "text", "text": "Page content"}]}]
        });
        let api = MockApi::confluence_page(Some(adf_body));

        let result = run_read(
            "12345",
            None,
            &ContentFormat::Jfm,
            &api,
            "https://org.atlassian.net",
        )
        .await;
        assert!(result.is_ok());
    }

    // ── run_write ──────────────────────────────────────────────

    #[tokio::test]
    async fn run_write_force_with_title() {
        let api = MockApi::jira_issue(None);
        let adf = AdfDocument::new();

        let result = run_write("PROJ-1", &adf, "My Title", true, &api).await;
        assert!(result.is_ok());
        assert!(api.was_update_called());
    }

    #[tokio::test]
    async fn run_write_force_empty_title() {
        let api = MockApi::jira_issue(None);
        let adf = AdfDocument::new();

        let result = run_write("PROJ-1", &adf, "", true, &api).await;
        assert!(result.is_ok());
        assert!(api.was_update_called());
    }

    // ── print_create_dry_run ───────────────────────────────────────

    #[test]
    fn print_create_dry_run_with_labels() {
        let adf = AdfDocument::new();
        let labels = vec!["backend".to_string(), "urgent".to_string()];
        let result = print_create_dry_run("PROJ", "Bug", "Fix login", &adf, &labels);
        assert!(result.is_ok());
    }

    #[test]
    fn print_create_dry_run_without_labels() {
        let adf = AdfDocument::new();
        let result = print_create_dry_run("PROJ", "Task", "Add feature", &adf, &[]);
        assert!(result.is_ok());
    }
}