prek 0.5.5

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
use std::path::{Path, PathBuf};

use anyhow::Result;
use clap::Parser;
use serde::de::IgnoredAny;

use crate::hook::Hook;
use crate::hooks::HookOutput;
use crate::hooks::pre_commit_hooks::{parse_hook_args, run_blocking_file_checks};

#[derive(Parser)]
#[command(disable_help_subcommand = true)]
#[command(disable_version_flag = true)]
#[command(disable_help_flag = true)]
pub(crate) struct Args {
    /// Allow multiple YAML documents.
    #[arg(long, short = 'm', visible_alias = "multi")]
    allow_multiple_documents: bool,
    /// Reject unrecognized YAML tags.
    #[arg(long, conflicts_with = "unsafe")]
    disallow_unknown_tags: bool,
    /// Parse YAML syntax without loading it. Implies `--allow-multiple-documents`.
    #[arg(long)]
    r#unsafe: bool,
    #[arg(value_name = "FILENAMES")]
    filenames: Vec<PathBuf>,
}

#[derive(Clone, Copy)]
enum CheckMode {
    Load {
        multiple: bool,
        disallow_unknown_tags: bool,
    },
    SyntaxOnly,
}

/// Runs the `check-yaml` hook.
pub(crate) async fn run(hook: &Hook, filenames: &[&Path]) -> Result<HookOutput> {
    let args: Args = parse_hook_args(hook)?;
    let mode = if args.r#unsafe {
        CheckMode::SyntaxOnly
    } else {
        CheckMode::Load {
            multiple: args.allow_multiple_documents,
            disallow_unknown_tags: args.disallow_unknown_tags,
        }
    };

    run_blocking_file_checks(
        hook.project().relative_path(),
        &args.filenames,
        filenames,
        move |file_path, display_path| check_file(file_path, display_path, mode),
    )
    .await
}

fn check_file(file_path: &Path, display_path: &Path, mode: CheckMode) -> Result<HookOutput> {
    let content = fs_err::read(file_path)?;
    if content.is_empty() {
        return Ok(HookOutput::unchanged(0, Vec::new()));
    }

    let output = match mode {
        CheckMode::Load {
            multiple,
            disallow_unknown_tags,
        } => check_loaded(display_path, &content, multiple, disallow_unknown_tags),
        CheckMode::SyntaxOnly => check_syntax(display_path, &content),
    };
    Ok(output)
}

fn check_loaded(
    display_path: &Path,
    content: &[u8],
    allow_multi_docs: bool,
    disallow_unknown_tags: bool,
) -> HookOutput {
    let options = serde_saphyr::options! {
        budget: serde_saphyr::budget! {
            // `check-yaml` is a syntax/structure validator, not a service parsing
            // untrusted YAML at runtime. Keep the absolute caps, but allow
            // high-reuse anchors that are common in compose-style files. See #1838.
            enforce_alias_anchor_ratio: false,
        },
        // Comments do not affect syntax or structure validation. See #2501.
        emit_comments: false,
        // Do not require `!!binary` scalars to decode as UTF-8. See #1102.
        ignore_binary_tag_for_string: true,
        // A YAML tag identifies a node's type or application-specific semantics.
        // `%TAG` directives map tag handles to prefixes. The predefined `!!`
        // handle expands to `tag:yaml.org,2002:`, while `!` is the local tag handle.
        // Unknown tags are application-defined, and deserializing into `IgnoredAny` does not
        // construct their values. Reject them only when explicitly requested. See #2674.
        reject_unsupported_tags: disallow_unknown_tags,
        // The scalar values are discarded, so only validate whether they are
        // legal YAML, not whether an untyped data model can represent them. See #2544.
        reject_non_finite_typeless_float: false,
    };
    let result = match simdutf8::compat::from_utf8(content) {
        Ok(content) if allow_multi_docs => {
            serde_saphyr::from_multiple_with_options::<IgnoredAny>(content, options).map(|_| ())
        }
        Ok(content) => {
            serde_saphyr::from_str_with_options::<IgnoredAny>(content, options).map(|_| ())
        }
        Err(_) => Err(serde_saphyr::Error::InvalidUtf8Input),
    };
    match result {
        Ok(()) => HookOutput::unchanged(0, Vec::new()),
        Err(e) => {
            let err = e.render_with_options(serde_saphyr::render_options! {
                snippets: serde_saphyr::SnippetMode::Off,
                formatter: &serde_saphyr::UserMessageFormatter,
            });
            let error_message = format!(
                "{}: Failed to yaml decode ({err})\n",
                display_path.display()
            );
            HookOutput::unchanged(1, error_message.into_bytes())
        }
    }
}

fn check_syntax(display_path: &Path, content: &[u8]) -> HookOutput {
    let content = match simdutf8::compat::from_utf8(content) {
        Ok(content) => content,
        Err(error) => {
            let error_message = format!(
                "{}: Failed to decode UTF-8 ({error})\n",
                display_path.display()
            );
            return HookOutput::unchanged(1, error_message.into_bytes());
        }
    };

    let options = granit_parser::options! {
        // Comments do not affect syntax validation. See #2501.
        emit_comments: false,
    };

    // TODO: `granit-parser` resolves aliases while producing parser events, so this is stricter
    // than upstream's syntax-only mode for aliases that reference an undefined anchor.
    for event in granit_parser::Parser::with_options(granit_parser::StrInput::new(content), options)
    {
        if let Err(error) = event {
            let error_message = format!(
                "{}: Failed to yaml parse ({error})\n",
                display_path.display()
            );
            return HookOutput::unchanged(1, error_message.into_bytes());
        }
    }

    HookOutput::unchanged(0, Vec::new())
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::Parser;
    use std::fmt::Write;
    use std::path::PathBuf;
    use tempfile::tempdir;

    const LOAD_SINGLE_DOCUMENT: CheckMode = CheckMode::Load {
        multiple: false,
        disallow_unknown_tags: false,
    };
    const LOAD_MULTIPLE_DOCUMENTS: CheckMode = CheckMode::Load {
        multiple: true,
        disallow_unknown_tags: false,
    };

    async fn create_test_file(
        dir: &tempfile::TempDir,
        name: &str,
        content: &[u8],
    ) -> Result<PathBuf> {
        let file_path = dir.path().join(name);
        fs_err::tokio::write(&file_path, content).await?;
        Ok(file_path)
    }

    #[test]
    fn test_unsafe_argument() -> Result<()> {
        let args = Args::try_parse_from(["check-yaml", "--unsafe", "config.yaml"])?;
        assert!(args.r#unsafe);
        assert_eq!(args.filenames, [PathBuf::from("config.yaml")]);
        Ok(())
    }

    #[tokio::test]
    async fn test_valid_yaml() -> Result<()> {
        let dir = tempdir()?;
        let content = br"key1: value1
key2: value2
";
        let file_path = create_test_file(&dir, "valid.yaml", content).await?;
        let result = check_file(&file_path, &file_path, LOAD_SINGLE_DOCUMENT)?;
        assert_eq!(result.exit_status, 0);
        assert_eq!(result.output, b"");
        Ok(())
    }

    #[tokio::test]
    async fn test_yaml_with_non_finite_floats() -> Result<()> {
        let dir = tempdir()?;
        let content = br"nan: .nan
positive_infinity: .inf
negative_infinity: -.inf
";
        let file_path = create_test_file(&dir, "non-finite.yaml", content).await?;
        let result = check_file(&file_path, &file_path, LOAD_SINGLE_DOCUMENT)?;
        assert_eq!(
            result.exit_status,
            0,
            "{}",
            String::from_utf8_lossy(&result.output)
        );
        assert_eq!(result.output, b"");
        Ok(())
    }

    #[test]
    fn test_under_indented_flow_sequence() {
        let filename = Path::new("targets.yaml");
        let content = b"- targets: [\n  \"192.168.1.1:9100\",\n  \"192.168.1.2:9100\",\n]\n";

        for result in [
            check_loaded(filename, content, false, false),
            check_syntax(filename, content),
        ] {
            assert_eq!((result.exit_status, result.output), (0, Vec::new()));
        }
    }

    #[tokio::test]
    async fn test_invalid_yaml() -> Result<()> {
        let dir = tempdir()?;
        let content = br"key1: value1
key2: value2: another_value
";
        let file_path = create_test_file(&dir, "invalid.yaml", content).await?;
        let result = check_file(&file_path, &file_path, LOAD_SINGLE_DOCUMENT)?;
        assert_eq!(result.exit_status, 1);
        assert_ne!(result.output, b"");
        Ok(())
    }

    #[tokio::test]
    async fn test_duplicate_keys() -> Result<()> {
        let dir = tempdir()?;
        let content = br"key1: value1
key1: value2
";
        let file_path = create_test_file(&dir, "duplicate.yaml", content).await?;
        let result = check_file(&file_path, &file_path, LOAD_SINGLE_DOCUMENT)?;
        assert_eq!(result.exit_status, 1);
        assert_ne!(result.output, b"");
        Ok(())
    }

    #[tokio::test]
    async fn test_empty_yaml() -> Result<()> {
        let dir = tempdir()?;
        let content = b"";
        let file_path = create_test_file(&dir, "empty.yaml", content).await?;
        let result = check_file(&file_path, &file_path, LOAD_SINGLE_DOCUMENT)?;
        assert_eq!(result.exit_status, 0);
        assert_eq!(result.output, b"");
        Ok(())
    }

    #[tokio::test]
    async fn test_multiple_documents() -> Result<()> {
        let dir = tempdir()?;
        let content = b"\
---
key1: value1
---
key2: value2
";
        let file_path = create_test_file(&dir, "multi.yaml", content).await?;

        let result = check_file(&file_path, &file_path, LOAD_SINGLE_DOCUMENT)?;
        assert_eq!(result.exit_status, 1);
        assert_ne!(result.output, b"");

        let result = check_file(&file_path, &file_path, LOAD_MULTIPLE_DOCUMENTS)?;
        assert_eq!(result.exit_status, 0);
        assert_eq!(result.output, b"");
        Ok(())
    }

    #[tokio::test]
    async fn test_unsafe_allows_multiple_documents() -> Result<()> {
        let dir = tempdir()?;
        let content = b"---\nkey1: value1\n---\nkey2: value2\n";
        let file_path = create_test_file(&dir, "multi.yaml", content).await?;

        let result = check_file(&file_path, &file_path, CheckMode::SyntaxOnly)?;
        assert_eq!(
            result.exit_status,
            0,
            "{}",
            String::from_utf8_lossy(&result.output)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_unsafe_checks_later_documents() -> Result<()> {
        let dir = tempdir()?;
        let content = b"---\nkey: value\n---\n[";
        let file_path = create_test_file(&dir, "invalid-multi.yaml", content).await?;

        let result = check_file(&file_path, &file_path, CheckMode::SyntaxOnly)?;
        assert_eq!(result.exit_status, 1);
        assert_ne!(result.output, b"");
        Ok(())
    }

    #[tokio::test]
    async fn test_unsafe_allows_values_rejected_while_loading() -> Result<()> {
        let dir = tempdir()?;
        let content = b"duplicate: first\nduplicate: second\ntarget:\n  <<: not-a-map\n";
        let file_path = create_test_file(&dir, "unsafe.yaml", content).await?;

        let result = check_file(&file_path, &file_path, CheckMode::SyntaxOnly)?;
        assert_eq!(
            result.exit_status,
            0,
            "{}",
            String::from_utf8_lossy(&result.output)
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_unsafe_rejects_invalid_syntax() -> Result<()> {
        let dir = tempdir()?;
        let file_path = create_test_file(&dir, "invalid.yaml", b"[").await?;

        let result = check_file(&file_path, &file_path, CheckMode::SyntaxOnly)?;
        assert_eq!(result.exit_status, 1);
        assert_ne!(result.output, b"");
        Ok(())
    }

    #[tokio::test]
    async fn test_unsafe_rejects_invalid_utf8() -> Result<()> {
        let dir = tempdir()?;
        let file_path = create_test_file(&dir, "invalid.yaml", b"key: \xff").await?;

        let result = check_file(&file_path, &file_path, CheckMode::SyntaxOnly)?;
        assert_eq!(result.exit_status, 1);
        assert!(String::from_utf8_lossy(&result.output).contains("Failed to decode UTF-8"));
        Ok(())
    }

    #[test]
    fn test_unknown_yaml_tag_is_allowed_by_default() {
        let filename = Path::new("tagged.yaml");
        let content = b"foo: !reference [.bar, script]\n";

        let result = check_loaded(filename, content, false, false);
        assert_eq!((result.exit_status, result.output), (0, Vec::new()));
    }

    #[test]
    fn test_disallow_unknown_tags_rejects_unknown_yaml_tag() {
        let filename = Path::new("tagged.yaml");
        let content = b"foo: !reference [.bar, script]\n";

        let result = check_loaded(filename, content, false, true);
        assert_eq!(result.exit_status, 1);
        insta::assert_snapshot!(String::from_utf8_lossy(&result.output), @"tagged.yaml: Failed to yaml decode (unsupported tag `!reference` at line 1, column 17)");
    }

    #[test]
    fn test_unsafe_allows_unknown_yaml_tag() {
        let filename = Path::new("tagged.yaml");
        let content = b"foo: !reference [.bar, script]\n";

        let result = check_syntax(filename, content);
        assert_eq!((result.exit_status, result.output), (0, Vec::new()));
    }

    #[tokio::test]
    async fn test_yaml_with_binary_scalar() -> Result<()> {
        let dir = tempdir()?;
        let content = b"\
response:
  body:
    string: !!binary |
      H4sIAAAAAAAAA4xTPW/bMBDd9SsON9uFJaeJ4y0oujRIEXQpisiQaOokM6VIgjzFSQ3/94KSYzmt
      A2TRwPfBd/eoXQKAqsIloNwIlq3T0y/rF6JfbXYT2m3rvan+NLfXt/zj2/f5NsVJVNj1I0l+VX2S
      tnWaWFkzwNKTYIqu6dXlPL28mmeLHmhtRTrKGsfTCzvNZtnFNE2n2ewg3FglKeASHhIAgF3/jRFN
      Rc+4hNnk9aSlEERDuDySANBbHU9QhKACC8M4GUFpDZPpU5dl+Risyc0uNwA5smJNOS4hxxu4Jx8c
      SVZPBNbA12enhRFxugC2hjurSXZaeLj3VCkZAbiLg4UcJ4Of6HhjfYiODzn+JK3FVjATEIPQOa4O
      vMqqyDGd1rnZ56Ysy9PEnuouCH1gnADCGMtDpHjF6oDsj9vRtnHersM/UqyVUWFTeBLBmriJwNZh
      j+4TgFXfQvdmsei8bR0XbH9Tf91iPtjhWPsIzq8PIFsWejxPs2xyxq6oiIXS4aRGlEJuqBqlY+ei
      q5Q9AZKTof9Pc857GFyZ5iP2IyAlOaaqcMfGz9E8xb/iPdpxyX1gDOSflKSCFflYREW16PTwYDG8
      BKa2qJVpyDuvhldbu0LOFtnicypnC0z2yV8AAAD//wMALvIkjL4DAAA=
";
        let file_path = create_test_file(&dir, "binary.yaml", content).await?;
        let result = check_file(&file_path, &file_path, LOAD_SINGLE_DOCUMENT)?;
        assert_eq!(result.exit_status, 0);
        assert_eq!(result.output, b"");
        Ok(())
    }

    #[tokio::test]
    async fn test_yaml_with_many_aliases_and_few_anchors() -> Result<()> {
        let dir = tempdir()?;
        let mut content = indoc::formatdoc! {"
        defaults: &defaults
          image: alpine
        services:
        "};
        for index in 0..158 {
            let _ = write!(content, "  svc{index}:\n    <<: *defaults\n");
        }

        let file_path = create_test_file(&dir, "many-aliases.yaml", content.as_bytes()).await?;
        let result = check_file(&file_path, &file_path, LOAD_SINGLE_DOCUMENT)?;
        assert_eq!(
            result.exit_status,
            0,
            "{}",
            String::from_utf8_lossy(&result.output)
        );
        assert_eq!(result.output, b"");
        Ok(())
    }

    #[tokio::test]
    async fn test_yaml_with_many_consecutive_comments() -> Result<()> {
        let dir = tempdir()?;
        let mut content = "items:\n".to_string();
        for index in 0..100 {
            let _ = writeln!(content, "  # comment {index}");
        }
        content.push_str("  - value\n");

        let file_path = create_test_file(&dir, "many-comments.yaml", content.as_bytes()).await?;
        for mode in [LOAD_SINGLE_DOCUMENT, CheckMode::SyntaxOnly] {
            let result = check_file(&file_path, &file_path, mode)?;
            assert_eq!(
                result.exit_status,
                0,
                "{}",
                String::from_utf8_lossy(&result.output)
            );
            assert_eq!(result.output, b"");
        }
        Ok(())
    }
}