Skip to main content

cargo_critpath/
error.rs

1//! Everything that can go wrong reading a build's output.
2
3use core::fmt;
4
5use critpath_core::GraphError;
6
7/// Enough of a unit's identity to name it in an error message.
8///
9/// A unit that could not be matched has to be described from whichever side saw it, so the fields
10/// that side does not know are empty rather than invented.
11#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
12#[non_exhaustive]
13pub struct UnitDescription {
14    /// Package name, where it is known.
15    pub package: String,
16    /// Package version, where it is known.
17    pub version: String,
18    /// Target within the package: `lib`, a binary name, or a build-script phase.
19    pub target: String,
20    /// Where in its input the unit was seen, counted from one, for locating it by eye.
21    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/// A build's output that could not be turned into a graph, and why.
43///
44/// Every variant's message states what to do next, because the usual cause is that the build the
45/// output came from was not the kind of build the analysis needs.
46#[derive(Clone, Debug, PartialEq)]
47#[non_exhaustive]
48pub enum ParseError {
49    /// The input holds NUL characters, so it is not the UTF-8 text Cargo wrote.
50    NotUtf8 {
51        /// What was being read, for the message: `build log` or `timing report`.
52        what: &'static str,
53        /// How many NUL characters were found.
54        nuls: usize,
55    },
56    /// The verbose log contained no compiler invocations at all.
57    NoInvocations,
58    /// A `Running` line could not be split into arguments because a quote was left open.
59    UnbalancedQuoting {
60        /// The offending line, truncated.
61        line: String,
62    },
63    /// The timing report contained no `UNIT_DATA` array.
64    NoUnitData,
65    /// A JavaScript array literal in the timing report was not valid JSON.
66    MalformedArray {
67        /// The name of the assignment, such as `UNIT_DATA`.
68        name: String,
69        /// What `serde_json` said about it.
70        detail: String,
71    },
72    /// An array literal in the timing report was cut off before its closing bracket.
73    TruncatedArray {
74        /// The name of the assignment, such as `UNIT_DATA`.
75        name: String,
76    },
77    /// A `UNIT_DATA` entry was missing a field, or the field had the wrong type.
78    BadUnitField {
79        /// Which entry, counted from zero as the report numbers them.
80        entry: usize,
81        /// The field that was wrong.
82        field: &'static str,
83        /// What was expected of it.
84        expected: &'static str,
85    },
86    /// The timing report's summary table was absent or unreadable.
87    NoSummaryTable,
88    /// The timing report's summary table lacked a row the analysis needs.
89    MissingSummaryRow {
90        /// The row's label, as Cargo writes it.
91        row: &'static str,
92    },
93    /// A summary row was present but did not hold the expected kind of value.
94    BadSummaryRow {
95        /// The row's label, as Cargo writes it.
96        row: &'static str,
97        /// What the row actually contained.
98        value: String,
99        /// What was expected of it.
100        expected: &'static str,
101    },
102    /// The build reused cached units, so most of its weights are zero.
103    FreshUnits {
104        /// How many units were reused.
105        fresh: usize,
106        /// How many units the build had in total.
107        total: usize,
108    },
109    /// The build compiled nothing.
110    EmptyBuild,
111    /// A duration in the timing report is not a duration.
112    DurationOutOfRange {
113        /// Which entry, counted from zero.
114        entry: usize,
115        /// The value that could not be used.
116        seconds: f64,
117    },
118    /// The two inputs describe different sets of units.
119    UnmatchedUnits {
120        /// Units the verbose log has and the timing report does not.
121        in_log: Vec<UnitDescription>,
122        /// Units the timing report has and the verbose log does not.
123        in_report: Vec<UnitDescription>,
124        /// Whether `cargo metadata` output was supplied.
125        had_metadata: bool,
126    },
127    /// A `--extern` names an artifact no invocation in this log produced.
128    UnresolvedDependency {
129        /// The unit that named it, boxed so that a failure path does not widen every `Result` in
130        /// the crate.
131        consumer: Box<UnitDescription>,
132        /// The `--extern` name.
133        dependency: String,
134        /// The artifact path's producer hash, where there was one.
135        producer: String,
136    },
137    /// `cargo metadata` output could not be read.
138    Metadata {
139        /// What was wrong with it.
140        detail: String,
141    },
142    /// The assembled graph was rejected by the core.
143    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
335/// Refuses text that holds NUL characters.
336///
337/// Cargo's output is UTF-8 and never contains a NUL. UTF-16LE without a byte-order mark decodes as
338/// valid UTF-8 in which every second character is one, so this is what tells a mis-encoded capture
339/// apart from an empty one. A stray NUL is not tolerated either: there is no reading under which
340/// Cargo would have written one.
341pub(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}