use std::fmt;
use std::io;
use std::path::Path;
use crumbkit::{Code, Failure, Field, FieldValue, Recovery, Spelling};
use miette::{Diagnostic, LabeledSpan, NamedSource, SourceCode};
use starmap::{Spec, SpecError, SpecProblemKind};
use crate::cli::SpecFile;
use crate::codes;
use crate::files;
#[cfg(test)]
mod tests;
pub(crate) fn load(path: &Path) -> Result<Spec, SpecFailure> {
let file = path.display().to_string();
let bytes = files::read_capped(path, Spec::MAX_BYTES + 1).map_err(|error| {
if error.kind() == io::ErrorKind::NotFound {
SpecFailure::NotFound { file: file.clone() }
} else {
SpecFailure::Unreadable {
file: file.clone(),
error,
}
}
})?;
if bytes.len() > Spec::MAX_BYTES {
return Err(SpecFailure::TooLarge { file });
}
parse(file, bytes)
}
pub(crate) fn parse(file: String, bytes: Vec<u8>) -> Result<Spec, SpecFailure> {
let text = String::from_utf8(bytes).map_err(|error| SpecFailure::NotUtf8 {
file: file.clone(),
at: error.utf8_error().valid_up_to(),
})?;
Spec::parse(&text).map_err(|error| SpecFailure::Invalid {
source: NamedSource::new(file.clone(), text),
file,
error,
})
}
#[derive(Debug)]
pub(crate) enum SpecFailure {
NotFound {
file: String,
},
Exists {
file: String,
},
Unwritable {
file: String,
error: io::Error,
},
Unreadable {
file: String,
error: io::Error,
},
TooLarge {
file: String,
},
NotUtf8 {
file: String,
at: usize,
},
Invalid {
file: String,
source: NamedSource<String>,
error: SpecError,
},
}
impl SpecFailure {
fn first_kind(&self) -> Option<SpecProblemKind> {
match self {
Self::Invalid { error, .. } => error.problems().first().map(|problem| problem.kind()),
Self::NotFound { .. }
| Self::Exists { .. }
| Self::Unwritable { .. }
| Self::Unreadable { .. }
| Self::TooLarge { .. }
| Self::NotUtf8 { .. } => None,
}
}
fn guesses(&self) -> Option<usize> {
let Self::Invalid { error, .. } = self else {
return None;
};
let problems = error.problems();
let all_guesses = problems
.iter()
.all(|problem| problem.kind() == SpecProblemKind::Guess);
(problems.len() > 1 && all_guesses).then_some(problems.len())
}
}
impl fmt::Display for SpecFailure {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotFound { file } => write!(formatter, "{file} does not exist"),
Self::Exists { file } => write!(formatter, "{file} exists already"),
Self::Unwritable { file, .. } => write!(formatter, "{file} cannot be written"),
Self::Unreadable { file, .. } => write!(formatter, "{file} cannot be read"),
Self::TooLarge { file } => write!(formatter, "{file} is over 256 KiB"),
Self::NotUtf8 { file, at } => write!(
formatter,
"{file} is not UTF-8 text at byte {at}, so it is not TOML"
),
Self::Invalid { file, error, .. } => match (error.problems(), self.guesses()) {
([problem], _) => write!(formatter, "{file}: {problem}"),
(_, Some(count)) => write!(
formatter,
"{file} still holds {count} guesses that starmap init marked with ?"
),
(problems, None) => write!(formatter, "{file} has {} problems", problems.len()),
},
}
}
}
impl std::error::Error for SpecFailure {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Unreadable { error, .. } | Self::Unwritable { error, .. } => Some(error),
Self::NotFound { .. }
| Self::Exists { .. }
| Self::TooLarge { .. }
| Self::NotUtf8 { .. }
| Self::Invalid { .. } => None,
}
}
}
impl Diagnostic for SpecFailure {
fn source_code(&self) -> Option<&dyn SourceCode> {
match self {
Self::Invalid { source, .. } => Some(source),
Self::NotFound { .. }
| Self::Exists { .. }
| Self::Unwritable { .. }
| Self::Unreadable { .. }
| Self::TooLarge { .. }
| Self::NotUtf8 { .. } => None,
}
}
fn labels(&self) -> Option<Box<dyn Iterator<Item = LabeledSpan> + '_>> {
let Self::Invalid { error, .. } = self else {
return None;
};
if self.guesses().is_some() {
let span = error.problems().first()?.span();
let label =
LabeledSpan::new(Some("the first guess".to_owned()), span.start, span.len());
return Some(Box::new(std::iter::once(label)));
}
let only = error.problems().len() == 1;
Some(Box::new(error.problems().iter().map(move |problem| {
let span = problem.span();
let text = if only {
"here".to_owned()
} else {
problem.to_string()
};
LabeledSpan::new(Some(text), span.start, span.len())
})))
}
}
impl Failure for SpecFailure {
fn code(&self) -> &'static Code {
match self {
Self::NotFound { .. } => &codes::SPEC_NOT_FOUND,
Self::Exists { .. } => &codes::SPEC_EXISTS,
Self::Unwritable { .. } => &codes::SPEC_UNWRITABLE,
Self::Unreadable { .. } => &codes::SPEC_UNREADABLE,
Self::TooLarge { .. } => &codes::SPEC_TOO_LARGE,
Self::NotUtf8 { .. } => &codes::SPEC_SYNTAX,
Self::Invalid { .. } => self.first_kind().map_or(&codes::SPEC_SYNTAX, code),
}
}
fn recovery(&self) -> Recovery {
let hint = match self {
Self::NotFound { file } => return Recovery::Run(SpecFile::call(&["init"], file)),
Self::Exists { file } => return Recovery::Run(SpecFile::call(&["check"], file)),
Self::Unwritable { file, .. } => {
format!("make the directory of {file} writable, or pass --spec another file")
}
Self::Unreadable { file, .. } => {
format!("make {file} readable, or pass --spec another file")
}
Self::TooLarge { .. } => hint(SpecProblemKind::TooLarge).to_owned(),
Self::NotUtf8 { file, .. } => format!("save {file} as UTF-8 text"),
Self::Invalid { .. } => self.first_kind().map_or("", hint).to_owned(),
};
Recovery::Hint(hint)
}
fn fields(&self) -> Vec<Field<'_>> {
match self {
Self::NotFound { file }
| Self::Exists { file }
| Self::Unwritable { file, .. }
| Self::Unreadable { file, .. }
| Self::TooLarge { file }
| Self::NotUtf8 { file, .. } => {
vec![Field::new("file", file)]
}
Self::Invalid { file, error, .. } => vec![
Field::new("file", file),
Field::new(
"problems",
FieldValue::list(error.problems().iter().map(|problem| problem.kind().code())),
),
],
}
}
fn diagnostic(&self) -> Option<&dyn Diagnostic> {
Some(self)
}
}
fn code(kind: SpecProblemKind) -> &'static Code {
codes::ALL
.iter()
.copied()
.find(|code| Spelling::COLONS.spell(code) == kind.code())
.unwrap_or(&codes::SPEC_SYNTAX)
}
fn hint(kind: SpecProblemKind) -> &'static str {
match kind {
SpecProblemKind::TooLarge => {
"remove the variables the application does not read, so the file is at most 256 KiB"
}
SpecProblemKind::UnknownField => "use one of the fields the failure lists",
SpecProblemKind::MissingField => "add the field the failure names",
SpecProblemKind::BadValue => "set a value the field takes, as the failure lists",
SpecProblemKind::BadName => {
"rename the variable with upper case letters, digits and underscores"
}
SpecProblemKind::Guess => "confirm or correct each guess and delete its ?",
SpecProblemKind::BadDefault => "set a default the type accepts",
SpecProblemKind::BadRange => "swap or correct the bounds",
SpecProblemKind::EmptyEnumeration => "list each value once",
SpecProblemKind::ShownSecret => "set show = \"withheld\"",
SpecProblemKind::SecretForm => "set type = \"string\"",
SpecProblemKind::BindMismatch => "change the source or the bind, as the failure lists",
SpecProblemKind::BadBytes => "set bytes from 16 to 1024 on a generated variable",
SpecProblemKind::UnknownPlaceholder => "use {workspace}, {checkout} or {home}",
SpecProblemKind::ModeUndeclared => "declare the mode variable",
SpecProblemKind::ModeSource => "make the mode variable a setting",
_ => "fix the line the failure points at",
}
}