sokf-core 0.9.0

sokf-core holds the logic of the sokf command-line tool: it loads and validates Superdev Open Knowledge Format (SOKF) knowledge stores, and runs each sokf command. Unstable: its interface can change in any release.
Documentation
//! This module renders the text report of `validate` (CLI-4).
//! The report writes each path relative to the repository root, starting with `/` (CLI-1_AC-6).

use std::fmt::Write as _;

use super::{Finding, FixOp, Report, Severity};

/// `LISTED_WARNINGS` holds the keys of the warnings that the text report
/// lists even without `--warnings`: the warnings at a stale and at an absent
/// part of a harness and at a part that may not be an edit, the warning that
/// the formatter failed, and the warning at a file of the packs that an older
/// sokf wrote, which the agent can act on at once (CLI-4_AC-43).
pub(crate) const LISTED_WARNINGS: [&str; 5] = [
    STALE_PART,
    ABSENT_PART,
    UNVOUCHED_PART,
    crate::compare::WARNING,
    LEFTOVER_PACKS,
];
/// `STALE_PART` is the key of the warning at a stale part of a harness.
pub(crate) const STALE_PART: &str = "CLI-4_AC-40";
/// `ABSENT_PART` is the key of the warning at an absent part of a harness.
pub(crate) const ABSENT_PART: &str = "CLI-4_AC-42";
/// `UNVOUCHED_PART` is the key of the warning at a part of a harness that may
/// not be an edit, because its record doesn't tell an edit from an earlier
/// version of sokf's content.
pub(crate) const UNVOUCHED_PART: &str = "CLI-4_AC-118";
/// `LEFTOVER_PACKS` is the key of the warning at a file of the packs that an
/// older sokf wrote.
pub(crate) const LEFTOVER_PACKS: &str = "CLI-4_AC-104";

/// `message` returns the message of `f` followed by the key of the criterion
/// that `f` breaks, in parentheses, such as `(SOKF_FORMAT_53)`.
// sokf-implements: CLI-4_AC-8
pub fn message(f: &Finding) -> String {
    format!("{} ({})", f.message, f.criterion)
}

/// `and_list` joins `items` as a list in English, for the message of a
/// finding: "a", "a and b", or "a, b, and c".
pub(crate) fn and_list(items: &[String]) -> String {
    match items {
        [] => String::new(),
        [one] => one.clone(),
        [a, b] => format!("{a} and {b}"),
        [rest @ .., last] => format!("{}, and {last}", rest.join(", ")),
    }
}

/// `text` renders the text report: the fixes, then the findings, then the counts line.
// sokf-implements: CLI-4_AC-25
// sokf-implements: CLI-4_AC-26
// sokf-implements: CLI-4_AC-7
// sokf-implements: CLI-4_AC-11
// sokf-implements: CLI-1_AC-6
pub fn text(report: &Report, warnings: bool) -> String {
    let mut out = String::new();
    for fix in &report.fixes {
        match fix {
            FixOp::Moved { from, to } => {
                let _ = writeln!(out, "moved   {from} -> {to}");
            }
            FixOp::Created { path } => {
                let _ = writeln!(out, "created {path}");
            }
            FixOp::Rewrote { path } => {
                let _ = writeln!(out, "rewrote {path}");
            }
        }
    }
    let mut findings: Vec<_> = report.errors.iter().collect();
    // sokf-implements: CLI-4_AC-43
    findings.extend(
        report
            .warnings
            .iter()
            .filter(|f| warnings || LISTED_WARNINGS.contains(&f.criterion.as_str())),
    );
    let listed = findings.len() - report.errors.len();
    if listed > 0 {
        findings.sort_by(|a, b| (&a.path, a.line).cmp(&(&b.path, b.line)));
    }
    for f in findings {
        let severity = match f.severity {
            Severity::Error => "error",
            Severity::Warning => "warning",
        };
        let message = message(f);
        match f.line {
            Some(line) => {
                let _ = writeln!(out, "{}:{line}: {severity}: {message}", f.path);
            }
            None => {
                let _ = writeln!(out, "{}: {severity}: {message}", f.path);
            }
        }
    }
    // sokf-implements: CLI-4_AC-30
    if !out.is_empty() {
        out.push('\n');
    }
    // With no warnings, the counts line reads `0 warnings`, not `0 of 0 warnings listed`.
    let warnings = match report.warnings.len() {
        0 => "0 warnings".to_string(),
        all => format!("{listed} of {all} warnings listed"),
    };
    let _ = writeln!(
        out,
        "{}, {warnings}",
        tramlines_core::text::count(report.errors.len(), "error", "errors")
    );
    out
}

/// `fixable_line` returns the line that follows the line of counts in a run
/// without `--fix`: the number of the findings that the report lists and
/// that `--fix` repairs, followed by `potentially fixable with` and the
/// command, or `None` where it lists none (CLI-4_AC-30). A file whose schema
/// breaks the grammar holds none, because `--fix` leaves it unchanged
/// (CLI-4_AC-106).
// sokf-implements: CLI-4_AC-30
pub fn fixable_line(report: &Report, warnings: bool) -> Option<String> {
    let unchecked: std::collections::BTreeSet<&crate::RepoPath> = report
        .errors
        .iter()
        .filter(|f| f.criterion == "SOKF_VALIDATION_41")
        .map(|f| &f.path)
        .collect();
    let listed = report.errors.iter().chain(
        report
            .warnings
            .iter()
            .filter(|f| warnings || LISTED_WARNINGS.contains(&f.criterion.as_str())),
    );
    let fixable = listed
        .filter(|f| !unchecked.contains(&f.path) && super::fixable::fixable(f))
        .count();
    (fixable > 0).then(|| format!("{fixable} potentially fixable with `sokf validate --fix`"))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn and_list_joins_each_length_of_list() {
        let names =
            |list: &[&str]| -> Vec<String> { list.iter().map(ToString::to_string).collect() };
        assert_eq!(and_list(&[]), "");
        assert_eq!(and_list(&names(&["a"])), "a");
        assert_eq!(and_list(&names(&["a", "b"])), "a and b");
        assert_eq!(and_list(&names(&["a", "b", "c"])), "a, b, and c");
    }
}