use std::fmt;
use std::io;
use std::path::{Path, PathBuf};
use crumbkit::{Code, Failure, Field, FieldValue, Recovery};
use miette::{Diagnostic, LabeledSpan, NamedSource, SourceCode};
use starmap::{Pointer, Spec, SpecError, SpecProblemKind};
use crate::cli::SpecFile;
use crate::codes;
use crate::files;
mod listed;
mod masked;
#[cfg(test)]
mod tests;
use listed::{code, hint};
use masked::masked;
#[derive(Debug)]
pub(crate) struct Opened {
pub(crate) spec: Spec,
pub(crate) located: Located,
}
#[derive(Debug)]
pub(crate) struct Located {
pub(crate) file: PathBuf,
pub(crate) src: Vec<PathBuf>,
pub(crate) dotenv: PathBuf,
pub(crate) pointer: Option<String>,
text: Option<String>,
}
impl Located {
fn beside(path: &Path, text: Option<String>) -> Self {
let dir = path.parent().unwrap_or(Path::new(""));
Self {
file: path.to_path_buf(),
src: vec![dir.join(Pointer::SRC)],
dotenv: dir.join(Pointer::DOTENV),
pointer: None,
text,
}
}
}
pub(crate) fn open(path: &Path) -> Result<Opened, SpecFailure> {
let mut located = locate(path)?;
let file = located.file.display().to_string();
let spec = match located.text.take() {
Some(text) => parse_text(file, text),
None => read(&located.file).and_then(|bytes| parse(file, bytes)),
}
.map_err(|failure| failure.through(located.pointer.as_deref()))?;
Ok(Opened { spec, located })
}
pub(crate) fn locate(path: &Path) -> Result<Located, SpecFailure> {
let file = path.display().to_string();
let bytes = match read(path) {
Ok(bytes) => bytes,
Err(SpecFailure::NotFound { .. }) => return Ok(Located::beside(path, None)),
Err(failure) => return Err(failure),
};
let text = utf8(&file, bytes)?;
match Pointer::parse(&text) {
Ok(None) => Ok(Located::beside(path, Some(text))),
Ok(Some(pointer)) => {
let dir = path.parent().unwrap_or(Path::new(""));
Ok(Located {
file: dir.join(pointer.spec()),
src: pointer.src().iter().map(|src| dir.join(src)).collect(),
dotenv: dir.join(pointer.dotenv()),
pointer: Some(file),
text: None,
})
}
Err(error) => Err(SpecFailure::Invalid {
source: masked(text, error.reference_spans())
.map(|text| NamedSource::new(file.clone(), text)),
file,
error,
}),
}
}
fn read(path: &Path) -> Result<Vec<u8>, 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(),
pointer: None,
}
} else {
SpecFailure::Unreadable {
file: file.clone(),
error,
}
}
})?;
if bytes.len() > Spec::MAX_BYTES {
return Err(SpecFailure::TooLarge { file });
}
Ok(bytes)
}
fn utf8(file: &str, bytes: Vec<u8>) -> Result<String, SpecFailure> {
String::from_utf8(bytes).map_err(|error| SpecFailure::NotUtf8 {
file: file.to_owned(),
at: error.utf8_error().valid_up_to(),
})
}
pub(crate) fn parse(file: String, bytes: Vec<u8>) -> Result<Spec, SpecFailure> {
let text = utf8(&file, bytes)?;
parse_text(file, text)
}
fn parse_text(file: String, text: String) -> Result<Spec, SpecFailure> {
Spec::parse(&text).map_err(|error| SpecFailure::Invalid {
source: masked(text, error.reference_spans())
.map(|text| NamedSource::new(file.clone(), text)),
file,
error,
})
}
#[derive(Debug)]
pub(crate) enum SpecFailure {
NotFound {
file: String,
pointer: Option<String>,
},
Exists {
file: String,
pointer: Option<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: Option<NamedSource<String>>,
error: SpecError,
},
}
impl SpecFailure {
fn through(self, pointer: Option<&str>) -> Self {
match (self, pointer) {
(Self::NotFound { file, .. }, Some(pointer)) => Self::NotFound {
file,
pointer: Some(pointer.to_owned()),
},
(failure, _) => failure,
}
}
fn given<'a>(file: &'a str, pointer: Option<&'a String>) -> &'a str {
pointer.map_or(file, String::as_str)
}
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,
pointer: None,
} => write!(formatter, "{file} does not exist"),
Self::NotFound {
file,
pointer: Some(pointer),
} => write!(
formatter,
"{file}, which {pointer} points to, does not exist"
),
Self::Exists {
file,
pointer: None,
} => write!(formatter, "{file} exists already"),
Self::Exists {
file,
pointer: Some(pointer),
} => write!(
formatter,
"{file}, which {pointer} points to, 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 { error, .. }
if error
.problems()
.iter()
.any(|problem| problem.kind() == SpecProblemKind::WithheldDefault) =>
{
None
}
Self::Invalid { source, .. } => source.as_ref().map(|source| source as &dyn SourceCode),
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) -> 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, pointer } => {
return Recovery::Run(SpecFile::call(
&["init"],
Self::given(file, pointer.as_ref()),
));
}
Self::Exists { file, pointer } => {
return Recovery::Run(SpecFile::call(
&["check"],
Self::given(file, pointer.as_ref()),
));
}
Self::Unwritable { file, .. } => format!("make the directory of {file} writable"),
Self::Unreadable { file, .. } => format!("make {file} readable"),
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 alternatives(&self) -> Vec<Recovery> {
match self {
Self::Unwritable { .. } | Self::Unreadable { .. } => {
vec![Recovery::hint("pass --spec another file")]
}
Self::NotFound { .. }
| Self::Exists { .. }
| Self::TooLarge { .. }
| Self::NotUtf8 { .. }
| Self::Invalid { .. } => Vec::new(),
}
}
fn fields(&self) -> Vec<Field<'_>> {
match self {
Self::NotFound { file, pointer } | Self::Exists { file, pointer } => {
let mut fields = vec![Field::new("file", file)];
if let Some(pointer) = pointer {
fields.push(Field::new("pointer", pointer));
}
fields
}
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)
}
}