Skip to main content

xtask/tasks/fmt/lints/
trailing_newline.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Checks that text files end with exactly one trailing newline.
5
6use super::Lint;
7use super::LintCtx;
8use super::Lintable;
9use toml_edit::DocumentMut;
10
11const CHECKED_EXTENSIONS: &[&str] = &[
12    "c", "md", "proto", "py", "rs", "sh", "toml", "txt", "yml", "js", "ts",
13];
14
15pub struct TrailingNewline;
16
17impl Lint for TrailingNewline {
18    fn new(_ctx: &LintCtx) -> Self {
19        TrailingNewline
20    }
21
22    fn enter_workspace(&mut self, _content: &Lintable<DocumentMut>) {}
23    fn enter_crate(&mut self, _content: &Lintable<DocumentMut>) {}
24
25    fn visit_file(&mut self, content: &mut Lintable<String>) {
26        let mut ending_newlines = 0;
27        for c in content.as_bytes().iter().rev() {
28            if *c == b'\n' {
29                ending_newlines += 1;
30            } else {
31                break;
32            }
33        }
34
35        if ending_newlines == 0 {
36            content.fix("missing trailing newline", |content| content.push('\n'));
37        } else if ending_newlines != 1 {
38            content.fix("too many trailing newlines", |content| {
39                // Trim all trailing newlines but one.
40                content.truncate(content.len() - ending_newlines + 1);
41            });
42        }
43    }
44
45    fn exit_crate(&mut self, content: &mut Lintable<DocumentMut>) {
46        // toml_edit unfortunately makes checking for a trailing newline
47        // inconvenient, as it parses into the decor of the last item, not the
48        // document as a whole. It's easier to just check the raw file content.
49        let mut ending_newlines = 0;
50        for c in content.raw().unwrap().as_bytes().iter().rev() {
51            if *c == b'\n' {
52                ending_newlines += 1;
53            } else {
54                break;
55            }
56        }
57
58        // Writing a trailing newline is also annoying, as it likes to synthesize
59        // one if it was originally missing. So we just trim all trailing newlines
60        // and let it add one back if needed, being careful not to remove any trailing
61        // comments or the like. It only synthesizes a newline after the last
62        // item, so a trailing comment needs its newline added back here.
63        if ending_newlines != 1 {
64            content.fix("missing or too many trailing newlines", |content| {
65                let trailing = content.trailing().as_str().unwrap().trim_end();
66                let trailing = if trailing.is_empty() {
67                    String::new()
68                } else {
69                    format!("{trailing}\n")
70                };
71                content.set_trailing(trailing);
72            });
73        }
74    }
75
76    fn exit_workspace(&mut self, content: &mut Lintable<DocumentMut>) {
77        self.exit_crate(content)
78    }
79
80    fn visit_nonrust_file(&mut self, extension: &str, content: &mut Lintable<String>) {
81        // workaround for `mdbook-docfx` emitting yaml with no trailing newline
82        if content.path().file_name().unwrap_or_default() == "toc.yml" {
83            return;
84        }
85
86        // TODO: Should we just check everything?
87        if CHECKED_EXTENSIONS.contains(&extension) {
88            self.visit_file(content)
89        }
90    }
91}
92
93#[cfg(test)]
94mod tests {
95    use super::super::test_support::failed;
96    use super::super::test_support::lintable;
97    use super::super::test_support::manifest;
98    use super::*;
99
100    fn fixed(text: &str) -> (String, bool) {
101        let mut file = lintable("src/lib.rs", text.to_owned(), true);
102        TrailingNewline.visit_file(&mut file);
103        (file.content.clone(), file.modified)
104    }
105
106    // Test: Fix files with no, one, several and only trailing newlines.
107    // Expected: Every fixed file ends with exactly one newline, interior blank
108    //       lines are untouched, and an already-correct file is not modified.
109    #[test]
110    fn fixes_trailing_newlines_to_exactly_one() {
111        assert_eq!(fixed("fn a() {}"), ("fn a() {}\n".into(), true));
112        assert_eq!(fixed("a\n\nb\n"), ("a\n\nb\n".into(), false));
113        assert_eq!(fixed("a\n\n\n\n"), ("a\n".into(), true));
114        assert_eq!(fixed("\n\n"), ("\n".into(), true));
115        assert_eq!(fixed(""), ("\n".into(), true));
116    }
117
118    // Test: Fix Cargo.toml manifests with extra trailing newlines or none, with
119    //       and without a trailing comment, then check a correct manifest.
120    // Expected: Each fixed manifest ends with exactly one newline and keeps its
121    //       trailing comment; the correct manifest is not modified.
122    #[test]
123    fn fixes_manifest_trailing_newlines_and_keeps_comments() {
124        let fixed = |raw: &str| {
125            let mut file = manifest("a/Cargo.toml", raw, true);
126            TrailingNewline.exit_crate(&mut file);
127            (file.content.to_string(), file.modified)
128        };
129        let commented = "[package]\nname = \"a\"\n# end\n";
130        let plain = "[package]\nname = \"a\"\n";
131        assert_eq!(
132            fixed("[package]\nname = \"a\"\n# end\n\n\n"),
133            (commented.to_owned(), true)
134        );
135        assert_eq!(
136            fixed("[package]\nname = \"a\"\n# end"),
137            (commented.to_owned(), true)
138        );
139        assert_eq!(
140            fixed("[package]\nname = \"a\"\n\n\n"),
141            (plain.to_owned(), true)
142        );
143        assert_eq!(fixed(commented), (commented.to_owned(), false));
144    }
145
146    // Test: Check, without fixing, a file that lacks its trailing newline, and
147    //       visit non-Rust files with checked, unchecked and exempt names.
148    // Expected: Check mode reports failure without editing; unchecked extensions
149    //       and the generated toc.yml are ignored.
150    #[test]
151    fn check_mode_reports_and_respects_extension_filters() {
152        let mut file = lintable("src/lib.rs", "x".to_owned(), false);
153        TrailingNewline.visit_file(&mut file);
154        assert!(failed(&file));
155        assert_eq!((file.content.as_str(), file.modified), ("x", false));
156
157        for (path, ext, expect_failure) in [
158            ("docs/a.md", "md", true),
159            ("img/a.svg", "svg", false),
160            ("Guide/toc.yml", "yml", false),
161            ("ci/a.yml", "yml", true),
162        ] {
163            let mut file = lintable(path, "x".to_owned(), false);
164            TrailingNewline.visit_nonrust_file(ext, &mut file);
165            assert_eq!(failed(&file), expect_failure, "{path}");
166        }
167    }
168}