use oakum::state::{ChangedPackage, RetiredPackage};
use super::CliError;
#[derive(Default)]
pub(super) struct LookReport {
pub(super) lines: Vec<String>,
pub(super) refusals: Vec<Refusal>,
pub(super) changed: Option<Vec<ChangedPackage>>,
pub(super) retired: Option<Vec<RetiredPackage>>,
}
pub(super) struct Refusal {
pub(super) error: CliError,
pub(super) lines: Vec<String>,
}
impl Refusal {
pub(super) fn bare(error: CliError) -> Self {
Self {
error,
lines: Vec::new(),
}
}
}
impl LookReport {
pub(super) fn from_result(result: Result<(), CliError>) -> Self {
Self::refusing(result.err().into_iter().map(Refusal::bare).collect())
}
pub(super) fn refusing(refusals: Vec<Refusal>) -> Self {
Self {
refusals,
..Self::default()
}
}
}
pub(crate) struct Block {
looks: Vec<&'static str>,
pub(super) error: CliError,
pub(super) lines: Vec<String>,
}
impl Block {
fn raised_by(look: &'static str, refusal: Refusal) -> Self {
Self {
looks: vec![look],
error: refusal.error,
lines: refusal.lines,
}
}
fn also_raised_by(&mut self, look: &'static str) {
if !self.looks.contains(&look) {
self.looks.push(look);
}
}
pub(super) fn raised_by_look(&self, look: &str) -> bool {
self.looks.contains(&look)
}
}
pub(super) struct Verdict {
said: Vec<(&'static str, String)>,
changed: Vec<(&'static str, Vec<ChangedPackage>)>,
retired: Vec<(&'static str, Vec<RetiredPackage>)>,
blocks: Vec<Block>,
deciding: Option<usize>,
}
impl Verdict {
pub(super) fn said(&self) -> impl Iterator<Item = (&'static str, &str)> {
self.said.iter().map(|(look, line)| (*look, line.as_str()))
}
pub(super) fn changed(&self, look: &str) -> Option<&[ChangedPackage]> {
self.changed
.iter()
.find(|(name, _)| *name == look)
.map(|(_, changed)| changed.as_slice())
}
pub(super) fn retired(&self, look: &str) -> Option<&[RetiredPackage]> {
self.retired
.iter()
.find(|(name, _)| *name == look)
.map(|(_, retired)| retired.as_slice())
}
pub(super) fn refusals(&self) -> impl Iterator<Item = (&Block, bool)> {
self.blocks
.iter()
.enumerate()
.map(move |(index, block)| (block, self.deciding == Some(index)))
}
pub(super) fn error(&self) -> Option<CliError> {
let chosen = &self.blocks[self.deciding?];
let mut detail = first_line(&chosen.error.detail());
indent_into(&mut detail, &continuation(&chosen.error.detail()));
indent_into(&mut detail, &chosen.lines);
for (index, also) in self.blocks.iter().enumerate() {
if Some(index) == self.deciding {
continue;
}
detail.push_str("\nalso ");
detail.push_str(also.error.outcome());
detail.push_str(": ");
detail.push_str(&first_line(&also.error.detail()));
indent_into(&mut detail, &continuation(&also.error.detail()));
indent_into(&mut detail, &also.lines);
}
Some(chosen.error.recast(detail))
}
}
pub(super) fn carry(reports: Vec<(&'static str, LookReport)>) -> Verdict {
let mut said = Vec::new();
let mut changed = Vec::new();
let mut retired = Vec::new();
let mut blocks: Vec<Block> = Vec::new();
for (look, report) in reports {
said.extend(report.lines.into_iter().map(|line| (look, line)));
changed.extend(report.changed.map(|packages| (look, packages)));
retired.extend(report.retired.map(|packages| (look, packages)));
for refusal in report.refusals {
match blocks.iter_mut().find(|block| {
block.error.class() == refusal.error.class()
&& block.error.to_string() == refusal.error.to_string()
}) {
Some(block) => {
block.lines.extend(refusal.lines);
block.also_raised_by(look);
}
None => blocks.push(Block::raised_by(look, refusal)),
}
}
}
let deciding = blocks
.iter()
.enumerate()
.min_by_key(|(_, block)| block.error.class())
.map(|(index, _)| index);
Verdict {
said,
changed,
retired,
blocks,
deciding,
}
}
pub(super) fn first_line(detail: &str) -> String {
detail.lines().next().unwrap_or_default().to_owned()
}
fn continuation(detail: &str) -> Vec<String> {
detail.lines().skip(1).map(str::to_owned).collect()
}
fn indent_into(detail: &mut String, lines: &[String]) {
for line in lines {
detail.push('\n');
if !line.is_empty() {
detail.push_str(" ");
detail.push_str(line);
}
}
}
pub(super) fn named(looks: &[&str]) -> String {
match looks {
[] => String::new(),
[only] => (*only).to_owned(),
[rest @ .., last] => format!("{}, and {last}", rest.join(", ")),
}
}
pub(super) fn verdict_line(detail: &str) -> &str {
detail
.lines()
.rev()
.find(|line| line.starts_with("fatal:") || line.starts_with("error:"))
.or_else(|| detail.lines().find(|line| !line.trim().is_empty()))
.unwrap_or_else(|| detail.lines().next().unwrap_or(detail))
}
#[cfg(test)]
mod tests {
use super::{carry, continuation, indent_into, LookReport, Refusal};
use crate::cli::{CliError, Outcome};
fn reports_named(reports: Vec<LookReport>) -> Vec<(&'static str, LookReport)> {
const NAMES: [&str; 4] = ["first", "second", "third", "fourth"];
reports
.into_iter()
.enumerate()
.map(|(index, report)| (NAMES[index], report))
.collect()
}
#[test]
fn a_multi_line_refusal_stays_one_block() {
let report = LookReport::refusing(vec![Refusal {
error: CliError::unverified("unverified: first\nsecond"),
lines: vec![String::from("detail")],
}]);
let verdict = carry(reports_named(vec![report]))
.error()
.expect("a refusal");
assert_eq!(verdict.detail(), "first\n second\n detail");
}
#[test]
fn a_merged_block_names_both_looks() {
let same = || CliError::unverified("unverified: same text");
let first = LookReport::refusing(vec![Refusal::bare(same())]);
let second = LookReport::refusing(vec![Refusal::bare(same())]);
let verdict = carry(reports_named(vec![first, second]));
let (block, _) = verdict.refusals().next().expect("one merged block");
assert!(block.raised_by_look("first") && block.raised_by_look("second"));
}
#[test]
fn an_identical_refusal_merges_and_keeps_its_evidence() {
let same = || CliError::unverified("unverified: same text");
let first = LookReport::refusing(vec![Refusal {
error: same(),
lines: vec![String::from("from the first look")],
}]);
let second = LookReport::refusing(vec![Refusal {
error: same(),
lines: vec![String::from("from the second look")],
}]);
let verdict = carry(reports_named(vec![first, second]))
.error()
.expect("a refusal");
assert_eq!(
verdict.detail(),
"same text\n from the first look\n from the second look"
);
}
#[test]
fn a_shadowed_multi_line_refusal_stays_one_block() {
let deciding = LookReport::refusing(vec![Refusal::bare(CliError::new("first"))]);
let shadowed = LookReport::refusing(vec![Refusal::bare(CliError::unverified(
"unverified: git failed\nfatal: why",
))]);
let verdict = carry(reports_named(vec![deciding, shadowed]))
.error()
.expect("a refusal");
assert_eq!(
verdict.detail(),
"first\nalso unverified: git failed\n fatal: why"
);
}
#[test]
fn a_finding_does_not_merge_into_an_identical_unverified_look() {
let look = LookReport::refusing(vec![Refusal::bare(CliError::unverified(
"unverified: same words",
))]);
let finding =
LookReport::refusing(vec![Refusal::bare(CliError::new("unverified: same words"))]);
let verdict = carry(reports_named(vec![look, finding]))
.error()
.expect("a refusal");
assert_eq!(verdict.class(), Outcome::Error);
assert_eq!(verdict.detail(), "same words\nalso unverified: same words");
}
#[test]
fn a_report_is_said_and_is_not_a_block() {
let advisory = LookReport {
lines: vec![String::from("changed with no covering intent")],
..LookReport::default()
};
let refusing = LookReport::refusing(vec![Refusal::bare(CliError::new("drift"))]);
let verdict = carry(reports_named(vec![advisory, refusing]));
assert_eq!(
verdict.said().collect::<Vec<_>>(),
vec![("first", "changed with no covering intent")]
);
assert_eq!(verdict.error().expect("a refusal").detail(), "drift");
}
#[test]
fn a_blank_detail_line_carries_no_indent() {
let mut detail = String::from("summary");
indent_into(&mut detail, &continuation("summary\none\n\nthree"));
assert_eq!(detail, "summary\n one\n\n three");
}
}
#[cfg(test)]
mod conclusion {
use super::verdict_line;
#[test]
fn the_last_fatal_wins_over_an_earlier_warning() {
let detail = "warning: could not open directory 'vendor/': Permission denied\n\
fatal: object database is unreadable; run `git fsck`";
assert_eq!(
verdict_line(detail),
"fatal: object database is unreadable; run `git fsck`"
);
}
#[test]
fn an_inflate_error_does_not_outrank_the_conclusion() {
let detail = "error: inflate: data stream error (incorrect header check)\n\
error: unable to unpack 2407861 header\n\
fatal: Not a valid commit name main";
assert_eq!(verdict_line(detail), "fatal: Not a valid commit name main");
}
#[test]
fn a_diagnostic_with_no_verdict_keeps_its_first_line() {
assert_eq!(
verdict_line("terminated by a signal"),
"terminated by a signal"
);
assert_eq!(verdict_line(""), "");
}
#[test]
fn a_blank_diagnostic_still_yields_one_line() {
assert_eq!(verdict_line(" \n \n"), " ");
}
}