prek 0.5.6

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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
#[cfg(feature = "ci")]
use prek_consts::env_vars::EnvVars;

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

#[test]
fn run_basic() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r"
        repos:
          - repo: https://github.com/pre-commit/pre-commit-hooks
            rev: v5.0.0
            hooks:
              - id: trailing-whitespace
              - id: end-of-file-fixer
              - id: requirements-txt-fixer
                files: ^file\.txt$
              - id: check-json
    "})
        .with_files([
            ("file.txt", "z-project\na-project\n"),
            ("valid.json", "{}"),
            ("main.py", r#"print "abc"  "#),
        ])
        .init_git();

    cmd_snapshot!(context, context.run().arg("-q"), @"
    success: false
    exit_code: 1
    ----- stdout -----
    trim trailing whitespace.................................................Failed
    - hook id: trailing-whitespace
    - description: trims trailing whitespace
    - exit code: 1
    - files were modified by this hook

      Fixing main.py
    fix end of files.........................................................Failed
    - hook id: end-of-file-fixer
    - description: ensures that a file is either empty, or ends with one newline
    - exit code: 1
    - files were modified by this hook

      Fixing valid.json
      Fixing main.py
    fix requirements.txt.....................................................Failed
    - hook id: requirements-txt-fixer
    - description: sorts entries in requirements.txt
    - exit code: 1
    - files were modified by this hook

      Sorting file.txt

    ----- stderr -----
    ");

    assert_eq!(context.read("file.txt"), "a-project\nz-project\n");

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

    cmd_snapshot!(context, context.run().arg("trailing-whitespace"), @r#"
    success: true
    exit_code: 0
    ----- stdout -----
    trim trailing whitespace.................................................Passed

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

#[test]
fn fast_path_checks_filenames_from_entry_and_args() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r"
        repos:
          - repo: https://github.com/pre-commit/pre-commit-hooks
            rev: v5.0.0
            hooks:
              - id: check-json
                entry: check-json from-entry.json
                args: [from-args.json]
                files: ^selected\.json$
    "})
        .with_files([
            ("from-entry.json", "invalid"),
            ("from-args.json", "invalid"),
            ("selected.json", "{}"),
        ])
        .init_git();

    cmd_snapshot!(context, context.run(), @r"
    success: false
    exit_code: 1
    ----- stdout -----
    check json...............................................................Failed
    - hook id: check-json
    - description: checks json files for parseable syntax
    - exit code: 1

      from-entry.json: Failed to json decode (expected value at line 1 column 1)
      from-args.json: Failed to json decode (expected value at line 1 column 1)

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

#[test]
fn local() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: local
                name: local
                language: system
                entry: echo Hello, world!
                always_run: true
    "})
        .init_git();

    cmd_snapshot!(context, context.run(), @r#"
    success: true
    exit_code: 0
    ----- stdout -----
    local....................................................................Passed

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

/// Pass pre-commit environment variables to the hook.
#[test]
fn pass_env_vars() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: env-vars
                name: Pass environment
                language: system
                entry: python3 -c "import os, sys; print(os.getenv('PRE_COMMIT')); sys.exit(1)"
                always_run: true
    "#})
        .init_git();

    cmd_snapshot!(context, context.run(), @r"
    success: false
    exit_code: 1
    ----- stdout -----
    Pass environment.........................................................Failed
    - hook id: env-vars
    - exit code: 1

      1

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

/// Local python hook with no additional dependencies.
#[test]
fn local_python_hook() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: local-python-hook
                name: local-python-hook
                language: python
                entry: python3 -c 'import sys; print("Hello, world!"); sys.exit(1)'
    "#})
        .init_git();

    cmd_snapshot!(context, context.run(), @r"
    success: false
    exit_code: 1
    ----- stdout -----
    local-python-hook........................................................Failed
    - hook id: local-python-hook
    - exit code: 1

      Hello, world!

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

/// Invalid `entry`
#[test]
fn invalid_entry() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: entry
                name: entry
                language: python
                entry: '"'
    "#})
        .init_git();

    cmd_snapshot!(context, context.run(), @r#"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    error: Failed to run hook `entry`
      caused by: Invalid hook `entry`
      caused by: Failed to parse entry `"` as commands
    "#);
}

/// Test running hook whose `entry` is script with shebang on Windows.
#[test]
fn shebang_script() {
    let context = TestEnv::new().init_git();

    // Create a script with shebang.
    let script = indoc::indoc! {r"
        #!/usr/bin/env python
        import sys
        print('Hello, world!')
        sys.exit(0)
    "};
    let context = context
        .with_file("script.py", script)
        .with_config(indoc::indoc! {r"
      repos:
        - repo: local
          hooks:
            - id: shebang-script
              name: shebang-script
              language: python
              entry: script.py
              verbose: true
              pass_filenames: false
              always_run: true
    "});
    context.git().add(".");

    cmd_snapshot!(context, context.run(), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    shebang-script...........................................................Passed
    - hook id: shebang-script
    - duration: [TIME]

      Hello, world!

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

#[test]
fn dry_run() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: fail
                name: fail
                entry: fail
                language: fail
    "})
        .init_git();

    // Run with `--dry-run`
    cmd_snapshot!(context, context.run().arg("--dry-run").arg("-v"), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    fail....................................................................Dry Run
    - hook id: fail
    - duration: [TIME]

      `fail` would be run on 1 files:
      - .pre-commit-config.yaml

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

/// Test `language_version: system` works and disables downloading.
#[cfg(feature = "ci")]
#[test]
fn system_language_version() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: system-node
                name: system-node
                language: node
                language_version: system
                entry: node -v
                pass_filenames: false
              - id: system-go
                name: system-go
                language: golang
                language_version: system
                entry: go version
                pass_filenames: false
              - id: system-bun
                name: system-bun
                language: bun
                language_version: system
                entry: bun -e 'console.log(`Bun ${Bun.version}`)'
                pass_filenames: false
              - id: system-dotnet
                name: system-dotnet
                language: dotnet
                language_version: system
                entry: dotnet --version
                pass_filenames: false
       "})
        .init_git();

    // Binaries can't be found, `system` must fail.
    cmd_snapshot!(context,
        context.run()
        .arg("system-node")
        .env(EnvVars::PREK_INTERNAL__NODE_BINARY_NAME, "node-never-exist"), @r#"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    error: Failed to install hook `system-node`
      caused by: Failed to install node
      caused by: No suitable Node version found for toolchain policy: managed (downloads disabled)
    "#);

    cmd_snapshot!(context,
        context.run()
        .arg("system-go")
        .env(EnvVars::PREK_INTERNAL__GO_BINARY_NAME, "go-never-exist"), @r#"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    error: Failed to install hook `system-go`
      caused by: Failed to install go
      caused by: No suitable Go version found for toolchain policy: managed (downloads disabled)
    "#);

    cmd_snapshot!(context,
        context.run()
        .arg("system-bun")
        .env(EnvVars::PREK_INTERNAL__BUN_BINARY_NAME, "bun-never-exist"), @r#"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    error: Failed to install hook `system-bun`
      caused by: Failed to install bun
      caused by: No suitable Bun version found for toolchain policy: managed (downloads disabled)
    "#);

    cmd_snapshot!(context,
        context.run()
        .arg("system-dotnet")
        .env(EnvVars::PREK_INTERNAL__DOTNET_BINARY_NAME, "dotnet-never-exist"), @r#"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    error: Failed to install hook `system-dotnet`
      caused by: Failed to install dotnet SDK
      caused by: No suitable dotnet version found for toolchain policy: managed (downloads disabled)
    "#);
}

/// Tests that empty `entry` field.
#[test]
fn empty_entry() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: local
                name: local
                language: python
                entry: ''
                pass_filenames: false
       "})
        .init_git();

    // Go and Node can't be found, `system` must fail.
    cmd_snapshot!(context, context.run(), @r"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    error: Failed to run hook `local`
      caused by: Invalid hook `local`
      caused by: Failed to parse entry: entry is empty
    ");
}

/// Test that hooks are run with stdin closed.
#[test]
fn run_with_stdin_closed() {
    let context = TestEnv::new().with_config(indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: check-stdin
                name: check-stdin
                language: python
                entry: python -c 'import sys; sys.stdin.read(); print("STDIN closed"); sys.stdout.flush()'
                pass_filenames: false
                verbose: true
    "#}).init_git();

    cmd_snapshot!(context, context.run(), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    check-stdin..............................................................Passed
    - hook id: check-stdin
    - duration: [TIME]

      STDIN closed

    ----- stderr -----
    ");

    cmd_snapshot!(context, context.run().arg("--color").arg("always"), @r#"
    success: true
    exit_code: 0
    ----- stdout -----
    check-stdin..............................................................Passed
    - hook id: check-stdin
    - duration: [TIME]

      STDIN closed

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

#[test]
fn filename_batches_are_balanced() {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: batches
                name: batches
                entry: python3 -c 'import sys; print(len(sys.argv) - 1)'
                language: system
                files: '\.txt$'
                verbose: true
        "})
        .with_files((0..49).map(|i| (format!("f{i:02}.txt"), "")))
        .init_git();

    cmd_snapshot!(context, context.run().arg("--all-files")
        .env("PREK_CONCURRENT_BATCHES", "12")
        .env_remove("PREK_NO_CONCURRENCY"), @"
    success: true
    exit_code: 0
    ----- stdout -----
    batches..................................................................Passed
    - hook id: batches
    - duration: [TIME]

      17
      16
      16

    ----- stderr -----
    ");

    cmd_snapshot!(context, context.run().arg("--files")
        .args((0..31).map(|i| format!("f{i:02}.txt")))
        .env("PREK_CONCURRENT_BATCHES", "12")
        .env_remove("PREK_NO_CONCURRENCY"), @"
    success: true
    exit_code: 0
    ----- stdout -----
    batches..................................................................Passed
    - hook id: batches
    - duration: [TIME]

      31

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

/// `pass_filenames: n` limits each invocation to at most n files.
/// With n=1, each matched file gets its own invocation.
#[test]
fn pass_filenames_1_limits_batch_size() {
    let context = TestEnv::new().init_git();

    // Use a script that errors if it receives more than one filename argument.
    let context = context
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: one-at-a-time
                name: one at a time
                entry: python -c "import sys; args = sys.argv[1:]; sys.exit(0 if len(args) <= 1 else 1)"
                language: system
                pass_filenames: 1
                require_serial: true
                verbose: true
    "#})
        .with_files([("a.txt", "a"), ("b.txt", "b"), ("c.txt", "c")]);

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

    cmd_snapshot!(context, context.run().arg("--all-files"), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    one at a time............................................................Passed
    - hook id: one-at-a-time
    - duration: [TIME]

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

/// `pass_filenames: n` limits each invocation to at most n files.
/// With n=2 and more than 2 matching files, multiple batches are spawned.
#[test]
fn pass_filenames_2_limits_batch_size() {
    let context = TestEnv::new().init_git();

    // Use a script that errors if it receives more than two filename arguments.
    let context = context
        .with_config(indoc::indoc! {r#"
            repos:
              - repo: local
                hooks:
                  - id: two-at-a-time
                    name: two at a time
                    entry: python -c "import sys; args = sys.argv[1:]; sys.exit(0 if len(args) <= 2 else 1)"
                    language: system
                    pass_filenames: 2
                    require_serial: true
                    verbose: true
        "#})
        .with_files([
            ("a.txt", "a"),
            ("b.txt", "b"),
            ("c.txt", "c"),
            ("d.txt", "d"),
            ("e.txt", "e"),
        ]);

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

    cmd_snapshot!(context, context.run().arg("--all-files"), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    two at a time............................................................Passed
    - hook id: two-at-a-time
    - duration: [TIME]

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