omni-dev 0.31.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, and Datadog.
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
//! Info command — analyzes branch commits and outputs repository information.

use std::path::Path;

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

/// Info command options.
#[derive(Parser)]
pub struct InfoCommand {
    /// Base branch to compare against (defaults to main/master).
    #[arg(value_name = "BASE_BRANCH")]
    pub base_branch: Option<String>,
}

impl InfoCommand {
    /// Executes the info command.
    ///
    /// `repo` is the repository location resolved at the CLI boundary
    /// (`None` = current working directory).
    pub fn execute(self, repo: Option<&Path>) -> Result<()> {
        let yaml_output = run_info(self.base_branch.as_deref(), repo)?;
        println!("{yaml_output}");
        Ok(())
    }

    /// Reads the PR template file if it exists, returning both content and location.
    ///
    /// Resolves `.github/pull_request_template.md` against `repo_root` rather
    /// than the process current working directory.
    pub(crate) fn read_pr_template(repo_root: &Path) -> Result<(String, String)> {
        use std::fs;

        let template_path = repo_root.join(".github/pull_request_template.md");
        if template_path.exists() {
            let content = fs::read_to_string(&template_path)
                .context("Failed to read .github/pull_request_template.md")?;
            Ok((content, template_path.to_string_lossy().to_string()))
        } else {
            anyhow::bail!("PR template file does not exist")
        }
    }

    /// Returns pull requests for the current branch using gh CLI.
    ///
    /// Runs `gh` pinned to `repo_root` (via `.current_dir`) so it resolves the
    /// repository from the injected path rather than the process CWD.
    pub(crate) fn get_branch_prs(
        branch_name: &str,
        repo_root: &Path,
    ) -> Result<Vec<crate::data::PullRequest>> {
        use serde_json::Value;
        use std::process::Command;

        // Use gh CLI to get PRs for the branch
        let output = Command::new("gh")
            .current_dir(repo_root)
            .args([
                "pr",
                "list",
                "--head",
                branch_name,
                "--json",
                "number,title,state,url,body,baseRefName",
                "--limit",
                "50",
            ])
            .output()
            .context("Failed to execute gh command")?;

        if !output.status.success() {
            anyhow::bail!(
                "gh command failed: {}",
                String::from_utf8_lossy(&output.stderr)
            );
        }

        let json_str = String::from_utf8_lossy(&output.stdout);
        let prs_json: Value =
            serde_json::from_str(&json_str).context("Failed to parse PR JSON from gh")?;

        let mut prs = Vec::new();
        if let Some(prs_array) = prs_json.as_array() {
            for pr_json in prs_array {
                if let (Some(number), Some(title), Some(state), Some(url), Some(body)) = (
                    pr_json.get("number").and_then(serde_json::Value::as_u64),
                    pr_json.get("title").and_then(|t| t.as_str()),
                    pr_json.get("state").and_then(|s| s.as_str()),
                    pr_json.get("url").and_then(|u| u.as_str()),
                    pr_json.get("body").and_then(|b| b.as_str()),
                ) {
                    let base = pr_json
                        .get("baseRefName")
                        .and_then(|b| b.as_str())
                        .unwrap_or("")
                        .to_string();
                    prs.push(crate::data::PullRequest {
                        number,
                        title: title.to_string(),
                        state: state.to_string(),
                        url: url.to_string(),
                        body: body.to_string(),
                        base,
                    });
                }
            }
        }

        Ok(prs)
    }
}

/// Runs the info logic and returns the repository YAML as a `String`.
///
/// Shared by the CLI (which prints the result) and the MCP server (which
/// returns it as tool content). When `repo_path` is `Some`, opens the
/// repository at that path; otherwise opens at the current working directory.
/// `base_branch` defaults to `main` or `master` when omitted.
pub fn run_info<P: AsRef<Path>>(base_branch: Option<&str>, repo_path: Option<P>) -> Result<String> {
    use crate::data::{
        AiInfo, BranchInfo, FieldExplanation, FileStatusInfo, RepositoryView, VersionInfo,
        WorkingDirectoryInfo,
    };
    use crate::git::{GitRepository, RemoteInfo};
    use crate::utils::ai_scratch;

    // Resolve the repo location: the injected path, or the current working
    // directory as the default (resolved here at the entry point). Both branches
    // open via `open_at`, so nothing falls back to a no-arg CWD open.
    let repo = if let Some(path) = repo_path {
        GitRepository::open_at(path).context("Failed to open git repository at the given path")?
    } else {
        let cwd = std::env::current_dir().context("Failed to determine current directory")?;
        GitRepository::open_at(cwd)
            .context("Failed to open git repository. Make sure you're in a git repository.")?
    };

    // Resolve the workdir of the opened repo once; all sibling reads (PR
    // template, branch PRs via `gh`, AI scratch dir) anchor to it so they can
    // never silently mix data from the ambient CWD with the injected repo.
    let repo_root = repo
        .workdir()
        .context("repository has no working directory (bare repositories are not supported)")?;

    let current_branch = repo
        .get_current_branch()
        .context("Failed to get current branch. Make sure you're not in detached HEAD state.")?;

    let resolved_base = match base_branch {
        Some(branch) => {
            if !repo.branch_exists(branch)? {
                anyhow::bail!("Base branch '{branch}' does not exist");
            }
            branch.to_string()
        }
        None => {
            if repo.branch_exists("main")? {
                "main".to_string()
            } else if repo.branch_exists("master")? {
                "master".to_string()
            } else {
                anyhow::bail!("No default base branch found (main or master)");
            }
        }
    };

    let commit_range = format!("{resolved_base}..HEAD");

    let wd_status = repo.get_working_directory_status()?;
    let working_directory = WorkingDirectoryInfo {
        clean: wd_status.clean,
        untracked_changes: wd_status
            .untracked_changes
            .into_iter()
            .map(|fs| FileStatusInfo {
                status: fs.status,
                file: fs.file,
            })
            .collect(),
    };

    let remotes = RemoteInfo::get_all_remotes(repo.repository())?;
    let commits = repo.get_commits_in_range(&commit_range)?;

    let (pr_template, pr_template_location) = match InfoCommand::read_pr_template(repo_root).ok() {
        Some((content, location)) => (Some(content), Some(location)),
        None => (None, None),
    };

    let branch_prs = InfoCommand::get_branch_prs(&current_branch, repo_root)
        .ok()
        .filter(|prs| !prs.is_empty());

    let versions = Some(VersionInfo {
        omni_dev: env!("CARGO_PKG_VERSION").to_string(),
    });

    let ai_scratch_path = ai_scratch::get_ai_scratch_dir_at(repo_root)
        .context("Failed to determine AI scratch directory")?;
    let ai_info = AiInfo {
        scratch: ai_scratch_path.to_string_lossy().to_string(),
    };

    let mut repo_view = RepositoryView {
        versions,
        explanation: FieldExplanation::default(),
        working_directory,
        remotes,
        ai: ai_info,
        branch_info: Some(BranchInfo {
            branch: current_branch,
        }),
        pr_template,
        pr_template_location,
        branch_prs,
        commits,
    };

    repo_view.to_yaml_output()
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use git2::{Repository, Signature};
    use tempfile::TempDir;

    fn init_repo_with_commits() -> (TempDir, Vec<git2::Oid>) {
        let tmp_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
        std::fs::create_dir_all(&tmp_root).unwrap();
        let temp_dir = tempfile::tempdir_in(&tmp_root).unwrap();
        let repo_path = temp_dir.path();
        let repo = Repository::init(repo_path).unwrap();
        {
            let mut config = repo.config().unwrap();
            config.set_str("user.name", "Test").unwrap();
            config.set_str("user.email", "test@example.com").unwrap();
            config.set_str("init.defaultBranch", "main").unwrap();
        }

        // Re-point HEAD at refs/heads/main so the first commit lands on "main"
        repo.set_head("refs/heads/main").unwrap();

        let signature = Signature::now("Test", "test@example.com").unwrap();
        let mut commits = Vec::new();
        for (i, msg) in ["base: init", "feat: work"].iter().enumerate() {
            std::fs::write(repo_path.join("f.txt"), format!("c{i}")).unwrap();
            let mut idx = repo.index().unwrap();
            idx.add_path(std::path::Path::new("f.txt")).unwrap();
            idx.write().unwrap();
            let tree_id = idx.write_tree().unwrap();
            let tree = repo.find_tree(tree_id).unwrap();
            let parents: Vec<git2::Commit<'_>> = match commits.last() {
                Some(id) => vec![repo.find_commit(*id).unwrap()],
                None => vec![],
            };
            let parent_refs: Vec<&git2::Commit<'_>> = parents.iter().collect();
            let oid = repo
                .commit(
                    Some("HEAD"),
                    &signature,
                    &signature,
                    msg,
                    &tree,
                    &parent_refs,
                )
                .unwrap();
            commits.push(oid);
        }
        (temp_dir, commits)
    }

    #[test]
    fn run_info_default_branch_uses_main() {
        let (temp_dir, _commits) = init_repo_with_commits();
        // With only a `main` branch, HEAD==main → main..HEAD is empty, so the
        // output lacks commits but still returns YAML with branch_info.
        let yaml = run_info(None, Some(temp_dir.path())).unwrap();
        assert!(
            yaml.contains("branch:"),
            "yaml should include branch_info: {yaml}"
        );
    }

    #[test]
    fn execute_against_injected_repo_succeeds() {
        // Drives `execute()` (not just `run_info`) so its run_info+println body
        // is covered deterministically via the injected repo path. Those lines
        // were previously only hit by the live-repo dispatch test and flickered
        // covered<->uncovered depending on the checkout state.
        let (temp_dir, _commits) = init_repo_with_commits();
        InfoCommand { base_branch: None }
            .execute(Some(temp_dir.path()))
            .unwrap();
    }

    #[test]
    fn run_info_with_explicit_missing_base_errors() {
        let (temp_dir, _commits) = init_repo_with_commits();
        let err = run_info(Some("no-such-branch"), Some(temp_dir.path())).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.contains("no-such-branch"),
            "expected missing-branch error: {msg}"
        );
    }

    #[test]
    fn run_info_no_default_base_branch_errors() {
        // Init an empty repo with only a non-main branch.
        let tmp_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
        std::fs::create_dir_all(&tmp_root).unwrap();
        let temp_dir = tempfile::tempdir_in(&tmp_root).unwrap();
        let repo = Repository::init(temp_dir.path()).unwrap();
        {
            let mut config = repo.config().unwrap();
            config.set_str("user.name", "Test").unwrap();
            config.set_str("user.email", "test@example.com").unwrap();
        }
        let signature = Signature::now("Test", "test@example.com").unwrap();
        // Create on a non-default branch "dev" only.
        repo.set_head("refs/heads/dev").unwrap();
        std::fs::write(temp_dir.path().join("f.txt"), "c").unwrap();
        let mut idx = repo.index().unwrap();
        idx.add_path(std::path::Path::new("f.txt")).unwrap();
        idx.write().unwrap();
        let tree_id = idx.write_tree().unwrap();
        let tree = repo.find_tree(tree_id).unwrap();
        repo.commit(Some("HEAD"), &signature, &signature, "first", &tree, &[])
            .unwrap();

        let err = run_info(None, Some(temp_dir.path())).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("main or master"), "got: {msg}");
    }

    #[test]
    fn run_info_with_invalid_path_returns_error() {
        let err = run_info(None, Some("/no/such/path/exists")).unwrap_err();
        let msg = format!("{err:#}");
        assert!(
            msg.to_lowercase().contains("git") || msg.to_lowercase().contains("repo"),
            "expected git/repo error, got: {msg}"
        );
    }

    /// The injected `repo_path` fully determines the repository with no
    /// dependence on the process current working directory — the path is passed
    /// directly rather than via any process-CWD mutation.
    #[test]
    fn run_info_uses_injected_repo_without_cwd() {
        let (temp_dir, _commits) = init_repo_with_commits();
        let yaml = run_info(None, Some(temp_dir.path())).unwrap();
        assert!(yaml.contains("branch:"));
    }

    #[test]
    fn run_info_with_explicit_existing_base_succeeds() {
        let (temp_dir, _commits) = init_repo_with_commits();
        // Explicitly pass "main" as base — branch exists, validation succeeds.
        let yaml = run_info(Some("main"), Some(temp_dir.path())).unwrap();
        assert!(yaml.contains("branch:"));
    }

    #[test]
    fn run_info_falls_back_to_master_when_main_missing() {
        // Init a repo with a `master` branch (no `main`) — exercises the
        // master fallback in the default-base resolution.
        let tmp_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
        std::fs::create_dir_all(&tmp_root).unwrap();
        let temp_dir = tempfile::tempdir_in(&tmp_root).unwrap();
        let repo = Repository::init(temp_dir.path()).unwrap();
        {
            let mut cfg = repo.config().unwrap();
            cfg.set_str("user.name", "Test").unwrap();
            cfg.set_str("user.email", "test@example.com").unwrap();
        }
        repo.set_head("refs/heads/master").unwrap();
        let signature = Signature::now("Test", "test@example.com").unwrap();
        std::fs::write(temp_dir.path().join("f.txt"), "x").unwrap();
        let mut idx = repo.index().unwrap();
        idx.add_path(std::path::Path::new("f.txt")).unwrap();
        idx.write().unwrap();
        let tree_id = idx.write_tree().unwrap();
        let tree = repo.find_tree(tree_id).unwrap();
        repo.commit(Some("HEAD"), &signature, &signature, "init", &tree, &[])
            .unwrap();

        let yaml = run_info(None, Some(temp_dir.path())).unwrap();
        assert!(yaml.contains("branch:"));
    }

    /// Exercises the `read_pr_template` Some arm by placing a PR template in
    /// the injected repo root's `.github/` — proving the template is read from
    /// the repo root, not the process current working directory.
    #[test]
    fn run_info_picks_up_pr_template_from_repo_root() {
        let (temp_dir, _commits) = init_repo_with_commits();
        let github_dir = temp_dir.path().join(".github");
        std::fs::create_dir_all(&github_dir).unwrap();
        std::fs::write(
            github_dir.join("pull_request_template.md"),
            "## Sample Template",
        )
        .unwrap();

        let yaml = run_info(None, Some(temp_dir.path())).unwrap();
        assert!(
            yaml.contains("pr_template:") || yaml.contains("Sample Template"),
            "expected PR template info in yaml: {yaml}"
        );
    }

    /// "No silent mix" guard: `read_pr_template` resolves only against its
    /// `repo_root` argument and has **no** fallback to the ambient CWD. A repo
    /// root with a template returns it; a different root without one errors —
    /// even though the process CWD (the omni-dev checkout) *does* ship a
    /// `.github/pull_request_template.md`. This is the regression guard for the
    /// silent-mix bug the injection closes.
    #[test]
    fn read_pr_template_anchors_to_repo_root() {
        let tmp_root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tmp");
        std::fs::create_dir_all(&tmp_root).unwrap();

        let with = tempfile::tempdir_in(&tmp_root).unwrap();
        std::fs::create_dir_all(with.path().join(".github")).unwrap();
        std::fs::write(
            with.path().join(".github/pull_request_template.md"),
            "## Marker ABC",
        )
        .unwrap();
        let (content, location) = InfoCommand::read_pr_template(with.path()).unwrap();
        assert!(content.contains("Marker ABC"));
        assert!(location.contains("pull_request_template.md"));

        let without = tempfile::tempdir_in(&tmp_root).unwrap();
        assert!(
            InfoCommand::read_pr_template(without.path()).is_err(),
            "read_pr_template must not fall back to the ambient CWD template"
        );
    }
}