Skip to main content

xtask/tasks/fmt/lints/
crate_name_nodash.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Checks that crate names and their containing folder names do not use
5//! dashes (hyphens). Use underscores instead.
6
7use super::Lint;
8use super::LintCtx;
9use super::Lintable;
10use toml_edit::DocumentMut;
11
12pub struct CrateNameNoDash;
13
14impl Lint for CrateNameNoDash {
15    fn new(_ctx: &LintCtx) -> Self {
16        CrateNameNoDash
17    }
18
19    fn enter_workspace(&mut self, _content: &Lintable<DocumentMut>) {}
20
21    fn enter_crate(&mut self, _content: &Lintable<DocumentMut>) {}
22
23    fn visit_file(&mut self, _content: &mut Lintable<String>) {}
24
25    fn exit_crate(&mut self, content: &mut Lintable<DocumentMut>) {
26        let package_name = match content
27            .as_table()
28            .get("package")
29            .and_then(|p| p.get("name"))
30            .and_then(|n| n.as_str())
31        {
32            Some(name) => name,
33            None => return, // Root of a different workspace, like xsync
34        };
35
36        // Check for allow-dash-in-name metadata escape hatch. Lookups work on
37        // both standard and inline TOML tables.
38        if content
39            .as_table()
40            .get("package")
41            .and_then(|x| x.get("metadata"))
42            .and_then(|x| x.get("xtask"))
43            .and_then(|x| x.get("house-rules"))
44            .and_then(|x| x.get("allow-dash-in-name"))
45            .and_then(|x| x.as_bool())
46            .unwrap_or(false)
47        {
48            return;
49        }
50
51        let bad_package_name = package_name.contains('-');
52        let bad_package_path = content
53            .path()
54            .parent()
55            .and_then(|p| p.file_name())
56            .unwrap_or_default()
57            .to_string_lossy()
58            .contains('-');
59
60        let msg = match (bad_package_name, bad_package_path) {
61            (true, true) => "crate name + folder cannot contain '-' char",
62            (true, false) => "crate name cannot contain '-' char",
63            (false, true) => "crate folder cannot contain '-' char",
64            _ => return,
65        };
66
67        content.unfixable(&format!(
68            "{}: name={} folder={}",
69            msg,
70            package_name,
71            content
72                .path()
73                .parent()
74                .map(|p| p.display().to_string())
75                .unwrap_or_default()
76        ));
77    }
78
79    fn exit_workspace(&mut self, _content: &mut Lintable<DocumentMut>) {}
80}
81
82#[cfg(test)]
83mod tests {
84    use super::super::test_support::failed;
85    use super::super::test_support::lintable;
86    use super::*;
87
88    fn fails(path: &str, manifest: &str) -> bool {
89        let mut file = lintable(path, manifest.parse::<DocumentMut>().unwrap(), false);
90        CrateNameNoDash.exit_crate(&mut file);
91        failed(&file)
92    }
93
94    // Test: Check crate names and folders with and without dashes, the boolean
95    //       escape hatch set true or false, and a workspace-only manifest.
96    // Expected: Any dash in the name or folder fails unless explicitly allowed;
97    //       manifests without a package are skipped.
98    #[test]
99    fn rejects_dashes_unless_explicitly_allowed() {
100        assert!(!fails(
101            "vm/good_crate/Cargo.toml",
102            "[package]\nname = \"good_crate\"\n"
103        ));
104        assert!(fails(
105            "vm/good_crate/Cargo.toml",
106            "[package]\nname = \"bad-crate\"\n"
107        ));
108        assert!(fails(
109            "vm/bad-dir/Cargo.toml",
110            "[package]\nname = \"good\"\n"
111        ));
112        assert!(fails(
113            "vm/bad-dir/Cargo.toml",
114            "[package]\nname = \"bad-name\"\n"
115        ));
116        let allow = |v: &str| {
117            format!(
118                "[package]\nname = \"bad-name\"\n[package.metadata.xtask.house-rules]\nallow-dash-in-name = {v}\n"
119            )
120        };
121        assert!(!fails("vm/bad-name/Cargo.toml", &allow("true")));
122        assert!(fails("vm/bad-name/Cargo.toml", &allow("false")));
123        assert!(!fails("Cargo.toml", "[workspace]\nmembers = []\n"));
124    }
125
126    // Test: Check a dashed crate whose escape hatch is an inline TOML table,
127    //       and one whose `house-rules` value is not a table at all.
128    // Expected: The inline form is honoured like the standard table form; a
129    //       non-table value grants no exception and is reported, without panicking.
130    #[test]
131    fn inline_table_escape_hatch_is_honoured() {
132        let manifest = "[package]\nname = \"bad-name\"\nmetadata.xtask.house-rules = { allow-dash-in-name = true }\n";
133        assert!(!fails("vm/bad-name/Cargo.toml", manifest));
134        let not_table = "[package]\nname = \"bad-name\"\nmetadata.xtask.house-rules = true\n";
135        assert!(fails("vm/bad-name/Cargo.toml", not_table));
136    }
137}