use std::io;
use std::path::PathBuf;
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error(
"cannot open the state directory {path}: {source}\n\
calmrun: next: make sure it is writable, or point CALMRUN_HOME somewhere that is"
)]
StateDir {
path: PathBuf,
#[source]
source: io::Error,
},
#[error(
"cannot lock or update the queue state: {0}\n\
calmrun: next: check the state directory (`calmrun doctor` shows it)"
)]
State(#[source] io::Error),
#[error("cannot run {program}: {source}{}", spawn_hint(source))]
Spawn {
program: String,
#[source]
source: io::Error,
},
#[error("invalid queue id \"{0}\": use letters, digits, '-', '_' or '.' (not first)")]
InvalidQueue(String),
#[error("cannot read system information: {0}")]
SystemInfo(String),
#[error("cannot write {path}: {source}")]
Write {
path: PathBuf,
#[source]
source: io::Error,
},
}
fn spawn_hint(e: &io::Error) -> &'static str {
if e.kind() == io::ErrorKind::NotFound {
"\ncalmrun: next: check the name and PATH; a package's own bin may need `npx`, \
`pnpm exec` or `uv run` in front"
} else {
""
}
}
impl Error {
pub fn exit_code(&self) -> i32 {
match self {
Error::Spawn { source, .. } if source.kind() == io::ErrorKind::NotFound => 127,
Error::Spawn { .. } => 126,
Error::InvalidQueue(_) => 2,
_ => 1,
}
}
pub fn status(&self) -> &'static str {
match self {
Error::Spawn { .. } => "spawn-failed",
_ => "error",
}
}
}
pub type Result<T> = std::result::Result<T, Error>;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn missing_program_is_127_with_a_hint() {
let e = Error::Spawn {
program: "vitestt".into(),
source: io::Error::new(io::ErrorKind::NotFound, "command not found: vitestt"),
};
assert_eq!(e.exit_code(), 127);
let text = e.to_string();
assert!(text.starts_with("cannot run vitestt: command not found: vitestt\ncalmrun: next:"));
assert_eq!(Error::InvalidQueue("../x".into()).exit_code(), 2);
}
}