compare-changes 0.12.18

Reimplementation of GitHub file paths pattern matcher
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
#![cfg(feature = "cli")]
use assert_cmd::cargo::cargo_bin_cmd;
use serde_json;
use std::fs;
use std::path::Path;
#[cfg(unix)]
use std::process::Command;
use tempfile::{TempDir, tempdir};

fn prepare_workflow_with_patterns(patterns: &[&str]) -> TempDir {
    let temp = tempdir().unwrap();
    let workflows = temp.path().join(".github/workflows");
    fs::create_dir_all(&workflows).unwrap();

    let src = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/wildcard-template.yml");
    let dst = workflows.join("template.yml");
    fs::copy(&src, &dst).unwrap();

    // Read template and replace the "paths:" section robustly while preserving indentation.
    let template_yaml = fs::read_to_string(&src).unwrap();
    let mut out_lines: Vec<String> = Vec::new();
    let mut inserted = false;
    for line in template_yaml.lines() {
        if !inserted && line.trim_start().starts_with("paths:") {
            let indent: String = line.chars().take_while(|c| c.is_whitespace()).collect();
            out_lines.push(format!("{}paths:", indent));
            for p in patterns {
                out_lines.push(format!("{}  - \"{}\"", indent, p));
            }
            inserted = true;
        } else {
            out_lines.push(line.to_string());
        }
    }
    let yaml = if inserted { out_lines.join("\n") } else { template_yaml };
    fs::write(&dst, yaml).unwrap();

    temp
}

fn run_bin_with_changes(temp: &TempDir, changes: &[&str], debug: bool) -> (String, String) {
    let changes = serde_json::to_string(&changes).unwrap();

    let mut binding = cargo_bin_cmd!("compare-changes");
    let mut cmd = binding
        .current_dir(temp.path())
        .arg("--workflow")
        .arg("template.yml")
        .arg("--changes")
        .arg(&changes);

    if debug {
        cmd = cmd.arg("--debug");
    }

    let output = cmd.output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout).to_string();
    let stderr = String::from_utf8_lossy(&output.stderr).to_string();
    (stdout, stderr)
}

#[cfg(unix)]
fn run_git(temp: &TempDir, args: &[&str]) {
    let output = Command::new("git").current_dir(temp.path()).args(args).output().unwrap();

    assert!(
        output.status.success(),
        "git {:?} failed:\n{}",
        args,
        String::from_utf8_lossy(&output.stderr)
    );
}

#[cfg(unix)]
#[test]
fn test_find_preserves_git_pathnames() {
    let temp = tempdir().unwrap();
    run_git(&temp, &["init", "--quiet"]);
    run_git(&temp, &["config", "user.email", "test@example.com"]);
    run_git(&temp, &["config", "user.name", "Test User"]);
    run_git(&temp, &["config", "commit.gpgSign", "false"]);

    fs::write(temp.path().join("baseline.txt"), "baseline").unwrap();
    run_git(&temp, &["add", "--all"]);
    run_git(&temp, &["commit", "--quiet", "-m", "baseline"]);

    fs::create_dir(temp.path().join("src")).unwrap();
    let expected = vec![
        " leading.sh".to_string(),
        "src/line\nbreak.sh".to_string(),
        "src/quote\"name.sh".to_string(),
        "src/\u{e9}vil.sh".to_string(),
        "trailing.sh ".to_string(),
    ];
    for path in &expected {
        fs::write(temp.path().join(path), "changed").unwrap();
    }
    run_git(&temp, &["add", "--all"]);
    run_git(&temp, &["commit", "--quiet", "-m", "changed paths"]);

    let event_path = temp.path().join("event.json");
    let output_path = temp.path().join("github-output.txt");
    fs::write(&event_path, r#"{"pull_request":{}}"#).unwrap();

    let output = cargo_bin_cmd!("compare-changes")
        .current_dir(temp.path())
        .arg("--find")
        .env("GITHUB_EVENT_NAME", "pull_request")
        .env("GITHUB_EVENT_PATH", event_path)
        .env("GITHUB_OUTPUT", &output_path)
        .output()
        .unwrap();

    assert!(
        output.status.success(),
        "compare-changes failed:\n{}",
        String::from_utf8_lossy(&output.stderr)
    );

    let github_output = fs::read_to_string(output_path).unwrap();
    let files: Vec<String> = serde_json::from_str(github_output.trim().strip_prefix("array=").unwrap()).unwrap();
    assert_eq!(files, expected);
}

#[cfg(unix)]
#[test]
fn test_validate_includes_non_ignored_files() {
    let paths = [
        ("tracked.txt", "tracked.txt"),
        ("new.rs", "new.rs"),
        (" leading.rs", " leading.rs"),
        ("trailing.rs ", "trailing.rs "),
        ("src/quoted*.rs", "src/quoted\"name.rs"),
        ("src/line*.rs", "src/line\nbreak.rs"),
        ("src/\u{e9}vil.rs", "src/\u{e9}vil.rs"),
    ];
    let patterns: Vec<&str> = paths.iter().map(|(pattern, _)| *pattern).collect();
    let temp = prepare_workflow_with_patterns(&patterns);
    run_git(&temp, &["init", "--quiet"]);

    for (_, path) in paths {
        let path = temp.path().join(path);
        fs::create_dir_all(path.parent().unwrap()).unwrap();
        fs::write(path, "asset").unwrap();
    }

    for staged in [false, true] {
        if staged {
            run_git(&temp, &["add", "tracked.txt"]);
        }

        let output = cargo_bin_cmd!("compare-changes")
            .current_dir(temp.path())
            .arg("--validate")
            .output()
            .unwrap();
        assert!(output.status.success(), "validation failed:\n{}", String::from_utf8_lossy(&output.stderr));
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains(&format!("{} patterns across 1 file match at least one file!", patterns.len())),
            "expected validation of the untracked workflow, got:\n{}",
            stdout
        );
    }
}

#[cfg(unix)]
#[test]
fn test_validate_excludes_ignored_files() {
    let patterns = ["ignored.txt", "ignored-directory/**", "info-excluded.txt"];
    let temp = prepare_workflow_with_patterns(&patterns);
    run_git(&temp, &["init", "--quiet"]);
    fs::write(
        temp.path().join(".gitignore"),
        "ignored.txt\nignored-directory/\n.github/workflows/ignored.yml\n",
    )
    .unwrap();
    fs::write(temp.path().join(".git/info/exclude"), "info-excluded.txt\n").unwrap();
    fs::create_dir(temp.path().join("ignored-directory")).unwrap();
    for path in ["ignored.txt", "ignored-directory/file.txt", "info-excluded.txt"] {
        fs::write(temp.path().join(path), "ignored").unwrap();
    }
    fs::write(
        temp.path().join(".github/workflows/ignored.yml"),
        "on:\n  push:\n    paths:\n      - missing.rs\n",
    )
    .unwrap();

    let output = cargo_bin_cmd!("compare-changes")
        .current_dir(temp.path())
        .arg("--validate")
        .output()
        .unwrap();
    assert_eq!(output.status.code(), Some(5));
    let stderr = String::from_utf8_lossy(&output.stderr);
    for pattern in patterns {
        assert!(
            stderr.contains(&format!("no match for {}", pattern)),
            "expected no match for '{}':\n{}",
            pattern,
            stderr
        );
    }
    assert!(
        stderr.contains("3 path patterns did not match any file"),
        "unexpected validation failures:\n{}",
        stderr
    );
    assert!(!stderr.contains("ignored.yml"), "validated an ignored workflow:\n{}", stderr);
}

#[test]
fn test_changes_output() {
    let temp = prepare_workflow_with_patterns(&["1", "2", "3"]);
    let (stdout, stderr) = run_bin_with_changes(&temp, &["foo/bar", "baz", "3"], true);

    for expected in ["1", "2", "3", "foo/bar", "baz", "path '3' matched file '3'", "changed=true"] {
        assert!(stdout.contains(expected), "Expected output to contain '{}'", expected);
        assert!(!stderr.contains(expected), "Did not expect '{}' in stderr", expected);
    }
}

#[test]
fn test_valid_stray_closing_bracket() {
    let temp = prepare_workflow_with_patterns(&["abc]"]);
    let (stdout, stderr) = run_bin_with_changes(&temp, &["abc]"], true);

    for expected in ["path 'abc]' matched file 'abc]'", "changed=true"] {
        assert!(stdout.contains(expected), "Expected output to contain '{}'", expected);
        assert!(!stderr.contains(expected), "Did not expect '{}' in stderr", expected);
    }
}

#[test]
fn test_valid_standalone_plus() {
    let pat = "+foo";
    let temp = prepare_workflow_with_patterns(&[pat]);
    let (stdout, stderr) = run_bin_with_changes(&temp, &["foo"], true);

    let expected_path = format!("path '{}' matched file 'foo'", pat);
    assert!(stdout.contains(&expected_path), "Expected output to contain '{}'", expected_path);
    assert!(stdout.contains("changed=true"), "Expected output to contain 'changed=true'");
    assert!(!stderr.contains(&expected_path), "Did not expect '{}' in stderr", expected_path);
    assert!(!stderr.contains("changed=true"), "Did not expect 'changed=true' in stderr");
}

#[test]
fn test_valid_standalone_questionmark() {
    let pat = "?bar";
    let temp = prepare_workflow_with_patterns(&[pat]);
    let (stdout, stderr) = run_bin_with_changes(&temp, &["bar"], true);

    let expected_path = format!("path '{}' matched file 'bar'", pat);
    assert!(stdout.contains(&expected_path), "Expected output to contain '{}'", expected_path);
    assert!(stdout.contains("changed=true"), "Expected output to contain 'changed=true'");
    assert!(!stderr.contains(&expected_path), "Did not expect '{}' in stderr", expected_path);
    assert!(!stderr.contains("changed=true"), "Did not expect 'changed=true' in stderr");
}

#[test]
fn test_invalid_stray_opening_bracket() {
    let pat = "[abc";
    let temp = prepare_workflow_with_patterns(&[pat]);
    let (stdout, stderr) = run_bin_with_changes(&temp, &["foo/bar"], false);

    let msg = "Failed to compare paths: found end of input expected any, or ']'";

    assert!(
        stderr.contains(msg),
        "expected exact error message in stderr\n\nEXPECTED:\n{}\n\nSTDERR:\n{}",
        msg,
        stderr
    );
    assert!(!stdout.contains(msg), "did not expect the error message in stdout\n\nSTDOUT:\n{}", stdout);
}

#[test]
fn test_invalid_bracket_range() {
    let pat = "[z-a]";
    let temp = prepare_workflow_with_patterns(&[pat]);
    let (stdout, stderr) = run_bin_with_changes(&temp, &["foo/bar"], false);

    let expected = "invalid bracket range z-a";
    let msg = format!("Failed to compare paths: {}", expected);

    assert!(
        stderr.contains(&msg),
        "expected exact error message in stderr\n\nEXPECTED:\n{}\n\nSTDERR:\n{}",
        msg,
        stderr
    );
    assert!(
        !stdout.contains(&msg),
        "did not expect the error message in stdout\n\nSTDOUT:\n{}",
        stdout
    );
}

#[test]
fn test_empty_bracket() {
    let pat = "[]";
    let temp = prepare_workflow_with_patterns(&[pat]);
    let (stdout, stderr) = run_bin_with_changes(&temp, &["foo/bar"], false);

    let expected = "empty bracket";
    let msg = format!("Failed to compare paths: {}", expected);

    assert!(
        stderr.contains(&msg),
        "expected exact error message in stderr\n\nEXPECTED:\n{}\n\nSTDERR:\n{}",
        msg,
        stderr
    );
    assert!(
        !stdout.contains(&msg),
        "did not expect the error message in stdout\n\nSTDOUT:\n{}",
        stdout
    );
}

#[test]
fn test_negation_excludes_file() {
    let temp = prepare_workflow_with_patterns(&["*.md", "!README.md"]);
    let (stdout, stderr) = run_bin_with_changes(&temp, &["README.md"], false);

    assert!(stdout.contains("changed=false"), "expected 'changed=false' in stdout, got:\n{}", stdout);
    assert!(
        !stdout.contains("matched file"),
        "did not expect a match line in stdout, got:\n{}",
        stdout
    );
    assert!(stderr.is_empty(), "did not expect any stderr, got:\n{}", stderr);
}

#[test]
fn test_negation_allows_other_matches() {
    let temp = prepare_workflow_with_patterns(&["*.md", "!README.md"]);
    let (stdout, stderr) = run_bin_with_changes(&temp, &["README.md", "hello.md"], false);

    for expected in ["path '*.md' matched file 'hello.md'", "changed=true"] {
        assert!(stdout.contains(expected), "expected '{}' in stdout, got:\n{}", expected, stdout);
    }
    assert!(stderr.is_empty(), "did not expect any stderr, got:\n{}", stderr);
}

#[test]
fn test_negation_re_included_by_later_pattern() {
    let temp = prepare_workflow_with_patterns(&["*.md", "!README.md", "README*"]);
    let (stdout, stderr) = run_bin_with_changes(&temp, &["README.md"], false);

    for expected in ["path 'README*' matched file 'README.md'", "changed=true"] {
        assert!(stdout.contains(expected), "expected '{}' in stdout, got:\n{}", expected, stdout);
    }
    assert!(stderr.is_empty(), "did not expect any stderr, got:\n{}", stderr);
}

#[test]
fn test_exitcode_usage() {
    use std::collections::HashMap;
    use std::fs;
    use std::path::Path;

    // Extract exitcode function names from the macro definition
    let exitcode_file = Path::new(env!("CARGO_MANIFEST_DIR")).join("src/exitcode/mod.rs");
    let exitcode_content = fs::read_to_string(&exitcode_file).unwrap();

    let mut exitcodes = Vec::new();
    let mut in_macro = false;
    for line in exitcode_content.lines() {
        if line.contains("define_exitcodes!") && line.contains("{") {
            in_macro = true;
            continue;
        }
        if in_macro && line.trim() == "}" {
            break;
        }
        if in_macro {
            if let Some(pos) = line.find("=>") {
                let fn_name = line[..pos].trim().trim_end_matches(',');
                if !fn_name.is_empty() {
                    exitcodes.push(fn_name.to_string());
                }
            }
        }
    }

    // Count usage of each exitcode function in src/
    let mut counts: HashMap<String, usize> = HashMap::new();
    let src_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("src");

    fn visit_dir(dir: &Path, counts: &mut HashMap<String, usize>, exitcodes: &[String]) {
        if let Ok(entries) = fs::read_dir(dir) {
            for entry in entries.flatten() {
                let path = entry.path();
                if path.is_dir() {
                    visit_dir(&path, counts, exitcodes);
                } else if path.extension().map_or(false, |e| e == "rs") {
                    if let Ok(contents) = fs::read_to_string(&path) {
                        for exitcode in exitcodes {
                            let pattern = format!("exitcode::{}(", exitcode);
                            *counts.entry(exitcode.clone()).or_insert(0) += contents.matches(&pattern).count();
                        }
                    }
                }
            }
        }
    }

    visit_dir(&src_dir, &mut counts, &exitcodes);

    // Assert each exitcode is called exactly once
    for exitcode in &exitcodes {
        let count = counts.get(exitcode).copied().unwrap_or(0);
        assert_eq!(count, 1, "expected exactly 1 call to exitcode::{}, found {}", exitcode, count);
    }
}