alint-rules 0.9.22

Internal: built-in rule implementations for alint. Not a stable public API.
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
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
use std::io::Write;
use std::path::PathBuf;

use alint_core::{ContentSourceSpec, Error, FixContext, FixOutcome, Fixer, Result, Violation};

/// UTF-8 byte-order mark. Preserved across prepend operations so
/// editors that rely on it don't break.
const UTF8_BOM: &[u8] = b"\xEF\xBB\xBF";

/// Creates a file with pre-declared content. Target path is set at
/// rule-build time (either explicit `fix.file_create.path` or the
/// rule's first literal `paths:` entry). Content is either inline
/// or read at apply time from a path-relative-to-root.
#[derive(Debug)]
pub struct FileCreateFixer {
    path: PathBuf,
    source: ContentSourceSpec,
    create_parents: bool,
}

impl FileCreateFixer {
    pub fn new(path: PathBuf, source: ContentSourceSpec, create_parents: bool) -> Self {
        Self {
            path,
            source,
            create_parents,
        }
    }
}

impl Fixer for FileCreateFixer {
    fn describe(&self) -> String {
        match &self.source {
            ContentSourceSpec::Inline(s) => format!(
                "create {} ({} byte{})",
                self.path.display(),
                s.len(),
                if s.len() == 1 { "" } else { "s" }
            ),
            ContentSourceSpec::File(rel) => format!(
                "create {} (content from {})",
                self.path.display(),
                rel.display()
            ),
        }
    }

    fn apply(&self, _violation: &Violation, ctx: &FixContext<'_>) -> Result<FixOutcome> {
        let abs = ctx.root.join(&self.path);
        if abs.exists() {
            return Ok(FixOutcome::Skipped(format!(
                "{} already exists",
                self.path.display()
            )));
        }
        let content = match resolve_source_bytes(&self.source, ctx.root) {
            Ok(bytes) => bytes,
            Err(skip_msg) => return Ok(FixOutcome::Skipped(skip_msg)),
        };
        if ctx.dry_run {
            return Ok(FixOutcome::Applied(format!(
                "would create {}",
                self.path.display()
            )));
        }
        if self.create_parents
            && let Some(parent) = abs.parent()
        {
            std::fs::create_dir_all(parent).map_err(|source| Error::Io {
                path: parent.to_path_buf(),
                source,
            })?;
        }
        std::fs::write(&abs, &content).map_err(|source| Error::Io {
            path: abs.clone(),
            source,
        })?;
        Ok(FixOutcome::Applied(format!(
            "created {}",
            self.path.display()
        )))
    }
}

/// Read a `ContentSourceSpec` to bytes. Returns the raw payload
/// for inline content; for file-sourced content, reads the file
/// at apply time, resolving its path relative to `ctx_root`. A
/// missing or unreadable source produces a `Skipped`-friendly
/// `Err(String)` so the caller can degrade gracefully rather
/// than abort the whole fix run.
fn resolve_source_bytes(
    source: &ContentSourceSpec,
    ctx_root: &std::path::Path,
) -> std::result::Result<Vec<u8>, String> {
    match source {
        ContentSourceSpec::Inline(s) => Ok(s.as_bytes().to_vec()),
        ContentSourceSpec::File(rel) => {
            let abs = ctx_root.join(rel);
            std::fs::read(&abs)
                .map_err(|e| format!("content_from `{}` could not be read: {e}", rel.display()))
        }
    }
}

/// Prepends `source` content to the start of each violating
/// file. Paired with `file_header` to inject a required header
/// comment / boilerplate.
///
/// If the file starts with a UTF-8 BOM, the prepended bytes go
/// *after* the BOM so editors that rely on it don't break.
#[derive(Debug)]
pub struct FilePrependFixer {
    source: ContentSourceSpec,
}

impl FilePrependFixer {
    pub fn new(source: ContentSourceSpec) -> Self {
        Self { source }
    }
}

impl Fixer for FilePrependFixer {
    fn describe(&self) -> String {
        match &self.source {
            ContentSourceSpec::Inline(s) => format!(
                "prepend {} byte{} to each violating file",
                s.len(),
                if s.len() == 1 { "" } else { "s" }
            ),
            ContentSourceSpec::File(rel) => {
                format!(
                    "prepend content from {} to each violating file",
                    rel.display()
                )
            }
        }
    }

    fn apply(&self, violation: &Violation, ctx: &FixContext<'_>) -> Result<FixOutcome> {
        let Some(path) = &violation.path else {
            return Ok(FixOutcome::Skipped(
                "violation did not carry a path".to_string(),
            ));
        };
        let abs = ctx.root.join(path);
        let prepend = match resolve_source_bytes(&self.source, ctx.root) {
            Ok(b) => b,
            Err(skip_msg) => return Ok(FixOutcome::Skipped(skip_msg)),
        };
        if ctx.dry_run {
            return Ok(FixOutcome::Applied(format!(
                "would prepend {} byte(s) to {}",
                prepend.len(),
                path.display()
            )));
        }
        let existing = match alint_core::read_for_fix(&abs, path, ctx)? {
            alint_core::ReadForFix::Bytes(b) => b,
            alint_core::ReadForFix::Skipped(outcome) => return Ok(outcome),
        };
        let mut out = Vec::with_capacity(existing.len() + prepend.len());
        if existing.starts_with(UTF8_BOM) {
            out.extend_from_slice(UTF8_BOM);
            out.extend_from_slice(&prepend);
            out.extend_from_slice(&existing[UTF8_BOM.len()..]);
        } else {
            out.extend_from_slice(&prepend);
            out.extend_from_slice(&existing);
        }
        std::fs::write(&abs, &out).map_err(|source| Error::Io {
            path: abs.clone(),
            source,
        })?;
        Ok(FixOutcome::Applied(format!("prepended {}", path.display())))
    }
}

/// Appends `source` content to the end of each violating file.
/// Paired with `file_content_matches` / `file_footer` when the
/// required content is satisfied by the appended bytes.
#[derive(Debug)]
pub struct FileAppendFixer {
    source: ContentSourceSpec,
}

impl FileAppendFixer {
    pub fn new(source: ContentSourceSpec) -> Self {
        Self { source }
    }
}

impl Fixer for FileAppendFixer {
    fn describe(&self) -> String {
        match &self.source {
            ContentSourceSpec::Inline(s) => format!(
                "append {} byte{} to each violating file",
                s.len(),
                if s.len() == 1 { "" } else { "s" }
            ),
            ContentSourceSpec::File(rel) => {
                format!(
                    "append content from {} to each violating file",
                    rel.display()
                )
            }
        }
    }

    fn apply(&self, violation: &Violation, ctx: &FixContext<'_>) -> Result<FixOutcome> {
        let Some(path) = &violation.path else {
            return Ok(FixOutcome::Skipped(
                "violation did not carry a path".to_string(),
            ));
        };
        let abs = ctx.root.join(path);
        let payload = match resolve_source_bytes(&self.source, ctx.root) {
            Ok(b) => b,
            Err(skip_msg) => return Ok(FixOutcome::Skipped(skip_msg)),
        };
        if ctx.dry_run {
            return Ok(FixOutcome::Applied(format!(
                "would append {} byte(s) to {}",
                payload.len(),
                path.display()
            )));
        }
        if let Some(skip) = alint_core::check_fix_size(&abs, path, ctx)? {
            return Ok(skip);
        }
        let mut f = std::fs::OpenOptions::new()
            .append(true)
            .open(&abs)
            .map_err(|source| Error::Io {
                path: abs.clone(),
                source,
            })?;
        f.write_all(&payload).map_err(|source| Error::Io {
            path: abs.clone(),
            source,
        })?;
        Ok(FixOutcome::Applied(format!(
            "appended to {}",
            path.display()
        )))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn make_ctx(tmp: &TempDir, dry_run: bool) -> FixContext<'_> {
        FixContext {
            root: tmp.path(),
            dry_run,
            fix_size_limit: None,
        }
    }

    #[test]
    fn file_create_writes_content_when_missing() {
        let tmp = TempDir::new().unwrap();
        let fixer = FileCreateFixer::new(PathBuf::from("LICENSE"), "Apache-2.0\n".into(), true);
        let outcome = fixer
            .apply(&Violation::new("missing LICENSE"), &make_ctx(&tmp, false))
            .unwrap();
        assert!(matches!(outcome, FixOutcome::Applied(_)));
        let written = std::fs::read_to_string(tmp.path().join("LICENSE")).unwrap();
        assert_eq!(written, "Apache-2.0\n");
    }

    #[test]
    fn file_create_reads_content_from_relative_path() {
        // `content_from` relative to ctx.root: stage a template
        // file in the tempdir, point the fixer at it via a
        // relative path, and verify the apply step reads from
        // disk at apply time.
        let tmp = TempDir::new().unwrap();
        let template_dir = tmp.path().join(".alint/templates");
        std::fs::create_dir_all(&template_dir).unwrap();
        std::fs::write(
            template_dir.join("LICENSE-MIT.txt"),
            "MIT License\n\nCopyright (c) 2026 demo\n",
        )
        .unwrap();
        let fixer = FileCreateFixer::new(
            PathBuf::from("LICENSE"),
            ContentSourceSpec::File(PathBuf::from(".alint/templates/LICENSE-MIT.txt")),
            true,
        );
        let outcome = fixer
            .apply(&Violation::new("missing LICENSE"), &make_ctx(&tmp, false))
            .unwrap();
        assert!(matches!(outcome, FixOutcome::Applied(_)));
        let written = std::fs::read_to_string(tmp.path().join("LICENSE")).unwrap();
        assert!(written.starts_with("MIT License"));
        assert!(written.contains("Copyright (c) 2026"));
    }

    #[test]
    fn file_create_skips_when_content_from_missing() {
        // Missing source file produces a `Skipped` outcome
        // rather than aborting the whole fix run — same posture
        // as the rest of the fixer module.
        let tmp = TempDir::new().unwrap();
        let fixer = FileCreateFixer::new(
            PathBuf::from("LICENSE"),
            ContentSourceSpec::File(PathBuf::from("does/not/exist.txt")),
            true,
        );
        let outcome = fixer
            .apply(&Violation::new("missing"), &make_ctx(&tmp, false))
            .unwrap();
        let FixOutcome::Skipped(msg) = &outcome else {
            panic!("expected Skipped, got {outcome:?}")
        };
        assert!(msg.contains("could not be read"));
        // The target file should NOT have been created since
        // we skipped before the write.
        assert!(!tmp.path().join("LICENSE").exists());
    }

    #[test]
    fn file_prepend_with_content_from_reads_at_apply() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("hdr.txt"),
            "// SPDX-License-Identifier: MIT\n",
        )
        .unwrap();
        std::fs::write(tmp.path().join("a.rs"), "fn main() {}\n").unwrap();
        let fixer = FilePrependFixer::new(ContentSourceSpec::File(PathBuf::from("hdr.txt")));
        let outcome = fixer
            .apply(
                &Violation::new("missing header").with_path(PathBuf::from("a.rs")),
                &make_ctx(&tmp, false),
            )
            .unwrap();
        assert!(matches!(outcome, FixOutcome::Applied(_)));
        let updated = std::fs::read_to_string(tmp.path().join("a.rs")).unwrap();
        assert!(updated.starts_with("// SPDX-License-Identifier: MIT\n"));
        assert!(updated.contains("fn main() {}"));
    }

    #[test]
    fn file_create_creates_intermediate_directories() {
        let tmp = TempDir::new().unwrap();
        let fixer = FileCreateFixer::new(PathBuf::from("a/b/c/config.yaml"), "k: v\n".into(), true);
        fixer
            .apply(&Violation::new("missing"), &make_ctx(&tmp, false))
            .unwrap();
        assert!(tmp.path().join("a/b/c/config.yaml").exists());
    }

    #[test]
    fn file_create_skips_when_target_exists() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("README.md"), "existing\n").unwrap();
        let fixer = FileCreateFixer::new(PathBuf::from("README.md"), "NEW\n".into(), true);
        let outcome = fixer
            .apply(&Violation::new("x"), &make_ctx(&tmp, false))
            .unwrap();
        match outcome {
            FixOutcome::Skipped(reason) => assert!(reason.contains("already exists")),
            FixOutcome::Applied(_) => panic!("expected Skipped"),
        }
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("README.md")).unwrap(),
            "existing\n",
            "pre-existing content must not be overwritten"
        );
    }

    #[test]
    fn file_create_dry_run_does_not_touch_disk() {
        let tmp = TempDir::new().unwrap();
        let fixer = FileCreateFixer::new(PathBuf::from("x.txt"), "body".into(), true);
        let outcome = fixer
            .apply(&Violation::new("x"), &make_ctx(&tmp, true))
            .unwrap();
        match outcome {
            FixOutcome::Applied(s) => assert!(s.starts_with("would create")),
            FixOutcome::Skipped(_) => panic!("expected Applied"),
        }
        assert!(!tmp.path().join("x.txt").exists());
    }

    #[test]
    fn file_prepend_inserts_at_start() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("a.rs"), "fn main() {}\n").unwrap();
        let fixer = FilePrependFixer::new("// Copyright 2026\n".into());
        fixer
            .apply(
                &Violation::new("missing header").with_path(std::path::Path::new("a.rs")),
                &make_ctx(&tmp, false),
            )
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("a.rs")).unwrap(),
            "// Copyright 2026\nfn main() {}\n"
        );
    }

    #[test]
    fn file_prepend_preserves_utf8_bom() {
        let tmp = TempDir::new().unwrap();
        // BOM + "hello\n"
        let mut bytes = b"\xEF\xBB\xBF".to_vec();
        bytes.extend_from_slice(b"hello\n");
        std::fs::write(tmp.path().join("x.txt"), &bytes).unwrap();
        let fixer = FilePrependFixer::new("HEAD\n".into());
        fixer
            .apply(
                &Violation::new("m").with_path(std::path::Path::new("x.txt")),
                &make_ctx(&tmp, false),
            )
            .unwrap();
        let got = std::fs::read(tmp.path().join("x.txt")).unwrap();
        assert_eq!(&got[..3], b"\xEF\xBB\xBF");
        assert_eq!(&got[3..], b"HEAD\nhello\n");
    }

    #[test]
    fn file_prepend_dry_run_does_not_touch_disk() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("a.rs"), "original\n").unwrap();
        FilePrependFixer::new("HEAD\n".into())
            .apply(
                &Violation::new("m").with_path(std::path::Path::new("a.rs")),
                &make_ctx(&tmp, true),
            )
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("a.rs")).unwrap(),
            "original\n"
        );
    }

    #[test]
    fn file_prepend_skips_when_violation_has_no_path() {
        let tmp = TempDir::new().unwrap();
        let outcome = FilePrependFixer::new("h".into())
            .apply(&Violation::new("m"), &make_ctx(&tmp, false))
            .unwrap();
        assert!(matches!(outcome, FixOutcome::Skipped(_)));
    }

    #[test]
    fn file_append_writes_at_end() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("notes.md"), "# Notes\n").unwrap();
        let fixer = FileAppendFixer::new("\n## Section\n".into());
        fixer
            .apply(
                &Violation::new("missing section").with_path(std::path::Path::new("notes.md")),
                &make_ctx(&tmp, false),
            )
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("notes.md")).unwrap(),
            "# Notes\n\n## Section\n"
        );
    }

    #[test]
    fn file_append_dry_run_leaves_file_unchanged() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("x.txt"), "orig\n").unwrap();
        FileAppendFixer::new("extra\n".into())
            .apply(
                &Violation::new("m").with_path(std::path::Path::new("x.txt")),
                &make_ctx(&tmp, true),
            )
            .unwrap();
        assert_eq!(
            std::fs::read_to_string(tmp.path().join("x.txt")).unwrap(),
            "orig\n"
        );
    }

    #[test]
    fn file_append_skips_when_violation_has_no_path() {
        let tmp = TempDir::new().unwrap();
        let outcome = FileAppendFixer::new("x".into())
            .apply(&Violation::new("m"), &make_ctx(&tmp, false))
            .unwrap();
        assert!(matches!(outcome, FixOutcome::Skipped(_)));
    }
}