omni-dev 0.24.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
#![allow(clippy::unwrap_used, clippy::expect_used)]

use std::env;
use std::fs;
use std::path::PathBuf;

// Serialises the window where amend_command_with_temporary_repo mutates the
// process-wide CWD via env::set_current_dir.  That mutation is visible to all
// threads; without serialisation any concurrently-running test that creates a
// git2 Repository via a relative path (including TestRepo::new) races against
// it.  See <https://github.com/rust-works/omni-dev/issues/230>.
static CWD_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());

use anyhow::Result;
use git2::{Repository, Signature};
use tempfile::TempDir;

use omni_dev::cli::git::AmendCommand;
use omni_dev::data::amendments::{Amendment, AmendmentFile};

/// Test setup that creates a temporary git repository with test commits
struct TestRepo {
    _temp_dir: TempDir,
    repo_path: PathBuf,
    repo: Repository,
    commits: Vec<git2::Oid>,
}

impl TestRepo {
    fn new() -> Result<Self> {
        // Use an absolute base so TempDir::path() (and therefore repo_path)
        // is absolute.  A relative "tmp" would make repo_path relative to
        // the process CWD at creation time; if another test changes CWD
        // concurrently, libgit2 can no longer locate the repository.
        let tmp_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
        let temp_dir = {
            std::fs::create_dir_all(&tmp_root)?;
            tempfile::tempdir_in(&tmp_root)?
        };
        let repo_path = temp_dir.path().to_path_buf();

        // Initialize git repository
        let repo = Repository::init(&repo_path)?;

        // Configure git user for commits
        let mut config = repo.config()?;
        config.set_str("user.name", "Test User")?;
        config.set_str("user.email", "test@example.com")?;

        Ok(Self {
            _temp_dir: temp_dir,
            repo_path,
            repo,
            commits: Vec::new(),
        })
    }

    fn add_commit(&mut self, message: &str, content: &str) -> Result<git2::Oid> {
        // Create a test file
        let file_path = self.repo_path.join("test.txt");
        fs::write(&file_path, content)?;

        // Add file to index
        let mut index = self.repo.index()?;
        index.add_path(std::path::Path::new("test.txt"))?;
        index.write()?;

        // Create commit
        let signature = Signature::now("Test User", "test@example.com")?;
        let tree_id = index.write_tree()?;
        let tree = self.repo.find_tree(tree_id)?;

        let parent_commit = if let Some(last_commit_id) = self.commits.last() {
            Some(self.repo.find_commit(*last_commit_id)?)
        } else {
            None
        };

        let parents: Vec<&git2::Commit> = if let Some(ref parent) = parent_commit {
            vec![parent]
        } else {
            vec![]
        };

        let commit_id = self.repo.commit(
            Some("HEAD"),
            &signature,
            &signature,
            message,
            &tree,
            &parents,
        )?;

        self.commits.push(commit_id);
        Ok(commit_id)
    }

    fn get_commit_hash(&self, index: usize) -> Option<String> {
        self.commits.get(index).map(git2::Oid::to_string)
    }

    fn create_amendment_file(&self, amendments: Vec<(usize, &str)>) -> Result<PathBuf> {
        let amendment_file = AmendmentFile {
            amendments: amendments
                .iter()
                .filter_map(|(index, message)| {
                    self.get_commit_hash(*index)
                        .map(|hash| Amendment::new(hash, (*message).to_string()))
                })
                .collect(),
        };

        // Create the amendments file outside the repository to avoid it showing up as untracked
        let yaml_path = self.repo_path.parent().unwrap().join("amendments.yaml");
        amendment_file.save_to_file(&yaml_path)?;
        Ok(yaml_path)
    }
}

#[test]
fn amend_command_with_temporary_repo() -> Result<()> {
    // Set up temporary repository with test commits
    let mut test_repo = TestRepo::new()?;

    // Add some test commits
    let _commit1 = test_repo.add_commit("Initial commit", "Hello, world!")?;
    let _commit2 = test_repo.add_commit("Add feature", "Hello, world!\nNew feature added.")?;
    let _commit3 =
        test_repo.add_commit("Fix bug", "Hello, world!\nNew feature added.\nBug fixed.")?;

    println!("Created test repository at: {:?}", test_repo.repo_path);
    println!("Commits created:");
    for (i, commit_id) in test_repo.commits.iter().enumerate() {
        println!("  {i}: {commit_id}");
    }

    // Create amendment file to modify HEAD commit (tested and working)
    let amendments = vec![(2, "Fix critical bug in the new feature")];

    let amendment_file_path = test_repo.create_amendment_file(amendments)?;
    println!("Created amendment file at: {amendment_file_path:?}");

    // AmendCommand::execute → AmendmentHandler::new → Repository::open(".")
    // requires the process CWD to equal the repository root.  env::set_current_dir
    // is process-wide, so we hold CWD_MUTEX for the entire mutation window to
    // prevent concurrent tests from observing an unexpected CWD.
    let original_dir = env::current_dir()?;
    let result = {
        let _cwd_guard = CWD_MUTEX.lock().unwrap();
        env::set_current_dir(&test_repo.repo_path)?;

        let outcome = std::panic::catch_unwind(|| {
            let amend_cmd = AmendCommand {
                yaml_file: amendment_file_path.to_string_lossy().to_string(),
            };

            println!("Testing amend command...");
            let result = amend_cmd.execute();
            println!("Amend command result: {result:?}");
            result
        });

        // Restore CWD before releasing the mutex.
        env::set_current_dir(&original_dir)?;
        outcome
        // _cwd_guard dropped here — other threads may now change or read CWD.
    };

    match result {
        Ok(cmd_result) => {
            println!("Amend command completed: {cmd_result:?}");

            // The implementation should now actually work
            assert!(cmd_result.is_ok(), "Amend command should succeed");

            // Verify that amendments were actually made.  Use the absolute
            // repo_path directly so this does not depend on process CWD.
            let repo = Repository::open(&test_repo.repo_path)?;
            let head = repo.head()?.target().unwrap();
            let commit = repo.find_commit(head)?;
            println!(
                "Current HEAD commit message after amendment: {}",
                commit.message().unwrap_or("")
            );

            // The HEAD commit message should have been amended
            let head_message = commit.message().unwrap_or("").trim();
            assert_eq!(
                head_message, "Fix critical bug in the new feature",
                "HEAD commit should have been amended with new message"
            );

            println!("✅ Test passed: Amend command successfully amended the commit message");
        }
        Err(e) => {
            println!("❌ Amend command panicked: {e:?}");
            panic!("Amend command should not panic");
        }
    }

    Ok(())
}

#[test]
fn amendment_file_parsing() -> Result<()> {
    // Test that amendment file parsing works correctly
    let tmp_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
    let temp_dir = {
        std::fs::create_dir_all(&tmp_root)?;
        tempfile::tempdir_in(&tmp_root)?
    };
    let yaml_path = temp_dir.path().join("test_amendments.yaml");

    // Create a test amendment file
    let test_yaml = r#"
amendments:
  - commit: "1234567890abcdef1234567890abcdef12345678"
    message: "Updated commit message 1"
  - commit: "abcdef1234567890abcdef1234567890abcdef12"
    message: "Updated commit message 2"
"#;

    fs::write(&yaml_path, test_yaml)?;

    // Test loading the amendment file
    let amendment_file = AmendmentFile::load_from_file(&yaml_path)?;
    assert_eq!(amendment_file.amendments.len(), 2);

    println!("✅ Amendment file parsing test passed");
    Ok(())
}

#[test]
fn amendment_validation() -> Result<()> {
    // Test amendment validation
    let tmp_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
    let temp_dir = {
        std::fs::create_dir_all(&tmp_root)?;
        tempfile::tempdir_in(&tmp_root)?
    };
    let yaml_path = temp_dir.path().join("invalid_amendments.yaml");

    // Test with invalid commit hash (too short)
    let invalid_yaml = r#"
amendments:
  - commit: "12345"
    message: "Short hash should fail"
"#;

    fs::write(&yaml_path, invalid_yaml)?;

    // This should fail validation
    let result = AmendmentFile::load_from_file(&yaml_path);
    assert!(result.is_err());
    println!("✅ Amendment validation test passed - invalid hash rejected");

    Ok(())
}

#[test]
fn help_all_golden() -> Result<()> {
    // Capture the help-all output using the help generator directly
    use omni_dev::cli::help::HelpGenerator;

    let generator = HelpGenerator::new();
    let help_output = generator.generate_all_help()?;

    // Use insta for snapshot testing - this creates a .snap file with the expected output
    insta::assert_snapshot!("help_all_output", help_output);

    println!("✅ Golden test for help-all command completed");
    Ok(())
}

// ── CLI binary invocation tests ─────────────────────────────────

#[test]
fn binary_help_flag_succeeds() {
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_omni-dev"))
        .arg("--help")
        .output()
        .expect("failed to run binary");
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("comprehensive development toolkit"));
}

#[test]
fn binary_version_flag_succeeds() {
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_omni-dev"))
        .arg("--version")
        .output()
        .expect("failed to run binary");
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("omni-dev"));
}

#[test]
fn binary_unknown_command_fails() {
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_omni-dev"))
        .arg("nonexistent")
        .output()
        .expect("failed to run binary");
    assert!(!output.status.success());
}

#[test]
fn binary_config_models_show_succeeds() {
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_omni-dev"))
        .args(["config", "models", "show"])
        .output()
        .expect("failed to run binary");
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    // The models.yaml template should contain model definitions
    assert!(stdout.contains("claude"));
}

#[test]
fn binary_help_all_succeeds() {
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_omni-dev"))
        .arg("help-all")
        .output()
        .expect("failed to run binary");
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("omni-dev git"));
    assert!(stdout.contains("omni-dev ai"));
}

#[test]
fn binary_git_help_succeeds() {
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_omni-dev"))
        .args(["git", "--help"])
        .output()
        .expect("failed to run binary");
    assert!(output.status.success());
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("commit"));
    assert!(stdout.contains("branch"));
}

#[test]
fn binary_commands_generate_in_temp_dir() {
    let tmp_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
    let temp_dir = {
        std::fs::create_dir_all(&tmp_root).ok();
        tempfile::tempdir_in(&tmp_root).unwrap()
    };
    let output = std::process::Command::new(env!("CARGO_BIN_EXE_omni-dev"))
        .args(["commands", "generate", "all"])
        .current_dir(temp_dir.path())
        .output()
        .expect("failed to run binary");
    assert!(output.status.success());

    // Verify templates were written
    assert!(temp_dir
        .path()
        .join(".claude/commands/commit-twiddle.md")
        .exists());
    assert!(temp_dir
        .path()
        .join(".claude/commands/pr-create.md")
        .exists());
    assert!(temp_dir
        .path()
        .join(".claude/commands/pr-update.md")
        .exists());
}

// ── TestRepo builder coverage ───────────────────────────────────

#[test]
fn test_repo_multiple_commits() -> Result<()> {
    let mut repo = TestRepo::new()?;
    repo.add_commit("first", "content1")?;
    repo.add_commit("second", "content2")?;
    repo.add_commit("third", "content3")?;

    assert_eq!(repo.commits.len(), 3);
    assert!(repo.get_commit_hash(0).is_some());
    assert!(repo.get_commit_hash(1).is_some());
    assert!(repo.get_commit_hash(2).is_some());
    assert!(repo.get_commit_hash(3).is_none());

    // Hashes should be 40-character hex
    let hash = repo.get_commit_hash(0).unwrap();
    assert_eq!(hash.len(), 40);
    assert!(hash.chars().all(|c| c.is_ascii_hexdigit()));

    Ok(())
}

#[test]
fn test_repo_create_amendment_file_roundtrip() -> Result<()> {
    let mut repo = TestRepo::new()?;
    repo.add_commit("initial", "hello")?;
    repo.add_commit("second", "world")?;

    // Verify commits were actually created before relying on them
    assert_eq!(repo.commits.len(), 2, "should have 2 commits");
    let hash0 = repo
        .get_commit_hash(0)
        .expect("commit 0 must exist after add_commit");
    let hash1 = repo
        .get_commit_hash(1)
        .expect("commit 1 must exist after add_commit");

    // Build the AmendmentFile directly (avoid filter_map silently dropping items)
    let amendment_file = AmendmentFile {
        amendments: vec![
            Amendment::new(hash0, "improved initial".to_string()),
            Amendment::new(hash1, "improved second".to_string()),
        ],
    };

    // Use a unique filename to avoid collisions with other tests
    let yaml_path = repo
        .repo_path
        .parent()
        .unwrap()
        .join("roundtrip_amendments.yaml");
    amendment_file.save_to_file(&yaml_path)?;

    let loaded = AmendmentFile::load_from_file(&yaml_path)?;
    assert_eq!(loaded.amendments.len(), 2);
    assert_eq!(loaded.amendments[0].message, "improved initial");
    assert_eq!(loaded.amendments[1].message, "improved second");

    Ok(())
}

// ── Async dispatch coverage ──────────────────────────────────────
//
// These tests exercise the async execute() dispatch chain introduced in #222.
// They run in the omni-dev repo itself (a valid git repository), so commands
// that require a git repo succeed without needing a temporary repo setup.

#[tokio::test]
async fn cli_execute_dispatches_git_commit_message_view() {
    use omni_dev::cli::git::{
        CommitCommand, CommitSubcommands, GitCommand, GitSubcommands, MessageCommand,
        MessageSubcommands, ViewCommand,
    };
    use omni_dev::cli::{Cli, Commands};

    let cli = Cli {
        ai_backend: None,
        claude_cli_allow_tools: false,
        claude_cli_allow_mcp: false,
        claude_cli_max_budget_usd: None,
        command: Commands::Git(GitCommand {
            command: GitSubcommands::Commit(CommitCommand {
                command: CommitSubcommands::Message(MessageCommand {
                    command: MessageSubcommands::View(ViewCommand {
                        commit_range: Some("HEAD".to_string()),
                    }),
                }),
            }),
        }),
    };
    let _ = cli.execute().await;
}

#[tokio::test]
async fn cli_execute_dispatches_git_branch_info() {
    use omni_dev::cli::git::{
        BranchCommand, BranchSubcommands, GitCommand, GitSubcommands, InfoCommand,
    };
    use omni_dev::cli::{Cli, Commands};

    let cli = Cli {
        ai_backend: None,
        claude_cli_allow_tools: false,
        claude_cli_allow_mcp: false,
        claude_cli_max_budget_usd: None,
        command: Commands::Git(GitCommand {
            command: GitSubcommands::Branch(BranchCommand {
                command: BranchSubcommands::Info(InfoCommand { base_branch: None }),
            }),
        }),
    };
    let _ = cli.execute().await;
}

#[tokio::test]
async fn cli_execute_dispatches_ai_chat() {
    use omni_dev::cli::ai::{AiCommand, AiSubcommands, ChatCommand};
    use omni_dev::cli::{Cli, Commands};

    let cli = Cli {
        ai_backend: None,
        claude_cli_allow_tools: false,
        claude_cli_allow_mcp: false,
        claude_cli_max_budget_usd: None,
        command: Commands::Ai(AiCommand {
            command: AiSubcommands::Chat(ChatCommand { model: None }),
        }),
    };
    // Without API credentials this returns Err at the preflight check;
    // with credentials it returns Err in a non-TTY environment.
    // Either way the async dispatch chain is exercised.
    let _ = cli.execute().await;
}