omnicoach 0.2.0

Lightweight, high-signal static analysis and command linter for Python and Rust
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
//! Differential VCS diff parsing and filtering utilities.

architecture_component!(Diff);

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::Command;

/// Errors that can occur during VCS detection or diff extraction.
#[derive(Debug, thiserror::Error)]
pub enum DiffError {
    /// No supported VCS repository found in working directory hierarchy.
    #[error("--diff requires a Git or Jujutsu repository, but none was found")]
    RepoNotFound,

    /// Required VCS command-line binary was not found in PATH.
    #[error(
        "{name} CLI ('{binary}') was not found in PATH. Please install it or ensure it is accessible."
    )]
    CliNotFound {
        /// The human-readable name of the VCS tool.
        name: &'static str,
        /// The CLI binary name.
        binary: &'static str,
    },

    /// Failed to execute the VCS subprocess command.
    #[error("failed to run {binary} CLI: {source}")]
    CliExecution {
        /// The CLI binary name.
        binary: &'static str,
        /// The underlying IO error.
        #[source]
        source: std::io::Error,
    },

    /// VCS diff command exited with a non-zero status.
    #[error("{binary} diff failed: {message}")]
    CommandFailed {
        /// The CLI binary name.
        binary: &'static str,
        /// The stderr error message from the CLI.
        message: String,
    },
}

/// The type of Version Control System detected.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VcsType {
    /// Git version control system.
    Git,
    /// Jujutsu (jj) version control system.
    Jujutsu,
}

/// Mapping of changed file paths to their 1-indexed changed line numbers.
pub type ChangedLines = HashMap<PathBuf, HashSet<usize>>;

/// Result of detecting differential VCS changes (VCS type, resolved revision, and changed lines).
pub type DetectedDiff = (VcsType, String, ChangedLines);

/// Runs the detected VCS diff command and parses the output into a map of absolute paths
/// mapped to their 1-indexed changed line numbers.
///
/// # Errors
///
/// Returns [`DiffError`] if no VCS repository is found, if subprocess execution fails,
/// or if command stderr is non-empty.
pub fn detect_vcs_diff(custom_rev: Option<&str>) -> Result<DetectedDiff, DiffError> {
    let Repository {
        root: repo_root,
        vcs_type,
    } = find_repo_root().ok_or(DiffError::RepoNotFound)?;

    let resolved_rev = match vcs_type {
        VcsType::Jujutsu => custom_rev.unwrap_or("immutable().."),
        VcsType::Git => custom_rev.unwrap_or("HEAD"),
    };

    let diff_content = match vcs_type {
        VcsType::Jujutsu => get_jj_diff(&repo_root, resolved_rev)?,
        VcsType::Git => get_git_diff(&repo_root, resolved_rev)?,
    };

    let parsed_diff = parse_git_diff(&diff_content);

    // Convert relative repository paths to absolute paths
    let mut absolute_diff = HashMap::new();
    for (rel_path, lines) in parsed_diff {
        let abs_path = repo_root.join(rel_path);
        absolute_diff.insert(abs_path, lines);
    }

    Ok((vcs_type, resolved_rev.to_string(), absolute_diff))
}

/// A version-controlled repository enclosing the current working directory.
struct Repository {
    /// The repository root directory.
    root: PathBuf,
    /// The VCS that manages the repository.
    vcs_type: VcsType,
}

/// Walks up from the current working directory to locate the repository root
/// and determine the active VCS type.
#[must_use]
fn find_repo_root() -> Option<Repository> {
    let mut dir = std::env::current_dir().ok()?;
    loop {
        if dir.join(".jj").is_dir() {
            return Some(Repository {
                root: dir,
                vcs_type: VcsType::Jujutsu,
            });
        }
        if dir.join(".git").exists() {
            return Some(Repository {
                root: dir,
                vcs_type: VcsType::Git,
            });
        }
        if !dir.pop() {
            break;
        }
    }
    None
}

/// Jujutsu CLI binary, both spawned and named in errors.
const JJ_BINARY: &str = "jj";
/// Git CLI binary, both spawned and named in errors.
const GIT_BINARY: &str = "git";

fn get_jj_diff(repo_root: &Path, rev: &str) -> Result<String, DiffError> {
    let mut cmd = Command::new(JJ_BINARY);
    cmd.current_dir(repo_root).arg("diff").arg("--git");
    if is_complex_jj_revset(rev) {
        cmd.arg("-r").arg(rev);
    } else {
        cmd.arg("--from").arg(rev);
    }
    run_vcs_command(cmd, "Jujutsu", JJ_BINARY)
}

fn is_complex_jj_revset(rev: &str) -> bool {
    rev.contains("..")
        || rev.contains("::")
        || rev.contains('(')
        || rev.contains(')')
        || rev.chars().any(|c| matches!(c, '|' | '&' | '~' | ' '))
}

fn get_git_diff(repo_root: &Path, rev: &str) -> Result<String, DiffError> {
    let mut cmd = Command::new(GIT_BINARY);
    cmd.current_dir(repo_root).args([
        "-c",
        "core.quotepath=false",
        "diff", // omni:ignore [repeated-literal] -- Git's subcommand, unrelated to Jujutsu's
        "--src-prefix=a/",
        "--dst-prefix=b/",
        rev,
    ]);
    run_vcs_command(cmd, "Git", GIT_BINARY)
}

fn run_vcs_command(
    mut cmd: Command,
    name: &'static str,
    binary: &'static str,
) -> Result<String, DiffError> {
    let output = cmd.output().map_err(|error| {
        if error.kind() == std::io::ErrorKind::NotFound {
            DiffError::CliNotFound { name, binary }
        } else {
            DiffError::CliExecution {
                binary,
                source: error,
            }
        }
    })?;

    if !output.status.success() {
        let error_message = String::from_utf8_lossy(&output.stderr).trim().to_string();
        return Err(DiffError::CommandFailed {
            binary,
            message: error_message,
        });
    }

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

/// Parses a unified git-compatible diff output and returns a mapping from relative file paths
/// to their 1-indexed changed line numbers in the new file.
#[must_use]
fn parse_git_diff(content: &str) -> HashMap<PathBuf, HashSet<usize>> {
    let mut changed_lines = HashMap::new();
    let mut current_file: Option<(PathBuf, HashSet<usize>)> = None;
    let mut line_counter = 0;
    let mut is_deleted = false;
    let mut expecting_file_header = true;

    for line in content.lines() {
        if line.starts_with("diff --git") {
            commit_file_changes(&mut current_file, is_deleted, &mut changed_lines);
            is_deleted = false;
            line_counter = 0;
            expecting_file_header = true;
        } else if line.starts_with("+++ ") && expecting_file_header {
            if let Some(parsed_path) = extract_diff_header_path(line) {
                current_file = Some((parsed_path, HashSet::new()));
            } else {
                is_deleted = true;
            }
            expecting_file_header = false;
        } else if line.starts_with("@@ ") {
            line_counter = parse_hunk_header(line).unwrap_or(0);
        } else if let Some((_, lines)) = current_file.as_mut() {
            if is_deleted || line_counter == 0 {
                continue;
            }
            if line.starts_with('+') {
                lines.insert(line_counter);
                line_counter += 1;
            } else if line.starts_with(' ') || line.is_empty() {
                line_counter += 1;
            }
        }
    }

    commit_file_changes(&mut current_file, is_deleted, &mut changed_lines);

    changed_lines
}

/// Commits a parsed file's changed line numbers into `changed_lines` if the file was not deleted.
fn commit_file_changes(
    current_file: &mut Option<(PathBuf, HashSet<usize>)>,
    is_deleted: bool,
    changed_lines: &mut ChangedLines,
) {
    if let Some((path, lines)) = current_file.take()
        && !is_deleted
        && !lines.is_empty()
    {
        changed_lines.insert(path, lines);
    }
}

/// Extracts the normalized relative file path from a `+++ b/...` diff header line, or `None` if `/dev/null`.
fn extract_diff_header_path(line: &str) -> Option<PathBuf> {
    let path_part = &line[4..];
    if path_part == "/dev/null" {
        return None;
    }
    let parsed_path = path_part
        .split_once('\t')
        .map_or(path_part, |(path, _)| path)
        .trim_matches('"');
    let parsed_path = parsed_path
        .strip_prefix("b/")
        .unwrap_or(parsed_path)
        .trim_matches('"');
    Some(PathBuf::from(parsed_path))
}

fn parse_hunk_header(line: &str) -> Option<usize> {
    // Example: @@ -1,3 +4,5 @@
    // We want to extract '4' from '+4,5'
    let header = line.split("@@").nth(1)?;
    let new_file_part = header.split('+').nth(1)?;
    let new_start_text = new_file_part.split(',').next()?.trim();
    new_start_text.parse().ok()
}

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

    #[test]
    fn test_parse_simple_diff() {
        let diff = indoc::indoc! {r"
            diff --git a/src/lib.rs b/src/lib.rs
            index 123456..789101 100644
            --- a/src/lib.rs
            +++ b/src/lib.rs
            @@ -1,3 +1,4 @@
             fn foo() {
            -    let x = 1;
            +    let y = 2;
            +    let z = 3;
             }
        "};
        let changed_lines = parse_git_diff(diff);
        let path = PathBuf::from("src/lib.rs");
        assert_eq!(changed_lines.get(&path), Some(&HashSet::from([2, 3])));
    }

    #[test]
    fn test_parse_single_line_hunk() {
        let diff = indoc::indoc! {r"
            diff --git a/test.py b/test.py
            index 111..222 100644
            --- a/test.py
            +++ b/test.py
            @@ -10 +10 @@
            -old
            +new
        "};
        let changed_lines = parse_git_diff(diff);
        let path = PathBuf::from("test.py");
        let lines = &changed_lines[&path];
        assert_eq!(lines.len(), 1);
        assert!(lines.contains(&10));
    }

    #[test]
    fn test_parse_deleted_file() {
        let diff = indoc::indoc! {r"
            diff --git a/test.py b/test.py
            deleted file mode 100644
            --- a/test.py
            +++ /dev/null
            @@ -1,2 +0,0 @@
            -def foo():
            -    pass
        "};
        let changed_lines = parse_git_diff(diff);
        assert!(changed_lines.is_empty());
    }

    #[test]
    fn test_parse_quoted_paths_with_spaces() {
        let diff = indoc::indoc! {r#"
            diff --git a/"some file.rs" b/"some file.rs"
            --- a/"some file.rs"
            +++ b/"some file.rs"
            @@ -1 +1,2 @@
            +// added comment
             
        "#};
        let changed_lines = parse_git_diff(diff);
        let path = PathBuf::from("some file.rs");
        assert!(changed_lines.contains_key(&path));
        assert!(changed_lines[&path].contains(&1));
    }

    #[test]
    fn test_parse_no_newline_warning() {
        let diff = indoc::indoc! {r"
            diff --git a/test.py b/test.py
            --- a/test.py
            +++ b/test.py
            @@ -1 +1,2 @@
            +def foo(): pass
            \ No newline at end of file
             
        "};
        let changed_lines = parse_git_diff(diff);
        let path = PathBuf::from("test.py");
        assert!(changed_lines[&path].contains(&1));
    }

    #[test]
    fn test_parse_path_containing_b_slash() {
        let diff = indoc::indoc! {r"
            diff --git a/some b/file.rs b/some b/file.rs
            --- a/some b/file.rs
            +++ b/some b/file.rs
            @@ -1 +1,2 @@
            +// comment
             
        "};
        let changed_lines = parse_git_diff(diff);
        let path = PathBuf::from("some b/file.rs");
        assert!(changed_lines.contains_key(&path));
        assert!(changed_lines[&path].contains(&1));
    }

    #[test]
    fn test_parse_diff_with_added_line_starting_with_plus_plus() {
        let diff = indoc::indoc! {r"
            diff --git a/test.py b/test.py
            --- a/test.py
            +++ b/test.py
            @@ -1,2 +1,3 @@
             def foo():
                pass
            +++ this looks like a file header but is actually an added line starting with ++
        "};
        let changed_lines = parse_git_diff(diff);
        let path = PathBuf::from("test.py");
        assert!(changed_lines.contains_key(&path));
        assert!(changed_lines[&path].contains(&3));
    }

    #[rstest::rstest]
    #[case("immutable()..", true)]
    #[case("@-..@", true)]
    #[case("main..@", true)]
    #[case("root()..@", true)]
    #[case("all()", true)]
    #[case("@-::@", true)]
    #[case("a | b", true)]
    #[case("a & b", true)]
    #[case("~a", true)]
    #[case("@-", false)]
    #[case("@", false)]
    #[case("main", false)]
    #[case("v1.0", false)]
    #[case("cad67343", false)]
    fn test_is_complex_jj_revset(#[case] revset: &str, #[case] expected: bool) {
        assert_eq!(is_complex_jj_revset(revset), expected);
    }
}