1use core::fmt;
4
5use critpath_core::GraphError;
6
7#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
12#[non_exhaustive]
13pub struct UnitDescription {
14 pub package: String,
16 pub version: String,
18 pub target: String,
20 pub position: usize,
22}
23
24impl fmt::Display for UnitDescription {
25 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26 let package = if self.package.is_empty() {
27 "<unknown package>"
28 } else {
29 &self.package
30 };
31 write!(f, "{package}")?;
32 if !self.version.is_empty() {
33 write!(f, " {}", self.version)?;
34 }
35 if !self.target.is_empty() {
36 write!(f, " ({})", self.target)?;
37 }
38 write!(f, " [#{}]", self.position)
39 }
40}
41
42#[derive(Clone, Debug, PartialEq)]
47#[non_exhaustive]
48pub enum ParseError {
49 NotUtf8 {
51 what: &'static str,
53 nuls: usize,
55 },
56 NoInvocations,
58 UnbalancedQuoting {
60 line: String,
62 },
63 NoUnitData,
65 MalformedArray {
67 name: String,
69 detail: String,
71 },
72 TruncatedArray {
74 name: String,
76 },
77 BadUnitField {
79 entry: usize,
81 field: &'static str,
83 expected: &'static str,
85 },
86 NoSummaryTable,
88 MissingSummaryRow {
90 row: &'static str,
92 },
93 BadSummaryRow {
95 row: &'static str,
97 value: String,
99 expected: &'static str,
101 },
102 FreshUnits {
104 fresh: usize,
106 total: usize,
108 },
109 EmptyBuild,
111 DurationOutOfRange {
113 entry: usize,
115 seconds: f64,
117 },
118 UnmatchedUnits {
120 in_log: Vec<UnitDescription>,
122 in_report: Vec<UnitDescription>,
124 had_metadata: bool,
126 },
127 UnresolvedDependency {
129 consumer: Box<UnitDescription>,
132 dependency: String,
134 producer: String,
136 },
137 Metadata {
139 detail: String,
141 },
142 Graph(GraphError),
144}
145
146impl fmt::Display for ParseError {
147 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
148 match self {
149 Self::NotUtf8 { what, nuls } => write!(
150 f,
151 "the {what} holds {nuls} NUL characters, so it is not the UTF-8 text Cargo wrote; \
152 a redirection under PowerShell writes UTF-16. Capture it with \
153 `cargo build --timings -v --offline 2>&1 | Out-File -Encoding utf8 build.log`, \
154 or from a shell that redirects as UTF-8"
155 ),
156 Self::NoInvocations => write!(
157 f,
158 "the build log contains no compiler invocations; \
159 it was captured without -v, or every unit was already up to date. \
160 Run `cargo clean` and then \
161 `cargo build --timings -v --offline 2>build.log`"
162 ),
163 Self::UnbalancedQuoting { line } => write!(
164 f,
165 "a `Running` line in the build log has an unclosed quote and cannot be split into \
166 arguments: {line}. \
167 The log is probably truncated; capture it again, redirecting stderr to a file \
168 rather than copying it out of a terminal"
169 ),
170 Self::NoUnitData => write!(
171 f,
172 "the timing report contains no `UNIT_DATA` array, so it holds no per-unit times. \
173 Check that the file is the `cargo-timing.html` Cargo wrote and not the \
174 `cargo-timing-<date>.html` copy of an older run, and that the build used --timings"
175 ),
176 Self::MalformedArray { name, detail } => write!(
177 f,
178 "the `{name}` array in the timing report is not valid JSON ({detail}); \
179 this Cargo version writes a shape the parser does not know. \
180 Report the Cargo version, and in the meantime the analysis cannot use this report"
181 ),
182 Self::TruncatedArray { name } => write!(
183 f,
184 "the `{name}` array in the timing report is cut off before its closing bracket, \
185 so the file is incomplete; \
186 the build was probably interrupted, so run it again to completion"
187 ),
188 Self::BadUnitField {
189 entry,
190 field,
191 expected,
192 } => write!(
193 f,
194 "entry {entry} of `UNIT_DATA` has no usable `{field}` (expected {expected}); \
195 this Cargo version writes a shape the parser does not know, \
196 so report the Cargo version"
197 ),
198 Self::NoSummaryTable => write!(
199 f,
200 "the timing report has no summary table, so the build's unit counts and job limit \
201 cannot be read; \
202 check that the file is a complete `cargo-timing.html`"
203 ),
204 Self::MissingSummaryRow { row } => write!(
205 f,
206 "the timing report's summary table has no `{row}` row, \
207 so the analysis cannot tell whether the build was a clean one; \
208 this Cargo version writes a shape the parser does not know, \
209 so report the Cargo version"
210 ),
211 Self::BadSummaryRow {
212 row,
213 value,
214 expected,
215 } => write!(
216 f,
217 "the timing report's `{row}` row holds {value:?}, which is not {expected}; \
218 this Cargo version writes a shape the parser does not know, \
219 so report the Cargo version"
220 ),
221 Self::FreshUnits { fresh, total } => write!(
222 f,
223 "{fresh} of this build's {total} units were reused from the cache, so their \
224 recorded durations are zero and any critical path computed from them would be \
225 meaningless. \
226 Run `cargo clean` first, then \
227 `cargo build --timings -v --offline 2>build.log`"
228 ),
229 Self::EmptyBuild => write!(
230 f,
231 "the build compiled nothing, so there is no graph to analyse; \
232 run `cargo clean` and build again"
233 ),
234 Self::DurationOutOfRange { entry, seconds } => write!(
235 f,
236 "entry {entry} of `UNIT_DATA` reports a duration of {seconds} seconds, which is \
237 not a duration this analysis can use; \
238 the report is corrupt, so run the build again"
239 ),
240 Self::UnmatchedUnits {
241 in_log,
242 in_report,
243 had_metadata,
244 } => {
245 write!(
246 f,
247 "the build log and the timing report describe different sets of units, \
248 so a graph built from them would silently omit work"
249 )?;
250 if !in_log.is_empty() {
251 write!(f, "; only in the build log: ")?;
252 write_list(f, in_log)?;
253 }
254 if !in_report.is_empty() {
255 write!(f, "; only in the timing report: ")?;
256 write_list(f, in_report)?;
257 }
258 write!(
259 f,
260 ". Both must come from the same build, so capture them together with "
261 )?;
262 write!(f, "`cargo build --timings -v --offline 2>build.log`")?;
263 if *had_metadata {
264 write!(
265 f,
266 ". The `cargo metadata` output supplied did not cover these units, so \
267 check that it came from the same workspace"
268 )
269 } else {
270 write!(
271 f,
272 ". Supplying `cargo metadata --format-version 1` output as well would let \
273 a workspace-local package be attributed to its manifest exactly instead \
274 of by its directory name"
275 )
276 }
277 }
278 Self::UnresolvedDependency {
279 consumer,
280 dependency,
281 producer,
282 } => write!(
283 f,
284 "unit {consumer} depends on `{dependency}` through artifact {producer}, which no \
285 invocation in this log produced, so an edge would be missing from the graph and \
286 the critical path would be understated. \
287 That happens when part of the build was already up to date: \
288 run `cargo clean` and build again"
289 ),
290 Self::Metadata { detail } => write!(
291 f,
292 "the `cargo metadata` output could not be read ({detail}); \
293 produce it with `cargo metadata --format-version 1`, \
294 or omit it and local packages will be attributed by directory name instead"
295 ),
296 Self::Graph(inner) => write!(
297 f,
298 "the graph assembled from this build was rejected: {inner}. \
299 This is a defect in the adapter rather than in the build, so please report it \
300 with the Cargo version"
301 ),
302 }
303 }
304}
305
306fn write_list(f: &mut fmt::Formatter<'_>, units: &[UnitDescription]) -> fmt::Result {
307 const SHOWN: usize = 8;
308 for (i, unit) in units.iter().take(SHOWN).enumerate() {
309 if i > 0 {
310 write!(f, ", ")?;
311 }
312 write!(f, "{unit}")?;
313 }
314 if units.len() > SHOWN {
315 write!(f, ", and {} more", units.len().saturating_sub(SHOWN))?;
316 }
317 Ok(())
318}
319
320impl std::error::Error for ParseError {
321 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
322 match self {
323 Self::Graph(inner) => Some(inner),
324 _ => None,
325 }
326 }
327}
328
329impl From<GraphError> for ParseError {
330 fn from(inner: GraphError) -> Self {
331 Self::Graph(inner)
332 }
333}
334
335pub(crate) fn reject_wide_text(text: &str, what: &'static str) -> Result<(), ParseError> {
342 let nuls = text.bytes().filter(|b| *b == 0).count();
343 if nuls > 0 {
344 return Err(ParseError::NotUtf8 { what, nuls });
345 }
346 Ok(())
347}