use same_same::{Answer, NamedSet, Note, Unavailable, Verdict};
use super::{Pair, Reading, WARNING};
use crate::{Finding, RepoPath};
pub(super) fn reading(
pair: &Pair,
answer: &Answer,
ranged: bool,
same: NamedSet,
origin: &RepoPath,
) -> Reading {
let current = match &answer.verdict {
Verdict::Same => true,
Verdict::SameApartFrom(named) => named.is_subset(same),
_ => false,
};
if current {
return Reading {
current,
..Reading::default()
};
}
let line = answer
.place
.as_ref()
.zip(pair.source.as_ref())
.and_then(|(place, source)| source_line(source, ranged, place.a.lines.start));
let file = pair
.source
.as_ref()
.map_or(&pair.path, |source| &source.path);
let (warning, unsettled) = match warning(answer, file) {
Some((message, unsettled)) => (
Some(Finding::warning(origin.clone(), None, WARNING, message)),
unsettled,
),
None => (None, false),
};
Reading {
current,
line,
warning,
unsettled,
}
}
fn source_line(source: &super::Source, ranged: bool, line: u32) -> Option<usize> {
let line = if ranged {
line
} else {
let index = usize::try_from(line.checked_sub(1)?).ok()?;
match source.lines.get(index) {
Some(&line) => line,
None if index == source.lines.len() => source.lines.last()? + 1,
None => return None,
}
};
usize::try_from(line).ok()
}
fn warning(answer: &Answer, file: &RepoPath) -> Option<(String, bool)> {
let unavailable = answer.notes.iter().find_map(|note| match note {
Note::NormaliserUnavailable { id, why } => {
Some((unavailable_message(&id.name, why, file), true))
}
_ => None,
});
if unavailable.is_some() {
return unavailable;
}
answer.notes.iter().find_map(|note| match note {
Note::NormaliserCannot { id, .. } => Some((
format!("the formatter {} fails on `{file}`", id.name),
false,
)),
_ => None,
})
}
fn unavailable_message(name: &str, why: &Unavailable, file: &RepoPath) -> String {
match why {
Unavailable::Missing { program } if program.contains(['/', '\\']) => {
format!("the formatter {name} doesn't start: `{program}` names no file")
}
Unavailable::Missing { program } => format!(
"the formatter {name} doesn't start: `{program}` is in neither `node_modules/.bin` nor the path"
),
Unavailable::DoesntStart { why } => format!("the formatter {name} doesn't start: {why}"),
Unavailable::SampleFailed => {
let sample = file.extension().map_or_else(
|| "sample".to_string(),
|ending| format!("`.{ending}` sample"),
);
format!("the formatter {name} fails even on a plain {sample}; check its installation")
}
Unavailable::Hung { limit } => {
let secs = limit.as_secs();
let unit = if secs == 1 { "second" } else { "seconds" };
format!(
"the formatter {name} runs longer than `format.timeout`, {secs} {unit}, on `{file}`"
)
}
Unavailable::Broken { why } => format!("the formatter {name} fails: {why}"),
_ => format!("the formatter {name} fails on `{file}`"),
}
}