prek 0.5.2

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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
use std::env::consts::EXE_EXTENSION;

#[cfg(all(feature = "ci", not(target_os = "windows")))]
use assert_fs::fixture::PathChild;

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

fn ruby_context() -> TestEnv {
    TestEnv::new()
        .with_filter(
            r"ruby (\d+\.\d+)\.\d+(?:p\d+)? \(\d{4}-\d{2}-\d{2} revision [0-9a-f]{0,10}\).*?\[.+\]",
            "ruby $1.X ([DATE] revision [HASH]) [FLAGS] [PLATFORM]",
        )
        .init_git()
}

/// Test basic Ruby hook with system Ruby
#[test]
fn system_ruby() {
    let context = ruby_context();
    context.write_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: ruby-version
                name: ruby-version
                language: ruby
                entry: ruby --version
                language_version: system
                pass_filenames: false
                always_run: true
              - id: ruby-version-unspecified
                name: ruby-version-unspecified
                language: ruby
                entry: ruby --version
                pass_filenames: false
                always_run: true
    "});
    context.git().add(".");

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

      ruby 3.4.X ([DATE] revision [HASH]) [FLAGS] [PLATFORM]
    ruby-version-unspecified.................................................Passed
    - hook id: ruby-version-unspecified
    - duration: [TIME]

      ruby 3.4.X ([DATE] revision [HASH]) [FLAGS] [PLATFORM]

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

/// Test that `language_version: default` works
#[test]
fn language_version_default() {
    let context = ruby_context();

    context.write_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: ruby-default
                name: ruby-default
                language: ruby
                entry: ruby --version
                language_version: default
                pass_filenames: false
                always_run: true
    "});
    context.git().add(".");

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

      ruby 3.4.X ([DATE] revision [HASH]) [FLAGS] [PLATFORM]

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

/// Test basic Ruby hook with a specified (and available) version of Ruby
#[test]
fn specific_ruby_available() {
    let context = ruby_context();
    context.write_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: ruby-version-prefixed
                name: ruby-version-prefixed
                language: ruby
                entry: ruby --version
                language_version: ruby3.4
                pass_filenames: false
                always_run: true
              - id: ruby-version
                name: ruby-version
                language: ruby
                entry: ruby --version
                language_version: '3.4'
                pass_filenames: false
                always_run: true
              - id: ruby-version-range-min
                name: ruby-version-range-min
                language: ruby
                entry: ruby --version
                language_version: '>=3.2'
                pass_filenames: false
                always_run: true
              - id: ruby-version-range-max
                name: ruby-version-range-max
                language: ruby
                entry: ruby --version
                language_version: '<4.0'
                pass_filenames: false
                always_run: true
              - id: ruby-version-constrained-range
                name: ruby-version-constrained-range
                language: ruby
                entry: ruby --version
                language_version: '>=3.2, <4'
                pass_filenames: false
                always_run: true
    "});
    context.git().add(".");

    cmd_snapshot!(context, context.run().arg("-v"), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    ruby-version-prefixed....................................................Passed
    - hook id: ruby-version-prefixed
    - duration: [TIME]

      ruby 3.4.X ([DATE] revision [HASH]) [FLAGS] [PLATFORM]
    ruby-version.............................................................Passed
    - hook id: ruby-version
    - duration: [TIME]

      ruby 3.4.X ([DATE] revision [HASH]) [FLAGS] [PLATFORM]
    ruby-version-range-min...................................................Passed
    - hook id: ruby-version-range-min
    - duration: [TIME]

      ruby 3.4.X ([DATE] revision [HASH]) [FLAGS] [PLATFORM]
    ruby-version-range-max...................................................Passed
    - hook id: ruby-version-range-max
    - duration: [TIME]

      ruby 3.4.X ([DATE] revision [HASH]) [FLAGS] [PLATFORM]
    ruby-version-constrained-range...........................................Passed
    - hook id: ruby-version-constrained-range
    - duration: [TIME]

      ruby 3.4.X ([DATE] revision [HASH]) [FLAGS] [PLATFORM]

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

/// Test basic Ruby hook with a specified (and unavailable) version of Ruby
#[test]
fn specific_ruby_unavailable() {
    let context = ruby_context();
    context.write_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: ruby-version
                name: ruby-version
                language: ruby
                entry: ruby --version
                language_version: 3.1.3
                pass_filenames: false
                always_run: true
    "});
    context.git().add(".");

    #[cfg(target_os = "windows")]
    cmd_snapshot!(context, context.run().arg("-v"), @r"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    error: Failed to install hook `ruby-version`
      caused by: Failed to install Ruby
      caused by: No suitable Ruby found for request: 3.1.3
    Automatic installation is not supported on this platform.
    Please install Ruby manually.
    ");

    #[cfg(not(target_os = "windows"))]
    cmd_snapshot!(context, context.run().arg("-v"), @r"
    success: false
    exit_code: 2
    ----- stdout -----

    ----- stderr -----
    error: Failed to install hook `ruby-version`
      caused by: Failed to install Ruby
      caused by: No suitable Ruby found for request: 3.1.3
    No rv-ruby release found matching: 3.1.3
    Please install Ruby manually.
    ");
}

/// Test Ruby hook with `additional_dependencies` and `require` statement
#[test]
fn additional_gem_dependencies() {
    // Use a gem that is not bundled with Ruby.
    let context = TestEnv::new()
        .with_file(
            "test_script.rb",
            indoc::indoc! {r"
            require 'rspec'
            puts RSpec::Version::STRING
        "},
        )
        .init_git();

    context.write_config(indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: test-gem-require
                name: test-gem-require
                language: ruby
                entry: ruby test_script.rb
                language_version: system
                additional_dependencies: ["rspec"]
                pass_filenames: false
                always_run: true
              - id: test-gem-require-versioned
                name: test-gem-require-versioned
                language: ruby
                entry: ruby test_script.rb
                language_version: system
                additional_dependencies: ["rspec:3.12.0"]
                pass_filenames: false
                always_run: true
              - id: test-gem-require-missing
                name: test-gem-require-missing
                language: ruby
                entry: ruby test_script.rb
                language_version: system
                pass_filenames: false
                always_run: true
    "#});
    context.git().add(".");

    let context = context.with_filters([
        // Normalize unpinned rspec version (only for test-gem-require, not test-gem-require-versioned)
        (
            r"(- hook id: test-gem-require\n- duration: .*?\n\n)  \d+\.\d+\.\d+",
            "$1  X.Y.Z",
        ),
        // Normalize Ruby require frames
        (
            r"([ \t]*(?:from )?)[^:\n]+/ruby/\d+\.\d+\.\d+/rubygems/core_ext/kernel_require\.rb:\d+:in `require'",
            "$1<internal:[RUBY_LIB]>:[X]:in 'Kernel#require'",
        ),
        (r":in `([^']+)'", ":in '$1'"),
        (r"<internal:[^>]+>:\d+:in", "<internal:[RUBY_LIB]>:[X]:in"),
    ]);

    cmd_snapshot!(context, context.run().arg("-v"), @r"
    success: false
    exit_code: 1
    ----- stdout -----
    test-gem-require.........................................................Passed
    - hook id: test-gem-require
    - duration: [TIME]

      X.Y.Z
    test-gem-require-versioned...............................................Passed
    - hook id: test-gem-require-versioned
    - duration: [TIME]

      3.12.0
    test-gem-require-missing.................................................Failed
    - hook id: test-gem-require-missing
    - duration: [TIME]
    - exit code: 1

      <internal:[RUBY_LIB]>:[X]:in 'Kernel#require': cannot load such file -- rspec (LoadError)
      	from <internal:[RUBY_LIB]>:[X]:in 'Kernel#require'
      	from test_script.rb:1:in '<main>'

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

/// Test Ruby hook with gemspec
#[test]
fn gemspec_workflow() -> anyhow::Result<()> {
    let context = TestEnv::new()
        .with_file(
            "test_gem.gemspec",
            indoc::indoc! {r#"
            Gem::Specification.new do |spec|
              spec.name          = "test_gem"
              spec.version       = "0.1.0"
              spec.authors       = ["Test"]
              spec.email         = ["test@example.com"]
              spec.summary       = "Test gem"
              spec.files         = ["lib/test_gem.rb"]
              spec.require_paths = ["lib"]
            end
        "#},
        )
        .with_file(
            "lib/test_gem.rb",
            indoc::indoc! {r#"
            module TestGem
              def self.hello
                "Hello from TestGem"
              end
            end
        "#},
        )
        .with_file(
            "test_script.rb",
            indoc::indoc! {r"
            require 'test_gem'
            puts TestGem.hello
        "},
        )
        .init_git();

    context.write_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: test-gemspec
                name: test-gemspec
                language: ruby
                entry: ruby -I lib test_script.rb
                language_version: system
                pass_filenames: false
                always_run: true
    "});
    context.git().add(".");

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

      Hello from TestGem

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

    let gem_bin_ruby = fs_err::read_dir(context.home_dir().join("hooks"))?
        .filter_map(Result::ok)
        .find(|e| e.file_name().to_string_lossy().starts_with("ruby-"))
        .map(|e| e.path().join("gems/bin/ruby").with_extension(EXE_EXTENSION))
        .expect("No ruby hook directory found");
    assert!(gem_bin_ruby.exists());
    #[cfg(unix)]
    assert!(
        fs_err::symlink_metadata(gem_bin_ruby)?
            .file_type()
            .is_symlink()
    );

    Ok(())
}

/// Test environment isolation between Ruby hooks
#[test]
fn environment_isolation() -> anyhow::Result<()> {
    let context = TestEnv::new()
        .with_config(indoc::indoc! {r#"
        repos:
          - repo: local
            hooks:
              - id: hook1
                name: hook1
                language: ruby
                entry: ruby -e "puts 'hook1=' + ENV['GEM_HOME']"
                language_version: system
                pass_filenames: false
                always_run: true
                verbose: true
              - id: hook2
                name: hook2
                language: ruby
                entry: ruby -e "puts 'hook2=' + ENV['GEM_HOME']"
                language_version: system
                pass_filenames: false
                always_run: true
                verbose: true
              - id: hook3
                name: hook3
                language: ruby
                entry: ruby -e "puts 'hook3=' + ENV['GEM_HOME']"
                language_version: system
                additional_dependencies: ["rspec"]
                pass_filenames: false
                always_run: true
                verbose: true
              - id: hook4
                name: hook4
                language: ruby
                entry: ruby -e "puts 'hook4=' + ENV['GEM_HOME']"
                language_version: system
                additional_dependencies: ["webrick"]
                pass_filenames: false
                always_run: true
                verbose: true
              - id: hook5
                name: hook5
                language: ruby
                entry: ruby -e "puts 'hook5=' + ENV['GEM_HOME']"
                language_version: system
                additional_dependencies: ["rspec"]
                pass_filenames: false
                always_run: true
                verbose: true
    "#})
        .init_git();

    let output = context.run().output()?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    assert!(
        output.status.success(),
        "Command failed\nEXIT CODE: {:?}\nSTDOUT:\n{}\nSTDERR:\n{}",
        output.status.code(),
        stdout,
        stderr
    );

    // Extract GEM_HOME paths from each hook's output
    let extract_gem_home = |hook_id: &str| -> String {
        let prefix = format!("{hook_id}=");
        stdout
            .lines()
            .find_map(|line| line.trim().strip_prefix(&prefix))
            .unwrap_or_else(|| panic!("Failed to extract GEM_HOME for {hook_id}"))
            .to_string()
    };

    let hook1_gem_home = extract_gem_home("hook1");
    let hook2_gem_home = extract_gem_home("hook2");
    let hook3_gem_home = extract_gem_home("hook3");
    let hook4_gem_home = extract_gem_home("hook4");
    let hook5_gem_home = extract_gem_home("hook5");

    // Verify isolation: hook1 == hook2 (same dependencies (none))
    assert_eq!(
        hook1_gem_home, hook2_gem_home,
        "hook1 and hook2 should share the same environment (both have no additional_dependencies)"
    );

    // Verify isolation: hook3 == hook5 (same dependencies (rspec))
    assert_eq!(
        hook3_gem_home, hook5_gem_home,
        "hook3 and hook5 should share the same environment (both have the same additional_dependencies)"
    );

    // Verify isolation: hook1 != hook3 (different dependencies)
    assert_ne!(
        hook1_gem_home, hook3_gem_home,
        "hook1 and hook3 should have different environments (hook3 has rspec)"
    );

    // Verify isolation: hook1 != hook4 (different dependencies)
    assert_ne!(
        hook1_gem_home, hook4_gem_home,
        "hook1 and hook4 should have different environments (hook4 has webrick)"
    );

    // Verify isolation: hook3 != hook4 (different dependencies)
    assert_ne!(
        hook3_gem_home, hook4_gem_home,
        "hook3 and hook4 should have different environments (different gems)"
    );

    // Run the command again to check that the environments are reused
    let output = context.run().output()?;

    let stdout = String::from_utf8_lossy(&output.stdout);
    let stderr = String::from_utf8_lossy(&output.stderr);

    assert!(
        output.status.success(),
        "Command failed\nEXIT CODE: {:?}\nSTDOUT:\n{}\nSTDERR:\n{}",
        output.status.code(),
        stdout,
        stderr
    );

    let hook1_gem_home_v2 = extract_gem_home("hook1");
    let hook2_gem_home_v2 = extract_gem_home("hook2");
    let hook3_gem_home_v2 = extract_gem_home("hook3");
    let hook4_gem_home_v2 = extract_gem_home("hook4");
    let hook5_gem_home_v2 = extract_gem_home("hook5");

    assert_eq!(
        hook1_gem_home, hook1_gem_home_v2,
        "hook1 should reuse the same environment on a second run"
    );

    assert_eq!(
        hook2_gem_home, hook2_gem_home_v2,
        "hook2 should reuse the same environment on a second run"
    );

    assert_eq!(
        hook3_gem_home, hook3_gem_home_v2,
        "hook3 should reuse the same environment on a second run"
    );

    assert_eq!(
        hook4_gem_home, hook4_gem_home_v2,
        "hook4 should reuse the same environment on a second run"
    );

    assert_eq!(
        hook5_gem_home, hook5_gem_home_v2,
        "hook5 should reuse the same environment on a second run"
    );

    Ok(())
}

/// Test local Ruby hook repository with gemspec build and install
#[test]
fn local_hook_with_gemspec() {
    let context = TestEnv::new().init_git();
    let hook_repo = context
        .create_hook_repo(
            "ruby-hook",
            indoc::indoc! {r"
            - id: my-hook
              name: My Hook
              entry: my-hook
              language: ruby
              pass_filenames: false
        "},
        )
        .with_file(
            "my_hook.gemspec",
            indoc::indoc! {r#"
            Gem::Specification.new do |spec|
              spec.name          = "my_hook"
              spec.version       = "0.1.0"
              spec.authors       = ["Test"]
              spec.email         = ["test@example.com"]
              spec.summary       = "Test hook gem"
              spec.files         = ["bin/my-hook"]
              spec.executables   = ["my-hook"]
              spec.bindir        = "bin"
            end
        "#},
        )
        .with_file(
            "bin/my-hook",
            indoc::indoc! {r#"
        #!/usr/bin/env ruby
        puts "Hook executed from gem!"
    "#},
        )
        .build();

    // Configure prek to use this local repo
    context.write_config(indoc::formatdoc! {r"
            repos:
              - repo: {}
                rev: v1.0.0
                hooks:
                  - id: my-hook
                    name: my-hook
                    entry: my-hook
                    language: ruby
                    pass_filenames: false
                    always_run: true
        ",
        hook_repo
    });
    context.git().add(".pre-commit-config.yaml");

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

      Hook executed from gem!

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

/// Test Ruby hook with native gem (C extension)
#[test]
fn native_gem_dependency() {
    // msgpack is a small native gem that compiles quickly.
    let context = TestEnv::new()
        .with_file(
            "check_msgpack.rb",
            indoc::indoc! {r#"
            #!/usr/bin/env ruby
            require 'msgpack'

            # Test that the native extension works
            data = { "hello" => "world", "number" => 42 }
            packed = MessagePack.pack(data)
            unpacked = MessagePack.unpack(packed)

            puts "MessagePack native extension working!"
            puts "Packed size: #{packed.bytesize} bytes"
        "#},
        )
        .init_git();

    context.write_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: test-native-gem
                name: test-native-gem
                language: ruby
                entry: ruby check_msgpack.rb
                additional_dependencies: ['msgpack']
                pass_filenames: false
                always_run: true
    "});
    context.git().add(".");

    cmd_snapshot!(context, context.run().arg("-v"), @r"
    success: true
    exit_code: 0
    ----- stdout -----
    test-native-gem..........................................................Passed
    - hook id: test-native-gem
    - duration: [TIME]

      MessagePack native extension working!
      Packed size: 21 bytes

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

/// Test Ruby hook that processes files
#[test]
fn process_files() {
    let context = TestEnv::new()
        .with_file(
            "check_ruby.rb",
            indoc::indoc! {r#"
            ARGV.sort.each do |file|
              unless file.end_with?('.rb')
                puts "Error: #{file} is not a Ruby file"
                exit 1
              end
              puts "OK: #{file}"
            end
        "#},
        )
        .init_git();

    let context = context
        .with_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: check-ruby-files
                name: check-ruby-files
                language: ruby
                entry: ruby check_ruby.rb
                language_version: system
                files: \.rb$
                verbose: true
    "})
        .with_file("test.rb", "puts 'hello'")
        .with_file("test.txt", "hello");

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

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

      OK: check_ruby.rb
      OK: test.rb

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

/// Test that Ruby is auto-downloaded from rv-ruby when a specific version
/// is requested that isn't available on the system.
/// Windows doesn't support auto-download, so this test is only for non-Windows platforms.
/// The Windows-specific message is tested in `specific_ruby_unavailable`.
#[cfg(feature = "ci")]
#[test]
#[cfg(not(target_os = "windows"))]
fn auto_download() -> anyhow::Result<()> {
    use assert_fs::assert::PathAssert;

    let context = ruby_context();
    context.write_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: ruby-downloaded
                name: ruby-downloaded
                language: ruby
                entry: ruby --version
                language_version: '3.2.9'
                pass_filenames: false
                always_run: true
              - id: ruby-system
                name: ruby-system
                language: ruby
                entry: ruby --version
                language_version: '3.4'
                pass_filenames: false
                always_run: true
    "});
    context.git().add(".");

    let ruby_dir = context.home_dir().child("tools").child("ruby");
    ruby_dir.assert(predicates::path::missing());

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

      ruby 3.2.X ([DATE] revision [HASH]) [FLAGS] [PLATFORM]
    ruby-system..............................................................Passed
    - hook id: ruby-system
    - duration: [TIME]

      ruby 3.4.X ([DATE] revision [HASH]) [FLAGS] [PLATFORM]

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

    // Verify that only Ruby 3.1 was downloaded (3.4 should use system Ruby)
    let installed_versions = ruby_dir
        .read_dir()?
        .flatten()
        .filter_map(|d| {
            let filename = d.file_name().to_string_lossy().into_owned();
            if filename.starts_with('.') {
                None
            } else {
                Some(filename)
            }
        })
        .collect::<Vec<_>>();

    assert_eq!(
        installed_versions.len(),
        1,
        "Expected only one Ruby version to be downloaded, but found: {installed_versions:?}"
    );
    assert!(
        installed_versions.iter().any(|v| v.starts_with("3.2.9")),
        "Expected Ruby 3.2.9 to be downloaded, but found: {installed_versions:?}"
    );

    // Record the mtime of the downloaded Ruby directory so we can verify
    // step 2 doesn't re-download it.
    let ruby_version_dir = ruby_dir
        .read_dir()?
        .flatten()
        .find(|d| d.file_name().to_string_lossy().starts_with("3.2.9"))
        .expect("Expected a 3.2.9 directory");
    let mtime_before = ruby_version_dir.metadata()?.modified()?;

    // Step 2: Re-run with a looser version match that should reuse the
    // already-downloaded 3.2.9 without hitting the network again.
    context.write_config(indoc::indoc! {r"
        repos:
          - repo: local
            hooks:
              - id: ruby-reused
                name: ruby-reused
                language: ruby
                entry: ruby --version
                language_version: '3.2.9'
                pass_filenames: false
                always_run: true
    "});
    context.git().add(".");

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

      ruby 3.2.X ([DATE] revision [HASH]) [FLAGS] [PLATFORM]

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

    // Verify the directory wasn't re-downloaded: mtime should be unchanged
    let mtime_after = ruby_version_dir.metadata()?.modified()?;
    assert_eq!(
        mtime_before, mtime_after,
        "Ruby directory was modified during reuse, suggests it was re-downloaded"
    );

    Ok(())
}