Skip to main content

flow_toolkit_rust/
error.rs

1//! Why a command of the toolkit failed: each case carries the fact that went
2//! wrong, and what Cargo, the launcher or the system said, as their own.
3
4use flow_toolkit::cli::UsageError;
5use std::path::{Path, PathBuf};
6
7use crate::COMMAND;
8use crate::new::slashed;
9
10/// Why the command failed. Every refusal, a missing Rust toolchain included,
11/// exits with status 2 and says why on standard error.
12#[derive(Debug)]
13#[expect(
14    clippy::exhaustive_enums,
15    reason = "the command fails in these ways, and a caller handles each"
16)]
17pub enum PrepareError {
18    /// The command line is not one the toolkit takes.
19    Usage(UsageError),
20    /// `new` refuses the directory it was given.
21    New(NewError),
22    /// The file or directory at `path` could not be read, written, found
23    /// or locked.
24    Io {
25        /// The path.
26        path: PathBuf,
27        /// What the system said.
28        error: std::io::Error,
29    },
30    /// The file at `from` could not be copied to `to`.
31    Copy {
32        /// The file copied.
33        from: PathBuf,
34        /// Where it was going.
35        to: PathBuf,
36        /// What the system said.
37        error: std::io::Error,
38    },
39    /// A path the toolkit writes into a Cargo manifest, a cache file or a
40    /// depfile is not one line of UTF-8.
41    Unwritable {
42        /// The path.
43        path: PathBuf,
44    },
45    /// The library is not one the toolkit can build, at `at`: its manifest,
46    /// a lock, a source, or what its build wrote.
47    Library {
48        /// Where.
49        at: Place,
50        /// What is wrong there.
51        problem: LibraryProblem,
52    },
53    /// Cargo could not be started; a missing Rust toolchain is
54    /// [`std::io::ErrorKind::NotFound`].
55    NoCargo(std::io::Error),
56    /// A Cargo command failed.
57    Cargo {
58        /// Which command.
59        step: CargoStep,
60        /// How Cargo exited.
61        status: std::process::ExitStatus,
62        /// What Cargo wrote on standard error, when the toolkit kept it: a
63        /// build's diagnostics reach standard error as Cargo writes them.
64        said: String,
65    },
66    /// What Cargo reported is not what the toolkit reads from it.
67    CargoOutput(CargoOutput),
68    /// The library's inputs changed while it was built or exported, so the
69    /// launcher may not be what they build; building again picks them up.
70    Changed {
71        /// The files that changed; none when what changed is the build's
72        /// environment or Cargo configuration, or is not known.
73        inputs: Vec<PathBuf>,
74    },
75    /// The launcher at `launcher` could not be started.
76    Launch {
77        /// The launcher.
78        launcher: PathBuf,
79        /// What the system said.
80        error: std::io::Error,
81    },
82    /// The built launcher refused to extract the library's contract.
83    Extract {
84        /// The launcher.
85        launcher: PathBuf,
86        /// How it exited.
87        status: std::process::ExitStatus,
88        /// What it wrote on standard error.
89        said: String,
90    },
91    /// The host's contract file at `path` is not one this toolkit reads.
92    Contract {
93        /// The contract file.
94        path: PathBuf,
95        /// Why it does not read.
96        error: flow_abi::ListingError,
97    },
98    /// Standard output could not be written.
99    Output(std::io::Error),
100    /// Neither `XDG_CACHE_HOME` nor the platform's own cache directory is
101    /// set to an absolute path, so the toolkit has nowhere to build.
102    NoCacheHome,
103    /// The running toolkit could not find its own executable.
104    CurrentExe(std::io::Error),
105    /// This build of the toolkit carries no `Cargo.lock` for `new` to start
106    /// a library's lock from.
107    NoCarriedLock,
108}
109
110/// The Cargo command that failed.
111#[derive(Clone, Copy, PartialEq, Eq, Debug)]
112#[expect(
113    clippy::exhaustive_enums,
114    reason = "the toolkit runs these Cargo commands, and a caller handles each"
115)]
116pub enum CargoStep {
117    /// `cargo tree`, locking a new library from the carried lock.
118    Lock,
119    /// `cargo metadata --locked`, resolving the library against its
120    /// workspace's lock.
121    Metadata,
122    /// `cargo build`, compiling the launcher.
123    Build,
124}
125
126/// `new` refuses the directory it was given.
127#[derive(Clone, PartialEq, Eq, Debug)]
128#[expect(
129    clippy::exhaustive_enums,
130    reason = "`new` refuses a directory in these ways, and a caller handles each"
131)]
132pub enum NewError {
133    /// The directory that would hold the library is none; `new` creates
134    /// no directory above it.
135    NoParent(PathBuf),
136    /// Something is at the path already, other than an empty directory.
137    Taken(PathBuf),
138    /// The directory's name is no crate name: ASCII letters, digits, `-` and
139    /// `_`, starting with a letter.
140    CrateName(PathBuf),
141    /// The crate name, as Cargo spells it, is one Rust or Cargo keeps for
142    /// itself.
143    Reserved(String),
144}
145
146/// What is wrong with a file of the library, or of its build.
147#[derive(Clone, Debug)]
148#[expect(
149    clippy::exhaustive_enums,
150    reason = "the toolkit refuses a library in these ways, and a caller handles each"
151)]
152pub enum LibraryProblem {
153    /// A TOML file, a manifest or a lock, does not parse.
154    Toml(Box<toml::de::Error>),
155    /// A lock's `package` is not a list.
156    PackagesNotList,
157    /// A package of a lock has no name or version.
158    UnnamedLockEntry,
159    /// The library's launcher resolves a package the workspace's lock does
160    /// not lock at the same version, source and checksum.
161    Unlocked {
162        /// The package's name.
163        name: String,
164        /// Its version.
165        version: String,
166        /// Its source.
167        source: String,
168    },
169    /// The library's workspace has no `Cargo.lock`.
170    NoLock,
171    /// The library's root has no `Cargo.toml`.
172    NoManifest,
173    /// The manifest is a virtual workspace's.
174    VirtualWorkspace,
175    /// The manifest has no `[package]` with a name.
176    NoPackage,
177    /// The library target's source, `src/lib.rs` or `[lib].path`, is no
178    /// file.
179    NoLibraryTarget,
180    /// The library's directory has no UTF-8 name, which names its exported
181    /// launcher.
182    DirectoryName,
183    /// A file shares no root with the library at `root`.
184    NoSharedRoot {
185        /// The library's root.
186        root: PathBuf,
187    },
188    /// The library depends on no `flow-toolkit` crate, and the running
189    /// toolkit, at `executable`, lies in no installation holding its
190    /// sources.
191    NoToolkit {
192        /// The running toolkit.
193        executable: PathBuf,
194    },
195    /// The launcher's path in the cache is not absolute.
196    RelativeLauncher,
197    /// The launcher wrote no contract in the value encoding.
198    NotAContract(flow_abi::DecodeError),
199    /// A contract module's path is no module path.
200    ModulePath(flow_types::SegmentsError),
201    /// The library has no public `#[tool]` function.
202    NoTools,
203    /// A `#[tool]` function is conditional.
204    ConditionalTool,
205    /// A `#[lifespan]` function is conditional.
206    ConditionalLifespan,
207    /// The library has a second `#[lifespan]` function.
208    SecondLifespan,
209    /// A public module holding Tools is conditional or has a `#[path]`.
210    ModuleAttributes,
211    /// A public module holding Tools is named `name`, which is no Flow
212    /// lowercase name.
213    ModuleName {
214        /// The module's name.
215        name: String,
216    },
217    /// A source file lies outside the library's root.
218    OutsideRoot,
219    /// A source file does not parse as Rust.
220    Syntax(Box<syn::Error>),
221}
222
223/// What Cargo reported that the toolkit does not read.
224#[derive(Clone, Debug)]
225#[expect(
226    clippy::exhaustive_enums,
227    reason = "the toolkit refuses Cargo's output in these ways, and a caller handles each"
228)]
229pub enum CargoOutput {
230    /// Cargo's output is not UTF-8.
231    NotUtf8(std::str::Utf8Error),
232    /// A line of `cargo build`'s messages is not JSON.
233    BuildMessage(flow_toolkit::DecodeError),
234    /// `cargo build` reported more than one launcher executable.
235    Launchers,
236    /// `cargo build` reported no launcher executable.
237    NoLauncher,
238    /// Cargo's dependency information at `file` names no target.
239    DependencyTarget {
240        /// The dependency information.
241        file: PathBuf,
242    },
243    /// `cargo metadata`'s output is not JSON.
244    Metadata(flow_toolkit::DecodeError),
245    /// A row of `cargo metadata` has no text at `key`.
246    NoKey {
247        /// The key.
248        key: MetadataKey,
249    },
250    /// Two rows of `cargo metadata` share the ID `id`.
251    DuplicateId {
252        /// The ID.
253        id: String,
254    },
255    /// `cargo metadata` has no `packages`.
256    NoPackages,
257    /// `cargo metadata` has no resolved dependency graph.
258    NoResolve,
259    /// `cargo metadata` has no package for the library's manifest.
260    NoSelected,
261    /// `cargo metadata` has no package with the ID `id`.
262    NoPackage {
263        /// The ID.
264        id: String,
265    },
266    /// `cargo metadata`'s graph has no node with the ID `id`.
267    NoNode {
268        /// The ID.
269        id: String,
270    },
271    /// The node with the ID `id` has no `deps`.
272    NoDependencies {
273        /// The ID.
274        id: String,
275    },
276    /// A dependency has no `dep_kinds`.
277    NoKinds,
278    /// A dependency's kind is none of normal, build and dev.
279    DependencyKind {
280        /// The kind, as Cargo wrote it.
281        kind: String,
282    },
283    /// A package's manifest, at `manifest`, lies in no directory.
284    NoRoot {
285        /// The manifest.
286        manifest: PathBuf,
287    },
288    /// The library resolves more than one `flow-toolkit` package.
289    Toolkits,
290    /// The toolkit's package has no source.
291    NoToolkitSource,
292    /// The toolkit's source is neither a path, a registry nor Git.
293    ToolkitSource {
294        /// The source.
295        source: String,
296    },
297    /// The toolkit's Git source has no commit identity.
298    GitCommit {
299        /// The source.
300        source: String,
301    },
302    /// The toolkit's Git source names a reference with no value.
303    GitReference {
304        /// The source.
305        source: String,
306    },
307    /// The toolkit's Git source names a reference that is no branch, tag or
308    /// rev.
309    GitReferenceKind {
310        /// The kind.
311        kind: String,
312    },
313    /// `cargo metadata` names no workspace root.
314    NoWorkspaceRoot,
315}
316
317/// A key of a row of `cargo metadata` the toolkit reads.
318#[derive(Clone, Copy, PartialEq, Eq, Debug)]
319#[expect(
320    clippy::exhaustive_enums,
321    reason = "the toolkit reads these keys, and a caller handles each"
322)]
323pub enum MetadataKey {
324    /// A package's or a node's `id`.
325    Id,
326    /// A package's `name`.
327    Name,
328    /// A package's `version`.
329    Version,
330    /// A package's `manifest_path`.
331    ManifestPath,
332    /// A dependency's `pkg`.
333    Pkg,
334}
335
336impl MetadataKey {
337    /// The key as Cargo writes it.
338    #[must_use]
339    pub const fn name(self) -> &'static str {
340        match self {
341            MetadataKey::Id => "id",
342            MetadataKey::Name => "name",
343            MetadataKey::Version => "version",
344            MetadataKey::ManifestPath => "manifest_path",
345            MetadataKey::Pkg => "pkg",
346        }
347    }
348}
349
350/// A place in a file: the file, and the line and column where known.
351#[derive(Clone, PartialEq, Eq, Debug)]
352pub struct Place {
353    /// The file.
354    pub file: PathBuf,
355    /// The line and column, each counted from 1.
356    pub at: Option<(usize, usize)>,
357}
358
359impl Place {
360    /// The whole of `file`.
361    pub(crate) fn file(file: &Path) -> Self {
362        Self {
363            file: file.to_owned(),
364            at: None,
365        }
366    }
367
368    /// Where `span` starts in `file`.
369    pub(crate) fn span(file: &Path, span: proc_macro2::Span) -> Self {
370        let start = span.start();
371        Self {
372            file: file.to_owned(),
373            at: Some((start.line, start.column + 1)),
374        }
375    }
376}
377
378impl std::fmt::Display for Place {
379    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
380        write!(formatter, "{}", self.file.display())?;
381        if let Some((line, column)) = self.at {
382            write!(formatter, ":{line}:{column}")?;
383        }
384        Ok(())
385    }
386}
387
388impl PrepareError {
389    /// `problem` with the library at `at`.
390    pub(crate) fn library(at: Place, problem: LibraryProblem) -> Self {
391        PrepareError::Library { at, problem }
392    }
393
394    /// `problem` with the library's file `file`.
395    pub(crate) fn in_file(file: &Path, problem: LibraryProblem) -> Self {
396        Self::library(Place::file(file), problem)
397    }
398}
399
400impl From<CargoOutput> for PrepareError {
401    fn from(output: CargoOutput) -> Self {
402        PrepareError::CargoOutput(output)
403    }
404}
405
406impl std::fmt::Display for PrepareError {
407    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408        match self {
409            PrepareError::Usage(error) => write!(formatter, "{error}"),
410            PrepareError::New(error) => write!(formatter, "{error}"),
411            PrepareError::Io { path, error } => write!(formatter, "{}: {error}", path.display()),
412            PrepareError::Copy { from, to, error } => {
413                write!(formatter, "{} -> {}: {error}", from.display(), to.display())
414            }
415            PrepareError::Unwritable { path } => write!(
416                formatter,
417                "{}: the path is not one line of UTF-8, which the toolkit needs to write it",
418                path.display()
419            ),
420            PrepareError::Library { at, problem } => write!(formatter, "{at}: {problem}"),
421            PrepareError::NoCargo(error) if error.kind() == std::io::ErrorKind::NotFound => {
422                formatter.write_str(
423                    "cargo was not found on PATH: building a Rust library needs the Rust toolchain",
424                )
425            }
426            PrepareError::NoCargo(error) => write!(formatter, "cargo could not start: {error}"),
427            PrepareError::Cargo {
428                step: CargoStep::Build,
429                status,
430                ..
431            } => write!(formatter, "Rust tool compilation failed with {status}"),
432            PrepareError::Cargo {
433                step: CargoStep::Lock,
434                status,
435                said,
436            } => write!(formatter, "cargo failed with {status}: {said}"),
437            PrepareError::Cargo {
438                step: CargoStep::Metadata,
439                status,
440                said,
441            } => write!(
442                formatter,
443                "cargo failed with {status}: {said}\nthe Rust toolkit resolves a library against its workspace's Cargo.lock as it is and never writes it: update the lock in the library's workspace (cargo generate-lockfile where there is none) and try again"
444            ),
445            PrepareError::CargoOutput(output) => write!(formatter, "{output}"),
446            PrepareError::Changed { inputs } if inputs.is_empty() => formatter.write_str(
447                "Rust tool inputs changed while the launcher was prepared (its build environment, Cargo configuration or sources); run the build again",
448            ),
449            PrepareError::Changed { inputs } => write!(
450                formatter,
451                "Rust tool inputs changed during the build: {}; run it again",
452                inputs
453                    .iter()
454                    .map(|path| path.display().to_string())
455                    .collect::<Vec<_>>()
456                    .join(", ")
457            ),
458            PrepareError::Launch { launcher, error } => write!(
459                formatter,
460                "the Rust Tool launcher {} could not start: {error}; a launcher built for another target needs a native Cargo build target",
461                launcher.display()
462            ),
463            PrepareError::Extract { said, .. } if !said.is_empty() => formatter.write_str(said),
464            PrepareError::Extract {
465                launcher, status, ..
466            } => write!(
467                formatter,
468                "the Rust Tool launcher {} did not extract the contract: {status}",
469                launcher.display()
470            ),
471            PrepareError::Contract { path, error } => {
472                write!(formatter, "{}: {error}", path.display())
473            }
474            PrepareError::Output(error) => write!(formatter, "standard output: {error}"),
475            PrepareError::NoCacheHome => write!(
476                formatter,
477                "{COMMAND} keeps its builds in the platform's cache directory, and none is known: set XDG_CACHE_HOME or HOME"
478            ),
479            PrepareError::CurrentExe(error) => {
480                write!(formatter, "the running toolkit's own path: {error}")
481            }
482            PrepareError::NoCarriedLock => write!(
483                formatter,
484                "this build of {COMMAND} carries no Cargo.lock to start a library's lock from, so {COMMAND} new makes none; use {COMMAND} built from a Flow release, its repository or its published crate"
485            ),
486        }
487    }
488}
489
490impl std::error::Error for PrepareError {}
491
492impl std::fmt::Display for NewError {
493    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
494        match self {
495            NewError::NoParent(parent) => write!(
496                formatter,
497                "{} is not a directory, and {COMMAND} new creates none above the library",
498                slashed(parent)
499            ),
500            NewError::Taken(path) => write!(
501                formatter,
502                "{} exists: {COMMAND} new writes a library where nothing is, or into an empty directory",
503                slashed(path)
504            ),
505            NewError::CrateName(path) => write!(
506                formatter,
507                "a library's directory names its crate, so its name is ASCII letters, digits, - and _, starting with a letter; {} is not",
508                path.display()
509            ),
510            NewError::Reserved(name) => write!(
511                formatter,
512                "{name} is a name Rust keeps for itself, so it cannot name the library; pick another, such as {name}_tools"
513            ),
514        }
515    }
516}
517
518impl std::fmt::Display for LibraryProblem {
519    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
520        match self {
521            LibraryProblem::Toml(error) => write!(formatter, "{error}"),
522            LibraryProblem::PackagesNotList => formatter.write_str("`package` is not a list"),
523            LibraryProblem::UnnamedLockEntry => {
524                formatter.write_str("a package has no name or version")
525            }
526            LibraryProblem::Unlocked {
527                name,
528                version,
529                source,
530            } => write!(
531                formatter,
532                "the library's launcher resolves {name} {version} from {source}, which this lock does not lock; update the workspace's lock and build again"
533            ),
534            LibraryProblem::NoLock => formatter.write_str(
535                "no Cargo.lock in its workspace; a launcher is built against its workspace's lock",
536            ),
537            LibraryProblem::NoManifest => formatter.write_str(
538                "no Cargo.toml; a Rust library's root is the root of its Cargo package",
539            ),
540            LibraryProblem::VirtualWorkspace => formatter.write_str(
541                "a virtual workspace is no library; a Rust library's root is a Cargo package",
542            ),
543            LibraryProblem::NoPackage => {
544                formatter.write_str("Rust tools need a Cargo package with a library target")
545            }
546            LibraryProblem::NoLibraryTarget => formatter
547                .write_str("Rust tools need src/lib.rs or [lib].path, without a handwritten main"),
548            LibraryProblem::DirectoryName => {
549                formatter.write_str("the library directory has no UTF-8 name")
550            }
551            LibraryProblem::NoSharedRoot { root } => write!(
552                formatter,
553                "shares no root with the library at {}",
554                root.display()
555            ),
556            LibraryProblem::NoToolkit { executable } => write!(
557                formatter,
558                "the library depends on no flow-toolkit crate and {} lies in no installation holding the toolkit's sources; add flow-toolkit to the library's dependencies",
559                executable.display()
560            ),
561            LibraryProblem::RelativeLauncher => {
562                formatter.write_str("the launcher's recorded path is not absolute")
563            }
564            LibraryProblem::NotAContract(error) => {
565                write!(formatter, "it is not a contract in the value encoding: {error}")
566            }
567            LibraryProblem::ModulePath(error) => write!(formatter, "{error}"),
568            LibraryProblem::NoTools => {
569                formatter.write_str("no public #[tool] functions found in the Rust library")
570            }
571            LibraryProblem::ConditionalTool => formatter.write_str(
572                "conditional #[tool] exports are unsupported; use an unconditional public tool function",
573            ),
574            LibraryProblem::ConditionalLifespan => {
575                formatter.write_str("conditional #[lifespan] exports are unsupported")
576            }
577            LibraryProblem::SecondLifespan => formatter
578                .write_str("a Rust library may export at most one #[lifespan] initializer"),
579            LibraryProblem::ModuleAttributes => formatter
580                .write_str("conditional or #[path] exported tool modules are unsupported"),
581            LibraryProblem::ModuleName { name } => write!(
582                formatter,
583                "the module `{name}` is not a Flow lowercase name, so its Tools have no contract module path; rename it"
584            ),
585            LibraryProblem::OutsideRoot => {
586                formatter.write_str("the source lies outside the library root")
587            }
588            LibraryProblem::Syntax(error) => write!(formatter, "{error}"),
589        }
590    }
591}
592
593impl std::fmt::Display for CargoOutput {
594    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
595        match self {
596            CargoOutput::NotUtf8(error) => write!(formatter, "{error}"),
597            CargoOutput::BuildMessage(error) => {
598                write!(formatter, "invalid Cargo build message: {error}")
599            }
600            CargoOutput::Launchers => formatter.write_str("Cargo reported multiple launcher artifacts"),
601            CargoOutput::NoLauncher => formatter.write_str(
602                "Cargo did not report a native launcher executable; check its build target and profile",
603            ),
604            CargoOutput::DependencyTarget { file } => write!(
605                formatter,
606                "{}: Cargo's dependency information names no target",
607                file.display()
608            ),
609            CargoOutput::Metadata(error) => write!(formatter, "{error}"),
610            CargoOutput::NoKey { key } => {
611                write!(formatter, "Cargo metadata needs {}", key.name())
612            }
613            CargoOutput::DuplicateId { id } => {
614                write!(formatter, "duplicate Cargo metadata package ID: {id}")
615            }
616            CargoOutput::NoPackages => formatter.write_str("Cargo metadata has no packages"),
617            CargoOutput::NoResolve => {
618                formatter.write_str("Cargo metadata has no resolved dependency graph")
619            }
620            CargoOutput::NoSelected => {
621                formatter.write_str("Cargo metadata does not contain the selected native package")
622            }
623            CargoOutput::NoPackage { id } => {
624                write!(formatter, "Cargo dependency package is missing: {id}")
625            }
626            CargoOutput::NoNode { id } => write!(formatter, "Cargo dependency node is missing: {id}"),
627            CargoOutput::NoDependencies { id } => {
628                write!(formatter, "Cargo dependency node has no deps: {id}")
629            }
630            CargoOutput::NoKinds => formatter.write_str("Cargo dependency has no kind information"),
631            CargoOutput::DependencyKind { kind } => {
632                write!(formatter, "Cargo dependency kind is unsupported: {kind}")
633            }
634            CargoOutput::NoRoot { manifest } => write!(
635                formatter,
636                "Cargo package manifest {} has no parent",
637                manifest.display()
638            ),
639            CargoOutput::Toolkits => {
640                formatter.write_str("native package resolves multiple Flow toolkit identities")
641            }
642            CargoOutput::NoToolkitSource => formatter.write_str("Cargo toolkit source is missing"),
643            CargoOutput::ToolkitSource { source } => {
644                write!(formatter, "Cargo toolkit source is unsupported: {source}")
645            }
646            CargoOutput::GitCommit { source } => {
647                write!(formatter, "Cargo Git source has no commit identity: {source}")
648            }
649            CargoOutput::GitReference { source } => {
650                write!(formatter, "Cargo Git source has no reference value: {source}")
651            }
652            CargoOutput::GitReferenceKind { kind } => {
653                write!(formatter, "Cargo Git reference kind is unsupported: {kind}")
654            }
655            CargoOutput::NoWorkspaceRoot => {
656                formatter.write_str("Cargo metadata names no workspace root")
657            }
658        }
659    }
660}