prek 0.5.7

A fast Git hook manager written in Rust, designed as a drop-in alternative to pre-commit, reimagined.
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
//! Integration tests for detecting file modifications made by hooks.

use std::time::{Duration, SystemTime};

use anyhow::Result;
use assert_fs::prelude::*;

use crate::common::{TestEnv, cmd_snapshot};

fn remove_loose_blob(context: &TestEnv, filename: &str) -> Result<()> {
    let output = context
        .git()
        .command()
        .arg("hash-object")
        .arg(filename)
        .output()?;
    assert!(output.status.success(), "git hash-object should succeed");
    let blob = String::from_utf8(output.stdout)?;
    let blob = blob.trim_ascii();
    let object_path = context
        .child(".git")
        .child("objects")
        .child(&blob[..2])
        .child(&blob[2..]);
    fs_err::remove_file(object_path.path())?;
    Ok(())
}

#[test]
#[cfg(unix)]
fn identical_rewrite_with_stat_change_is_not_modified() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: rewrite-identical
                name: rewrite-identical
                language: system
                entry: python3 rewrite.py
                files: \.txt$
    "})
        .with_file(
            "rewrite.py",
            indoc::indoc! {r"
        from pathlib import Path
        import os
        import sys
        import time

        for filename in sys.argv[1:]:
            path = Path(filename)
            path.write_text(path.read_text())
            timestamp = time.time() + 10
            os.utime(path, (timestamp, timestamp))
    "},
        )
        .with_file("file.txt", "original\n")
        .init_git();

    for auto_refresh in ["true", "false"] {
        context
            .git()
            .run(["config", "diff.autoRefreshIndex", auto_refresh]);

        insta::allow_duplicates! {
            cmd_snapshot!(context, context.run(), @r#"
            success: true
            exit_code: 0
            ----- stdout -----
            rewrite-identical........................................................Passed

            ----- stderr -----
            "#);
        }
    }
}

#[test]
fn modifying_hook_is_reported() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: modify
                name: modify
                language: system
                entry: python3 -c "from pathlib import Path; Path('file.txt').write_text('changed\n')"
                pass_filenames: false
    "#})
        .with_file("file.txt", "original\n").init_git();

    cmd_snapshot!(context, context.run(), @r#"
    success: false
    exit_code: 1
    ----- stdout -----
    modify...................................................................Failed
    - hook id: modify
    - files were modified by this hook

    ----- stderr -----
    "#);
}

#[test]
fn binary_diff_snapshots_use_full_object_ids() -> Result<()> {
    let context = TestEnv::new();
    let status = context
        .git()
        .command()
        .args(["init", "--object-format=sha1"])
        .status()?;
    assert!(
        status.success(),
        "initializing SHA-1 repository should succeed"
    );

    let context = context
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: write-first
                name: write-first
                language: system
                entry: python3 -c "from pathlib import Path; Path('binary.dat').write_bytes(b'variant-20663\n')"
                pass_filenames: false
                priority: 0
              - id: write-second
                name: write-second
                language: system
                entry: python3 -c "from pathlib import Path; Path('binary.dat').write_bytes(b'variant-30375\n')"
                pass_filenames: false
                priority: 1
    "#})
        .with_file(".gitattributes", "binary.dat -diff\n")
        .with_file("binary.dat", "original\n");

    // The two replacement blobs have distinct SHA-1s whose first seven
    // hexadecimal digits are both `4b8e34c`.

    context.git().add(".");

    let status = context
        .git()
        .command()
        .args(["config", "core.abbrev", "7"])
        .status()?;
    assert!(status.success(), "setting core.abbrev should succeed");

    let output = context.run().output()?;
    assert!(
        !output.status.success(),
        "both hooks should modify the file"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert_eq!(
        stdout.matches("files were modified by this hook").count(),
        2,
        "both binary rewrites should produce distinct snapshots.\n\
         stdout:\n{stdout}"
    );

    Ok(())
}

#[test]
fn all_files_with_existing_unstaged_changes_uses_snapshot_baseline() -> Result<()> {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: modify
                name: modify
                language: system
                entry: python3 -c "from pathlib import Path; Path('hook.txt').write_text('changed\n')"
                pass_filenames: false
    "#})
        .with_file("file.txt", "original\n")
        .with_file("hook.txt", "original\n").init_git();

    context.write_file("file.txt", "unstaged\n");

    let output = context
        .run()
        .arg("--all-files")
        .env("RUST_LOG", "prek::git=trace")
        .output()?;

    assert!(
        !output.status.success(),
        "--all-files should still detect hook modifications when the worktree starts dirty"
    );

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("files were modified by this hook"));

    let stderr = String::from_utf8_lossy(&output.stderr);
    let diff_worktree_calls = stderr.matches("diff_worktree").count();
    assert_eq!(
        diff_worktree_calls, 2,
        "Expected a full before/after diff comparison for dirty `--all-files`, found {diff_worktree_calls}.\n\
         Trace output:\n{stderr}"
    );

    Ok(())
}

#[test]
fn all_files_clean_missing_blob_ignores_diff_snapshot_errors() -> Result<()> {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: noop
                name: noop
                language: system
                entry: python3 -c "pass"
                pass_filenames: false
    "#})
        .with_file("file.txt", "original\n")
        .init_git();

    context.git().commit("init");

    remove_loose_blob(&context, "file.txt")?;

    // Make the index stat data stale while keeping file content unchanged. A
    // full `git diff` now exits non-zero because the blob is missing, but its
    // stdout is still a usable best-effort before/after snapshot.
    fs_err::OpenOptions::new()
        .write(true)
        .open(context.child("file.txt").path())?
        .set_modified(SystemTime::now() + Duration::from_secs(10))?;

    let output = context
        .run()
        .arg("--all-files")
        .env("RUST_LOG", "prek::git=trace")
        .output()?;

    assert!(
        output.status.success(),
        "`--all-files` should not require blob objects when hooks leave a clean tree.\n\
         stdout:\n{}\n\
         stderr:\n{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    let ignored_diff_errors = stderr
        .matches("Continuing with git diff stdout despite non-zero exit status")
        .count();
    assert_eq!(
        ignored_diff_errors, 2,
        "Expected before/after git diff errors to be logged and ignored, found {ignored_diff_errors}.\n\
         Trace output:\n{stderr}"
    );
    assert!(
        !stderr.contains("Command `git diff` exited with an error"),
        "missing blobs should not turn hook modification detection into a fatal git diff error.\n\
         stderr:\n{stderr}"
    );

    Ok(())
}

#[test]
fn later_project_snapshots_diff_left_by_previous_project() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: root-noop
                name: root-noop
                language: system
                entry: python3 -c "pass"
                always_run: true
                pass_filenames: false
    "#})
        .with_file(
            "child/.pre-commit-config.yaml",
            indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: child-modify
                name: child-modify
                language: system
                entry: python3 -c "from pathlib import Path; Path('child.txt').write_text('changed\n')"
                always_run: true
                pass_filenames: false
    "#},
        )
        .with_file("child/child.txt", "original\n").init_git();

    cmd_snapshot!(context, context.run(), @r#"
    success: false
    exit_code: 1
    ----- stdout -----
    × child
      child-modify...........................................................Failed
      - hook id: child-modify
      - files were modified by this hook
    ✓ <workspace>
      root-noop..............................................................Passed

    ----- stderr -----
    "#);
}

#[test]
fn read_only_builtin_hook_does_not_run_diff_detection() -> Result<()> {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r"
        repos:
          - repo: builtin
            hooks:
              - id: check-toml
    "})
        .with_file("pyproject.toml", "[project]\nname = \"demo\"\n")
        .init_git();

    let output = context
        .run()
        .arg("--all-files")
        .env("RUST_LOG", "prek::git=trace")
        .output()?;

    assert!(output.status.success(), "prek should succeed");

    let stderr = String::from_utf8_lossy(&output.stderr);
    let diff_worktree_calls = stderr.matches("diff_worktree").count();
    assert_eq!(
        diff_worktree_calls, 0,
        "Expected no diff_worktree calls for read-only builtin hooks, found {diff_worktree_calls}.\n\
         Trace output:\n{stderr}"
    );

    Ok(())
}

#[test]
fn read_only_languages_do_not_run_diff_detection() -> Result<()> {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: fail
                name: fail
                language: fail
                entry: expected failure
                files: \.txt$
              - id: pygrep
                name: pygrep
                language: pygrep
                entry: not-present
                files: \.txt$
    "})
        .with_file("file.txt", "original\n")
        .init_git();

    let output = context
        .run()
        .arg("--all-files")
        .env("RUST_LOG", "prek::git=trace")
        .output()?;

    assert!(!output.status.success(), "the fail hook should fail");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("fail") && stdout.contains("Failed"));
    assert!(stdout.contains("pygrep") && stdout.contains("Passed"));
    assert!(!stdout.contains("files were modified by this hook"));

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        stderr.matches("diff_worktree").count(),
        0,
        "Read-only languages should not require a full worktree diff.\n\
         Trace output:\n{stderr}"
    );

    Ok(())
}

#[test]
fn same_group_known_modification_skips_diff_detection() -> Result<()> {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: builtin
            hooks:
              - id: end-of-file-fixer
                priority: 0
          - repo: local
            hooks:
              - id: noop
                name: noop
                language: system
                entry: python3 -c "pass"
                pass_filenames: false
                priority: 0
    "#})
        .with_file("file.txt", "missing newline")
        .init_git();

    let output = context.run().env("RUST_LOG", "prek::git=trace").output()?;

    assert!(
        !output.status.success(),
        "the builtin should report its modification"
    );
    assert_eq!(context.read("file.txt"), "missing newline\n");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout
            .lines()
            .any(|line| line.contains("noop") && line.contains("Passed"))
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        stderr.matches("diff_worktree").count(),
        0,
        "A known modification should make the same-group full diff unnecessary.\n\
         Trace output:\n{stderr}"
    );

    Ok(())
}

#[test]
fn same_group_known_modification_rebaselines_later_external_hook() -> Result<()> {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: builtin
            hooks:
              - id: end-of-file-fixer
                priority: 0
          - repo: local
            hooks:
              - id: same-group-noop
                name: same-group-noop
                language: system
                entry: python3 -c "pass"
                pass_filenames: false
                priority: 0
              - id: later-noop
                name: later-noop
                language: system
                entry: python3 -c "pass"
                pass_filenames: false
                priority: 1
    "#})
        .with_file("file.txt", "missing newline")
        .init_git();

    let output = context.run().env("RUST_LOG", "prek::git=trace").output()?;

    assert!(
        !output.status.success(),
        "the builtin should report its modification"
    );
    assert_eq!(context.read("file.txt"), "missing newline\n");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout
            .lines()
            .any(|line| line.contains("later-noop") && line.contains("Passed"))
    );

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        stderr.matches("diff_worktree").count(),
        2,
        "The later external hook should capture and compare the modified worktree.\n\
         Trace output:\n{stderr}"
    );

    Ok(())
}

#[test]
fn modifying_builtin_invalidates_baseline_for_later_external_hook() -> Result<()> {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: builtin
            hooks:
              - id: end-of-file-fixer
                priority: 0
          - repo: local
            hooks:
              - id: noop
                name: noop
                language: system
                entry: python3 -c "pass"
                pass_filenames: false
                priority: 1
    "#})
        .with_file("file.txt", "missing newline")
        .init_git();

    let output = context.run().env("RUST_LOG", "prek::git=trace").output()?;

    assert!(
        !output.status.success(),
        "the builtin should report its modification"
    );
    assert_eq!(context.read("file.txt"), "missing newline\n");

    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        stdout.contains("end-of-file-fixer") && stdout.contains("files were modified by this hook")
    );
    assert!(stdout.contains("noop") && stdout.contains("Passed"));

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        stderr.matches("diff_worktree").count(),
        2,
        "The later external hook should snapshot the builtin's change, then compare against it.\n\
         Trace output:\n{stderr}"
    );

    Ok(())
}

#[test]
fn failed_non_modifying_builtin_skips_diff_detection() -> Result<()> {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r"
        repos:
          - repo: builtin
            hooks:
              - id: mixed-line-ending
                args: ['--fix=no']
    "})
        .with_file("mixed.txt", "first\r\nsecond\n")
        .init_git();

    let output = context.run().env("RUST_LOG", "prek::git=trace").output()?;

    assert!(
        !output.status.success(),
        "mixed-line-ending should report the validation failure"
    );
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(stdout.contains("mixed.txt: mixed line endings"));
    assert!(!stdout.contains("files were modified by this hook"));

    let stderr = String::from_utf8_lossy(&output.stderr);
    assert_eq!(stderr.matches("diff_worktree").count(), 0);

    Ok(())
}