1use flow_toolkit::cli::UsageError;
5use std::path::{Path, PathBuf};
6
7use crate::COMMAND;
8use crate::new::slashed;
9
10#[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 Usage(UsageError),
20 New(NewError),
22 Io {
25 path: PathBuf,
27 error: std::io::Error,
29 },
30 Copy {
32 from: PathBuf,
34 to: PathBuf,
36 error: std::io::Error,
38 },
39 Unwritable {
42 path: PathBuf,
44 },
45 Library {
48 at: Place,
50 problem: LibraryProblem,
52 },
53 NoCargo(std::io::Error),
56 Cargo {
58 step: CargoStep,
60 status: std::process::ExitStatus,
62 said: String,
65 },
66 CargoOutput(CargoOutput),
68 Changed {
71 inputs: Vec<PathBuf>,
74 },
75 Launch {
77 launcher: PathBuf,
79 error: std::io::Error,
81 },
82 Extract {
84 launcher: PathBuf,
86 status: std::process::ExitStatus,
88 said: String,
90 },
91 Contract {
93 path: PathBuf,
95 error: flow_abi::ListingError,
97 },
98 Output(std::io::Error),
100 NoCacheHome,
103 CurrentExe(std::io::Error),
105 NoCarriedLock,
108}
109
110#[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 Lock,
119 Metadata,
122 Build,
124}
125
126#[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 NoParent(PathBuf),
136 Taken(PathBuf),
138 CrateName(PathBuf),
141 Reserved(String),
144}
145
146#[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 Toml(Box<toml::de::Error>),
155 PackagesNotList,
157 UnnamedLockEntry,
159 Unlocked {
162 name: String,
164 version: String,
166 source: String,
168 },
169 NoLock,
171 NoManifest,
173 VirtualWorkspace,
175 NoPackage,
177 NoLibraryTarget,
180 DirectoryName,
183 NoSharedRoot {
185 root: PathBuf,
187 },
188 NoToolkit {
192 executable: PathBuf,
194 },
195 RelativeLauncher,
197 NotAContract(flow_abi::DecodeError),
199 ModulePath(flow_types::SegmentsError),
201 NoTools,
203 ConditionalTool,
205 ConditionalLifespan,
207 SecondLifespan,
209 ModuleAttributes,
211 ModuleName {
214 name: String,
216 },
217 OutsideRoot,
219 Syntax(Box<syn::Error>),
221}
222
223#[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 NotUtf8(std::str::Utf8Error),
232 BuildMessage(flow_toolkit::DecodeError),
234 Launchers,
236 NoLauncher,
238 DependencyTarget {
240 file: PathBuf,
242 },
243 Metadata(flow_toolkit::DecodeError),
245 NoKey {
247 key: MetadataKey,
249 },
250 DuplicateId {
252 id: String,
254 },
255 NoPackages,
257 NoResolve,
259 NoSelected,
261 NoPackage {
263 id: String,
265 },
266 NoNode {
268 id: String,
270 },
271 NoDependencies {
273 id: String,
275 },
276 NoKinds,
278 DependencyKind {
280 kind: String,
282 },
283 NoRoot {
285 manifest: PathBuf,
287 },
288 Toolkits,
290 NoToolkitSource,
292 ToolkitSource {
294 source: String,
296 },
297 GitCommit {
299 source: String,
301 },
302 GitReference {
304 source: String,
306 },
307 GitReferenceKind {
310 kind: String,
312 },
313 NoWorkspaceRoot,
315}
316
317#[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 Id,
326 Name,
328 Version,
330 ManifestPath,
332 Pkg,
334}
335
336impl MetadataKey {
337 #[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#[derive(Clone, PartialEq, Eq, Debug)]
352pub struct Place {
353 pub file: PathBuf,
355 pub at: Option<(usize, usize)>,
357}
358
359impl Place {
360 pub(crate) fn file(file: &Path) -> Self {
362 Self {
363 file: file.to_owned(),
364 at: None,
365 }
366 }
367
368 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 pub(crate) fn library(at: Place, problem: LibraryProblem) -> Self {
391 PrepareError::Library { at, problem }
392 }
393
394 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}