use core::fmt;
use std::io;
use std::path::PathBuf;
use std::time::Duration;
use super::child::{ChildFailure, Reach, DEADLINE_VAR};
use crate::plan::WorkspaceError;
#[derive(Debug)]
pub enum DiscoverError {
CargoMetadata {
status: Option<i32>,
message: String,
},
CargoNotRunnable {
source: io::Error,
},
PnpmList {
status: Option<i32>,
message: String,
},
PnpmRoot {
status: Option<i32>,
message: String,
},
PnpmNotRunnable {
source: io::Error,
},
ChildDeadline {
tool: &'static str,
limit: Duration,
reach: Reach,
},
ChildStalled {
tool: &'static str,
limit: Duration,
},
ChildIo {
tool: &'static str,
message: String,
},
BadDeadline(String),
InvalidMetadata {
message: String,
},
PnpmVersion {
message: String,
},
WorkspaceRootOutsideRepository {
workspace_root: PathBuf,
repository_root: PathBuf,
},
Io {
path: PathBuf,
source: io::Error,
},
Json(serde_json::Error),
Toml {
path: PathBuf,
message: String,
},
Version {
package: String,
message: String,
},
Range {
package: String,
dependency: String,
message: String,
},
UnresolvedCatalog {
package: String,
dependency: String,
catalog_name: Option<String>,
path: Option<PathBuf>,
},
UnknownDependencyKind {
package: String,
dependency: String,
kind: String,
},
Workspace(WorkspaceError),
}
impl fmt::Display for DiscoverError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::CargoMetadata { status, message } => match status {
Some(code) => write!(f, "cargo metadata exited {code}: {message}"),
None => write!(f, "cargo metadata failed: {message}"),
},
Self::CargoNotRunnable { source } => write!(f, "could not run cargo: {source}"),
Self::PnpmList { status, message } => match status {
Some(code) => write!(f, "pnpm list exited {code}: {message}"),
None => write!(f, "pnpm list failed: {message}"),
},
Self::PnpmRoot { status, message } => match status {
Some(code) => write!(f, "pnpm root -w exited {code}: {message}"),
None => write!(f, "pnpm root -w failed: {message}"),
},
Self::PnpmNotRunnable { source } => write!(f, "could not run pnpm: {source}"),
Self::ChildDeadline { tool, limit, reach } => write!(
f,
"`{tool}` gave no answer within {}s, so oakum {}; a file it reads may be a FIFO or a lock it waits on. Set {DEADLINE_VAR} (seconds) if it is legitimately slow",
limit.as_secs(),
reach.describe("it")
),
Self::ChildStalled { tool, limit } => write!(
f,
"`{tool}` exited but something it spawned still held its output open {}s later and may still be running, so its answer could not be collected. Set {DEADLINE_VAR} (seconds) to wait longer",
limit.as_secs()
),
Self::ChildIo { tool, message } => write!(f, "`{tool}` ran but {message}"),
Self::BadDeadline(message) => f.write_str(message),
Self::InvalidMetadata { message } => write!(f, "discovery metadata: {message}"),
Self::PnpmVersion { message } => write!(f, "`pnpm --version` {message}"),
Self::WorkspaceRootOutsideRepository {
workspace_root,
repository_root,
} => write!(
f,
"workspace root {} is outside repository {}",
workspace_root.display(),
repository_root.display()
),
Self::Io { path, source } => write!(f, "read {}: {source}", path.display()),
Self::Json(err) => write!(f, "discovery JSON: {err}"),
Self::Toml { path, message } => {
write!(f, "parse {}: {message}", path.display())
}
Self::Version { package, message } => {
write!(f, "package {package}: {message}")
}
Self::Range {
package,
dependency,
message,
} => write!(f, "{package} dependency on {dependency}: {message}"),
Self::UnresolvedCatalog {
package,
dependency,
catalog_name,
path,
} => {
let protocol = match catalog_name {
None => String::from("catalog:"),
Some(catalog) => format!("catalog:{catalog}"),
};
match path {
Some(path) => write!(
f,
"{package} dependency on {dependency}: unresolved catalog protocol {protocol} in {}",
path.display()
),
None => write!(
f,
"{package} dependency on {dependency}: unresolved catalog protocol {protocol} (no pnpm-workspace.yaml found)"
),
}
}
Self::UnknownDependencyKind {
package,
dependency,
kind,
} => write!(
f,
"{package} dependency on {dependency}: unknown kind {kind:?}"
),
Self::Workspace(err) => write!(f, "{err}"),
}
}
}
impl DiscoverError {
#[must_use]
pub fn is_unverified(&self) -> bool {
matches!(
self,
Self::ChildDeadline { .. }
| Self::ChildStalled { .. }
| Self::ChildIo { .. }
| Self::BadDeadline(_)
)
}
}
impl DiscoverError {
pub(super) fn from_child(
tool: &'static str,
failure: ChildFailure,
not_runnable: fn(io::Error) -> Self,
) -> Self {
Self::unanswered(tool, failure).unwrap_or_else(not_runnable)
}
pub fn unanswered(tool: &'static str, failure: ChildFailure) -> Result<Self, io::Error> {
Ok(match failure {
ChildFailure::Spawn(err) => return Err(err),
ChildFailure::Deadline { limit, reach } => Self::ChildDeadline { tool, limit, reach },
ChildFailure::DrainStalled { limit, .. } => Self::ChildStalled { tool, limit },
ChildFailure::Wait(err, reach) => Self::ChildIo {
tool,
message: format!(
"waiting on it failed ({err}); oakum {}",
reach.describe("it")
),
},
ChildFailure::Read(err) => Self::ChildIo {
tool,
message: format!("its output could not be read: {err}"),
},
})
}
}
impl std::error::Error for DiscoverError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::CargoNotRunnable { source }
| Self::PnpmNotRunnable { source }
| Self::Io { source, .. } => Some(source),
Self::Json(err) => Some(err),
Self::Workspace(err) => Some(err),
_ => None,
}
}
}
impl From<WorkspaceError> for DiscoverError {
fn from(value: WorkspaceError) -> Self {
Self::Workspace(value)
}
}
impl From<serde_json::Error> for DiscoverError {
fn from(value: serde_json::Error) -> Self {
Self::Json(value)
}
}
#[cfg(test)]
mod tests {
use std::io;
use std::time::Duration;
use super::{ChildFailure, DiscoverError, Reach};
fn exit_status() -> std::process::ExitStatus {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
std::process::ExitStatus::from_raw(0)
}
#[cfg(windows)]
{
use std::os::windows::process::ExitStatusExt;
std::process::ExitStatus::from_raw(0)
}
}
#[test]
fn each_child_failure_keeps_its_class() {
let limit = Duration::from_secs(2);
let not_runnable = |source| DiscoverError::CargoNotRunnable { source };
let classify = |failure| DiscoverError::from_child("cargo metadata", failure, not_runnable);
let spawned = classify(ChildFailure::Spawn(io::Error::other("missing")));
assert!(matches!(spawned, DiscoverError::CargoNotRunnable { .. }));
assert!(!spawned.is_unverified());
let expired = classify(ChildFailure::Deadline {
limit,
reach: Reach::Killed(Vec::new()),
});
assert!(matches!(expired, DiscoverError::ChildDeadline { .. }));
assert!(expired.is_unverified());
let stalled = classify(ChildFailure::DrainStalled {
limit,
status: exit_status(),
});
assert!(matches!(stalled, DiscoverError::ChildStalled { .. }));
assert!(stalled.is_unverified());
for failure in [
ChildFailure::Wait(io::Error::other("wait"), Reach::Killed(Vec::new())),
ChildFailure::Read(io::Error::other("read")),
] {
let failed = classify(failure);
assert!(matches!(failed, DiscoverError::ChildIo { .. }), "{failed}");
assert!(failed.is_unverified(), "{failed}");
}
assert!(DiscoverError::BadDeadline(String::from("bad")).is_unverified());
}
}