Skip to main content

tidy/
triagebot.rs

1//! Tidy check to ensure paths mentioned in triagebot.toml exist in the project.
2
3use std::collections::HashSet;
4use std::path::Path;
5use std::sync::LazyLock;
6
7use toml::Value;
8
9use crate::diagnostics::{RunningCheck, TidyCtx};
10
11static SUBMODULES: LazyLock<Vec<&'static Path>> = LazyLock::new(|| {
12    // WORKSPACES doesn't list all submodules but it's contains the main at least
13    crate::deps::WORKSPACES
14        .iter()
15        .map(|ws| ws.submodules.iter())
16        .flatten()
17        .map(|p| Path::new(p))
18        .collect()
19});
20
21pub fn check(path: &Path, tidy_ctx: TidyCtx) {
22    let check = tidy_ctx.start_check("triagebot");
23    let triagebot_path = path.join("triagebot.toml");
24
25    // This check is mostly to catch broken path filters *within* `triagebot.toml`, and not enforce
26    // the existence of `triagebot.toml` itself (which is more obvious), as distribution tarballs
27    // will not include non-essential bits like `triagebot.toml`.
28    if !triagebot_path.exists() {
29        return;
30    }
31
32    let contents = std::fs::read_to_string(&triagebot_path).unwrap();
33    let config: Value = toml::from_str(&contents).unwrap();
34
35    // Check [mentions."*"] sections, i.e. [mentions."compiler/rustc_const_eval/src/"]
36    if let Some(Value::Table(mentions)) = config.get("mentions") {
37        check_glob_patterns(
38            path,
39            &check,
40            "[mentions.*]",
41            mentions
42                .iter()
43                .filter(|(_, entry_val)| {
44                    // Keep if type is missing or equals "filename"
45                    entry_val.get("type").and_then(|t| t.as_str()).map_or(true, |t| t == "filename")
46                })
47                .map(|(entry_key, _)| entry_key.as_str()),
48        );
49    } else {
50        check.error(
51            "triagebot.toml missing [mentions.*] section, this wrong for rust-lang/rust repo.",
52        );
53    }
54
55    // Check [assign.owners] sections, i.e.
56    // [assign.owners]
57    // "/.github/workflows" = ["infra-ci"]
58    if let Some(Value::Table(assign)) = config.get("assign") {
59        if let Some(Value::Table(owners)) = assign.get("owners") {
60            for path_str in owners.keys() {
61                // Remove quotes and leading slash from the path
62                let clean_path = path_str.trim_matches('"').trim_start_matches('/');
63                let full_path = path.join(clean_path);
64
65                if !full_path.exists() {
66                    check.error(format!(
67                        "triagebot.toml [assign.owners] contains path '{clean_path}' which doesn't exist"
68                    ));
69                }
70            }
71        } else {
72            check.error(
73                "triagebot.toml missing [assign.owners] section, this wrong for rust-lang/rust repo."
74            );
75        }
76    }
77
78    // Verify that trigger_files in [autolabel."*"] exist in the project, i.e.
79    // [autolabel."A-rustdoc-search"]
80    // trigger_files = [
81    //    "src/librustdoc/html/static/js/search.js",
82    //    "tests/rustdoc-js",
83    //    "tests/rustdoc-js-std",
84    // ]
85    if let Some(Value::Table(autolabels)) = config.get("autolabel") {
86        for (label, content) in autolabels {
87            if let Some(trigger_files) = content.get("trigger_files").and_then(|v| v.as_array()) {
88                check_glob_patterns(
89                    path,
90                    &check,
91                    &format!("[autolabel.{label}]"),
92                    trigger_files.iter().filter_map(|e| e.as_str()),
93                );
94            }
95        }
96    }
97}
98
99fn check_glob_patterns<'a>(
100    path: &Path,
101    check: &RunningCheck,
102    source: &str,
103    entries: impl Iterator<Item = &'a str>,
104) {
105    let mut builder = globset::GlobSetBuilder::new();
106    let mut glob_entries = Vec::new();
107
108    for path_str in entries {
109        // Remove quotes from the path
110        let clean_path = path_str.trim_matches('"');
111        let full_path = path.join(clean_path);
112
113        if !full_path.exists() {
114            // The full-path doesn't exists, maybe it's a glob, let's add it to the glob set builder
115            // to be checked against all the file and directories in the repository.
116            let trimmed_path = clean_path.trim_end_matches('/');
117            builder.add(
118                globset::GlobBuilder::new(&format!("{trimmed_path}{{,/*}}"))
119                    .empty_alternates(true)
120                    .build()
121                    .unwrap(),
122            );
123            glob_entries.push(clean_path.to_string());
124        } else if is_in_submodule(Path::new(clean_path)) {
125            check.error(format!(
126                "triagebot.toml {source} '{clean_path}' cannot match inside a submodule"
127            ));
128        }
129    }
130
131    let gs = builder.build().unwrap();
132
133    let mut found = HashSet::new();
134    let mut matches = Vec::new();
135
136    let cloned_path = path.to_path_buf();
137
138    // Walk the entire repository and match any entry against the remaining paths
139    for entry in ignore::WalkBuilder::new(&path)
140        .filter_entry(move |entry| {
141            // Ignore entries inside submodules as triagebot cannot detect them
142            let entry_path = entry.path().strip_prefix(&cloned_path).unwrap();
143            is_not_in_submodule(entry_path)
144        })
145        .build()
146        .flatten()
147    {
148        // Strip the prefix as mentions entries are always relative to the repo
149        let entry_path = entry.path().strip_prefix(path).unwrap();
150
151        // Find the matches and add them to the found set
152        gs.matches_into(entry_path, &mut matches);
153        found.extend(matches.iter().copied());
154
155        // Early-exist if all the globs have been matched
156        if found.len() == glob_entries.len() {
157            break;
158        }
159    }
160
161    for (i, clean_path) in glob_entries.iter().enumerate() {
162        if !found.contains(&i) {
163            check.error(format!(
164                "triagebot.toml {source} contains '{clean_path}' which doesn't match any file or directory in the repository"
165            ));
166        }
167    }
168}
169
170fn is_not_in_submodule(path: &Path) -> bool {
171    SUBMODULES.contains(&path) || !SUBMODULES.iter().any(|p| path.starts_with(*p))
172}
173
174fn is_in_submodule(path: &Path) -> bool {
175    !SUBMODULES.contains(&path) && SUBMODULES.iter().any(|p| path.starts_with(*p))
176}