1use std::collections::BTreeSet;
18use std::path::Path;
19use std::process::Command;
20
21pub const TIERS: [&str; 3] = ["unit", "integration", "system"];
23
24pub const LOWER_PROFILE: &str = "ci-lower";
26
27pub fn parse_list(json: &str) -> Result<BTreeSet<String>, String> {
31 let doc: serde_json::Value =
32 serde_json::from_str(json).map_err(|e| format!("not JSON: {e}"))?;
33 let suites = doc
34 .get("rust-suites")
35 .and_then(|s| s.as_object())
36 .ok_or("no `rust-suites` object: not nextest list output")?;
37 let mut out = BTreeSet::new();
38 for (binary, suite) in suites {
39 let cases = suite
40 .get("testcases")
41 .and_then(|c| c.as_object())
42 .ok_or_else(|| format!("suite `{binary}` has no `testcases` object"))?;
43 out.extend(
48 cases
49 .iter()
50 .filter(|(_, case)| {
51 case.pointer("/filter-match/status")
52 .and_then(|v| v.as_str())
53 != Some("mismatch")
54 })
55 .map(|(name, _)| format!("{binary} {name}")),
56 );
57 }
58 Ok(out)
59}
60
61pub fn check_partition(
64 all: &BTreeSet<String>,
65 tiers: &[(&str, BTreeSet<String>)],
66) -> Result<Vec<(String, usize)>, Vec<String>> {
67 let mut problems = Vec::new();
68 if all.is_empty() {
69 problems.push("the full test list is empty: nothing was listed".to_string());
70 }
71 for (name, set) in tiers {
72 if set.is_empty() {
73 problems.push(format!("tier `{name}` selects no test"));
74 }
75 }
76 for test in all {
77 let in_tiers: Vec<&str> = tiers
78 .iter()
79 .filter(|(_, set)| set.contains(test))
80 .map(|(name, _)| *name)
81 .collect();
82 match in_tiers.len() {
83 1 => {}
84 0 => problems.push(format!("in no tier: {test}")),
85 _ => problems.push(format!(
86 "in {} tiers ({}): {test}",
87 in_tiers.len(),
88 in_tiers.join(", ")
89 )),
90 }
91 }
92 for (name, set) in tiers {
93 for test in set.difference(all) {
94 problems.push(format!(
95 "tier `{name}` selects a test the full list lacks: {test}"
96 ));
97 }
98 }
99 if problems.is_empty() {
100 Ok(tiers
101 .iter()
102 .map(|(n, s)| (n.to_string(), s.len()))
103 .collect())
104 } else {
105 Err(problems)
106 }
107}
108
109pub fn check_lower(
113 lower: &BTreeSet<String>,
114 unit: &BTreeSet<String>,
115 integration: &BTreeSet<String>,
116) -> Result<(), Vec<String>> {
117 let want: BTreeSet<&String> = unit.union(integration).collect();
118 let got: BTreeSet<&String> = lower.iter().collect();
119 let mut problems = Vec::new();
120 for t in want.difference(&got) {
121 problems.push(format!(
122 "{LOWER_PROFILE} omits the unit/integration test `{t}`"
123 ));
124 }
125 for t in got.difference(&want) {
126 problems.push(format!(
127 "{LOWER_PROFILE} selects `{t}`, which is not unit or integration"
128 ));
129 }
130 if problems.is_empty() {
131 Ok(())
132 } else {
133 Err(problems)
134 }
135}
136
137pub fn check_profiles(nextest_toml: &str) -> Result<(), Vec<String>> {
140 let doc: toml::Table = nextest_toml
141 .parse()
142 .map_err(|e| vec![format!(".config/nextest.toml does not parse: {e}")])?;
143 let profiles = doc
144 .get("profile")
145 .and_then(|p| p.as_table())
146 .ok_or_else(|| vec![".config/nextest.toml has no [profile.*] tables".to_string()])?;
147 let mut problems = Vec::new();
148 let names = TIERS
149 .iter()
150 .map(|t| format!("ci-{t}"))
151 .chain([LOWER_PROFILE.to_string()]);
152 for name in names {
153 let Some(profile) = profiles.get(&name).and_then(|p| p.as_table()) else {
154 problems.push(format!("[profile.{name}] is missing"));
155 continue;
156 };
157 if profile.get("inherits").and_then(|v| v.as_str()) != Some("ci") {
158 problems.push(format!("[profile.{name}] must `inherits = \"ci\"`"));
159 }
160 let filter = profile
161 .get("default-filter")
162 .and_then(|v| v.as_str())
163 .unwrap_or("");
164 if filter.trim().is_empty() {
165 problems.push(format!("[profile.{name}] has no `default-filter`"));
166 }
167 }
168 if problems.is_empty() {
169 Ok(())
170 } else {
171 Err(problems)
172 }
173}
174
175fn list(root: &Path, profile: &str) -> Result<BTreeSet<String>, String> {
176 let out = Command::new("cargo")
177 .args([
178 "nextest",
179 "list",
180 "--workspace",
181 "--locked",
182 "--profile",
183 profile,
184 ])
185 .args(["--message-format", "json"])
186 .current_dir(root)
187 .output()
188 .map_err(|e| {
189 format!("cannot run `cargo nextest list` (is cargo-nextest installed?): {e}")
190 })?;
191 if !out.status.success() {
192 return Err(format!(
193 "`cargo nextest list --profile {profile}` failed:\n{}",
194 String::from_utf8_lossy(&out.stderr)
195 ));
196 }
197 parse_list(&String::from_utf8_lossy(&out.stdout)).map_err(|e| format!("profile {profile}: {e}"))
198}
199
200pub fn probe(root: &Path) -> Result<String, Vec<String>> {
202 let all = list(root, "ci").map_err(|e| vec![e])?;
203 let mut sets = Vec::new();
204 for tier in TIERS {
205 sets.push((
206 tier,
207 list(root, &format!("ci-{tier}")).map_err(|e| vec![e])?,
208 ));
209 }
210 let sizes = check_partition(&all, &sets)?;
211 let lower = list(root, LOWER_PROFILE).map_err(|e| vec![e])?;
212 check_lower(&lower, &sets[0].1, &sets[1].1)?;
213 let total: usize = sizes.iter().map(|(_, n)| n).sum();
214 let parts: Vec<String> = sizes.iter().map(|(t, n)| format!("{t} {n}")).collect();
215 Ok(format!(
216 "{total} tests, each in exactly one tier ({})",
217 parts.join(", ")
218 ))
219}