Repository navigation
Expand file tree
/
Copy patherror.rs
More file actions
446 lines (417 loc) · 16.7 KB
/
Copy patherror.rs
File metadata and controls
446 lines (417 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
use std::path::PathBuf;
use std::{env, fmt};
use common::SpecOrigin;
use graph::{Graph, PlanErr};
/// The errors possible when driving top-level minimal APIs.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("config error: {0}")]
Config(#[from] super::ConfigError),
#[error("{} I/O error at path {}: {}", .0, .1.display(), .2)]
IO(&'static str, PathBuf, #[source] std::io::Error),
#[error("invalid TOML: {0}")]
Format(#[source] toml::de::Error),
// Every mfile error's Display already prints its cause: the TOML parse
// error, or the io error. So the variant returns no `source()`, and a
// chain printer such as `{:#}` shows each cause once.
#[error("{prefix}: {0}", prefix = mfile::MFILE_NAME)]
MFile(mfile::Error),
#[error("{}", GraphDisplay(.0))]
Graph(Box<graph::Error>),
#[error("{}", PlanDisplay(.0))]
Plan(Box<(Graph, PlanErr)>),
#[error(
"{}",
ExecutionDisplay {
idx,
code,
reason,
stderr,
stdout
}
)]
Execution {
idx: usize,
code: i32,
reason: String,
stderr: String,
/// Last ~4 KiB of stdout (captured by `sandbox` alongside stderr).
/// Useful when build scripts redirect stderr away (e.g.
/// `pip install ... 2>/dev/null || true`) and the real
/// diagnostic only appears on stdout.
stdout: String,
},
#[error("{0}")]
Other(anyhow::Error),
}
impl Error {
/// Writes a human-friendly error to the given terminal or buffer.
pub fn report_to(&self, writer: &mut dyn codespan_reporting::term::termcolor::WriteColor) {
match self {
Error::Plan(b) => {
let (graph, err) = b.as_ref();
match err {
PlanErr::Cycles(cycles) => {
writeln!(
writer,
"Planning failed: unable to progress with unresolvable dependency cycles"
).unwrap();
writeln!(writer, "Cycles:").unwrap();
for c in cycles {
writeln!(
writer,
"\t{}",
c.iter()
.map(|bsr| graph.get(bsr).unwrap().name.clone())
.collect::<Vec<_>>()
.join(" -> "),
)
.unwrap()
}
}
}
}
Error::Graph(e) => {
match &**e {
// Slightly better error message if the upstream is not pinned, and this
// error occurred on the top-level repo.
graph::Error::UpstreamNotPinned {
upstream,
at_layer: SpecOrigin::LocalDir { absolute, .. },
} if env::current_dir()
.map(|d| absolute.starts_with(d))
.unwrap_or(false) =>
{
writeln!(writer, "Error: upstream defined but not pinned to a commit")
.unwrap();
writeln!(writer).unwrap();
writeln!(writer, "> minimal.toml").unwrap();
writeln!(writer, "[upstream]").unwrap();
writeln!(writer, "repo = \"{}\"", upstream).unwrap();
writeln!(
writer,
"locked_commit = <pinned commit hash>\t# missing field"
)
.unwrap();
writeln!(writer).unwrap();
writeln!(writer, "help: try running `minimal update`").unwrap();
}
_ => e.report_to(writer),
}
}
_ => writeln!(writer, "{}", self).unwrap(),
}
}
pub fn report_to_stderr(&self) {
common::report_to_stderr(|w| self.report_to(w));
}
}
/// Renders [`Error::Graph`]'s codespan diagnostic into a single line.
struct GraphDisplay<'a>(&'a graph::Error);
impl fmt::Display for GraphDisplay<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// Render the codespan diagnostic (source location + caret)
// into a buffer. NEVER use `{:?}` here — graph::Error's
// Decode(Nickel(..)) variant carries a
// codespan_reporting::files::Files index with every loaded
// source file's contents embedded, so Debug-dumping it
// floods the output with the ~5k-line Nickel stdlib plus
// every other file in the chain. `report_to` uses the same
// codespan facility to emit the human-readable diagnostic
// without the embedded source tree.
use codespan_reporting::term::termcolor::NoColor;
let mut buf: Vec<u8> = Vec::new();
self.0.report_to(&mut NoColor::new(&mut buf));
write!(f, "graph: {}", String::from_utf8_lossy(&buf).trim_end())
}
}
/// Renders [`Error::Plan`]'s unresolvable-cycle message.
struct PlanDisplay<'a>(&'a (Graph, PlanErr));
impl fmt::Display for PlanDisplay<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let (graph, PlanErr::Cycles(c)) = self.0;
write!(
f,
"Planning failed: unable to progress with unresolvable dependency cycles"
)?;
write!(f, "Cycles:")?;
for c in c.iter() {
write!(
f,
"\t{}",
c.iter()
.map(|bsr| graph.get(bsr).unwrap().name.clone())
.collect::<Vec<_>>()
.join(" -> "),
)?;
}
Ok(())
}
}
/// Renders [`Error::Execution`]'s conditional exit-code message.
struct ExecutionDisplay<'a> {
idx: &'a usize,
code: &'a i32,
reason: &'a String,
stderr: &'a String,
stdout: &'a String,
}
impl fmt::Display for ExecutionDisplay<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if *self.code == 125 {
write!(f, "invocation {} failed: {}", self.idx, self.reason)?;
} else {
write!(f, "invocation {} failed: exit code {}", self.idx, self.code)?;
}
if !self.stderr.is_empty() {
write!(f, "\nstderr:\n{}", self.stderr)?;
}
if !self.stdout.is_empty() {
write!(f, "\nstdout:\n{}", self.stdout)?;
}
Ok(())
}
}
impl Error {
/// Constructs an error wrapping an IO error when trying to create necessary directories.
pub(crate) fn setup_dirs(e: std::io::Error, erroring_path: PathBuf) -> Self {
Self::IO("directory setup", erroring_path, e)
}
}
impl From<checkouts::Error> for Error {
fn from(value: checkouts::Error) -> Self {
match value {
checkouts::Error::IO(e) => Self::IO("vcs", PathBuf::new(), e),
checkouts::Error::Other(e) => Self::Other(anyhow::anyhow!(e)),
checkouts::Error::GitCommandFailed {
command,
stderr,
status,
} => Self::Other(anyhow::anyhow!(
"unexpected: git command '{command}' failed ({status}): {stderr}"
)),
e @ (checkouts::Error::OptionLike { .. } | checkouts::Error::EmptyValue { .. }) => {
Self::Other(anyhow::anyhow!("{e}"))
}
checkouts::Error::InvalidPath => {
Self::Other(anyhow::anyhow!("vcs: invalid remote path"))
}
checkouts::Error::StatefileInvalid(e) => {
Self::Other(anyhow::anyhow!("vcs: failed parsing state file: {}", e))
}
checkouts::Error::OfflineCacheMiss { remote } => Self::Other(anyhow::anyhow!(
"vcs: offline cache miss for remote {} — --offline is set; pre-populate \
the vcs/ cache or remove the flag",
remote
)),
}
}
}
impl From<graph::Error> for Error {
fn from(value: graph::Error) -> Self {
Error::Graph(Box::new(value))
}
}
impl From<op::Error> for Error {
fn from(value: op::Error) -> Self {
match value {
op::Error::IO(e) => Self::IO("op", PathBuf::new(), e),
op::Error::Plan(graph, e) => Self::Plan(Box::new((graph, e))),
other => Self::Other(anyhow::anyhow!("{}", other)),
}
}
}
impl From<orchestrator::Error> for Error {
fn from(value: orchestrator::Error) -> Self {
match value {
orchestrator::Error::IO(e) => Self::IO("vcs", PathBuf::new(), e),
orchestrator::Error::Other(e) => Self::Other(anyhow::anyhow!(e)),
orchestrator::Error::Cache(e) => Self::Other(anyhow::anyhow!(e)), // TODO: better error
orchestrator::Error::BuildFailed(build, e) => {
Self::Other(anyhow::anyhow!("`{build}` failed to build: {e}"))
} // TODO: better error
orchestrator::Error::Sandbox(e) => Self::Other(anyhow::anyhow!(e)), // TODO: better error
orchestrator::Error::Plan(graph, e) => Self::Plan(Box::new((graph, e))),
e @ orchestrator::Error::DanglingCacheHit(_) => Self::Other(anyhow::anyhow!("{e}")),
}
}
}
impl From<check::Error> for Error {
fn from(value: check::Error) -> Self {
match value {
check::Error::IO(s, p, e) => Self::IO(s, p, e),
check::Error::Other(e) => Self::Other(e),
check::Error::Graph(e) => Self::Graph(e),
// Unreachable through this crate: mctx never hands `check` a token
// it later fires.
check::Error::Cancelled => Self::Other(anyhow::anyhow!("checks were cancelled")),
}
}
}
impl From<sandbox::Error> for Error {
fn from(value: sandbox::Error) -> Self {
match value {
sandbox::Error::IO(s, p, e) => Self::IO(s, p, e),
sandbox::Error::HardlinkFailed(e) => e.into(),
sandbox::Error::Execution(e) => match e {
sandbox::error::ExecutionError::InvocationFailed {
idx,
code,
reason,
stderr,
stdout,
} => Self::Execution {
idx,
code,
reason,
stderr,
stdout,
},
#[cfg(target_os = "linux")]
sandbox::error::ExecutionError::SpawnFailed(e) => {
Self::Other(anyhow::anyhow!("spawn failed: {}", e))
}
sandbox::error::ExecutionError::Cancelled => {
Self::Other(anyhow::anyhow!("execution cancelled"))
}
sandbox::error::ExecutionError::MountError { .. } => {
Self::Other(anyhow::anyhow!(e.to_string()))
}
sandbox::error::ExecutionError::NetworkIsolationUnavailable => {
Self::Other(anyhow::anyhow!(e.to_string()))
}
},
sandbox::Error::Output(e) => Self::Other(e.into()),
sandbox::Error::MappedFile(p) => Self::Other(anyhow::anyhow!(
"internal: file {} mapped to rootfs",
p.display()
)),
sandbox::Error::Network(e) => Self::Other(anyhow::anyhow!(e.to_string())),
}
}
}
impl From<common::HardlinkError> for Error {
fn from(value: common::HardlinkError) -> Self {
match value {
common::HardlinkError::IO(s, p, e) => Self::IO(s, p, e),
common::HardlinkError::HardlinkFailed(from, _to, e) => {
Self::IO("hardlinking failed", from, e)
}
}
}
}
impl From<rcache::Error<common::fetchers::AnyRespError>> for Error {
fn from(value: rcache::Error<common::fetchers::AnyRespError>) -> Self {
Self::Other(rcache_cause(value))
}
}
/// Renders an `rcache::Error` as a user-facing cause.
fn rcache_cause(value: rcache::Error<common::fetchers::AnyRespError>) -> anyhow::Error {
// The two arms are NOT interchangeable, though they look it:
// `rcache::Error`'s `Display` is `write!(f, "{:?}", self)` — it
// Debug-formats itself — so the fallback arm renders a `Config` as
// `Config("MINIMAL_INDEX_SOURCE: unknown index source \"banana\" ...")`,
// variant name and escaped quotes included. Destructuring `Config` and
// formatting the inner `msg` is what yields the clean, user-facing
// message; collapsing this to one arm reintroduces the panic-era output
// it replaced.
match value {
rcache::Error::Config(msg) => anyhow::anyhow!("{msg}"),
other => anyhow::anyhow!("{other}"),
}
}
/// The error for a failed remote artifact cache setup: the rcache cause under
/// a fixed context line, with `hint` in parentheses when the caller's user
/// has a switch to name. Render it with `{:#}` to keep the cause.
pub fn remote_cache_setup_error(
e: rcache::Error<common::fetchers::AnyRespError>,
hint: Option<&str>,
) -> anyhow::Error {
let cause = rcache_cause(e);
match hint {
Some(hint) => cause.context(format!(
"failed to set up the remote artifact cache ({hint})"
)),
None => cause.context("failed to set up the remote artifact cache"),
}
}
impl From<mfile::Error> for Error {
fn from(e: mfile::Error) -> Self {
Error::MFile(e)
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A missing minimal file renders with a single `minimal.toml:` prefix.
/// The boundary supplies the filename here, so `mfile`'s `NotFound` must
/// not carry it too, or the message reads `minimal.toml: minimal.toml not
/// found`.
#[test]
fn mfile_not_found_display_is_not_doubled() {
assert_eq!(
Error::MFile(mfile::Error::NotFound).to_string(),
"minimal.toml: not found",
);
}
/// A minimal file that does not parse prints `invalid TOML` and the TOML
/// parse error once each under `{:#}`, with the snippet.
#[test]
<
6D81
div>
fn mfile_format_error_prints_toml_error_once() {
let error = mfile::entry::read_entries(b"[boxes.dev\ntype = \"session\"\n")
.expect_err("the file does not parse");
assert!(matches!(error, mfile::Error::Format(_)), "{error:?}");
// `Error` is not `Send`, so anyhow cannot hold it. Walk the chain the
// way anyhow's `{:#}` does.
let error = Error::MFile(error);
let mut printed = error.to_string();
let mut cause = std::error::Error::source(&error);
while let Some(e) = cause {
printed.push_str(&format!(": {e}"));
cause = e.source();
}
assert!(
printed.starts_with("minimal.toml: invalid TOML: TOML parse error"),
"{printed}"
);
assert_eq!(printed.matches("invalid TOML").count(), 1, "{printed}");
assert_eq!(printed.matches("TOML parse error").count(), 1, "{printed}");
assert_eq!(printed.matches("[boxes.dev").count(), 1, "{printed}");
}
/// An unreadable minimal file prints its io error once under `{:#}`.
#[test]
fn mfile_io_error_prints_io_error_once() {
let io = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "denied");
let error = Error::MFile(mfile::Error::IO("minimal file", "p".into(), io));
let mut printed = error.to_string();
let mut cause = std::error::Error::source(&error);
while let Some(e) = cause {
printed.push_str(&format!(": {e}"));
cause = e.source();
}
assert_eq!(printed.matches("denied").count(), 1, "{printed}");
}
/// A remote cache setup failure keeps its cause under `{:#}`, rendered
/// from rcache's `Config` message rather than its Debug form.
#[test]
fn remote_cache_setup_error_keeps_clean_cause() {
let err = remote_cache_setup_error(rcache::Error::Config("bad url".into()), None);
assert_eq!(
format!("{err:#}"),
"failed to set up the remote artifact cache: bad url",
);
}
/// The caller's hint lands in parentheses on the context line.
#[test]
fn remote_cache_setup_error_carries_hint() {
let err = remote_cache_setup_error(
rcache::Error::Config("bad url".into()),
Some("pass --no-fetch to build without it"),
);
assert_eq!(
format!("{err:#}"),
"failed to set up the remote artifact cache \
(pass --no-fetch to build without it): bad url",
);
}
}