use super::cap::settled;
use super::hook::{self, Call, Event, Verdict};
use super::reason::{denied, denied_binary, file_note, output_note, tainted};
use super::tier::blocks;
use crate::judge::{Checker, Unruled, hazards_in, shown_path, unruled};
use crate::lint::{Finding, Group, Hazards};
use crate::render::codepoint;
use crate::scan::scan_str;
use std::io::Read;
use std::path::{Path, PathBuf};
pub(crate) fn run(stdin: &[u8], root: &Path) -> Result<String, String> {
let hazards = Hazards::builtin();
Ok(match hook::call(stdin)? {
Call::Read { cwd, path } => {
let cwd = cwd.map_or_else(|| root.to_path_buf(), PathBuf::from);
let verdict = read(&cwd, &path, &hazards);
hook::response(Event::Before, &legible(verdict))
}
Call::Output { tool, texts } => {
let verdict = output(&tool, &texts, &hazards);
hook::response(Event::After, &legible(verdict))
}
Call::Other => String::new(),
Call::Unparsed { text, why } => unparsed(&text, &hazards).ok_or(why)?,
})
}
fn unparsed(text: &str, hazards: &Hazards) -> Option<String> {
let blocking: Vec<Finding> =
unsigned(text, hazards).into_iter().filter(blocks).collect();
let first = blocking.first()?;
let why = tainted("unparsed hook", "payload", first, blocking.len());
Some(hook::response(Event::After, &legible(Verdict::Block(why))))
}
fn unsigned(text: &str, hazards: &Hazards) -> Vec<Finding> {
let hits = scan_str(text, |c| !hazards.contains(c));
let exempt = hazards.exempt(text);
hazards_in(hits, |hit| hazards.lint_unsigned(hit, &exempt))
}
fn notes(parts: [Option<String>; 2]) -> Verdict {
let said: Vec<String> = parts.into_iter().flatten().collect();
if said.is_empty() {
Verdict::Pass
} else {
Verdict::Note(said.join(" "))
}
}
fn legible(verdict: Verdict) -> Verdict {
match verdict {
Verdict::Pass => Verdict::Pass,
Verdict::Note(note) => Verdict::Note(spelled(¬e)),
Verdict::Block(why) => Verdict::Block(spelled(&why)),
}
}
fn spelled(text: &str) -> String {
text.chars()
.map(|c| match c {
' '..='~' => String::from(c),
_ => format!("<{}>", codepoint(c)),
})
.collect()
}
fn read(cwd: &Path, path: &str, hazards: &Hazards) -> Verdict {
let full = cwd.join(path);
let Some((bytes, whole)) = loaded(&full, CAP) else {
return Verdict::Pass;
};
let shown = shown_path(cwd, &full);
let (verdict, text) = judged(cwd, &shown, &bytes, hazards);
if whole || !text {
verdict
} else {
partial(&shown, verdict, bytes.len())
}
}
const CAP: u64 = 16 * 1024 * 1024;
fn loaded(full: &Path, cap: u64) -> Option<(Vec<u8>, bool)> {
let file = std::fs::File::open(full).ok()?;
let mut bytes = Vec::new();
file.take(cap.saturating_add(1))
.read_to_end(&mut bytes)
.ok()?;
let whole = u64::try_from(bytes.len()).is_ok_and(|n| n <= cap);
if !whole {
bytes.truncate(cut(&bytes, cap));
}
Some((bytes, whole))
}
fn cut(bytes: &[u8], cap: u64) -> usize {
let cap = usize::try_from(cap).map_or(bytes.len(), |c| c.min(bytes.len()));
let head = bytes.get(..cap).unwrap_or(bytes);
let whole = match std::str::from_utf8(head) {
Err(e) if e.error_len().is_none() => e.valid_up_to(),
_ => head.len(),
};
settled(head.get(..whole).unwrap_or(head))
}
fn partial(shown: &str, verdict: Verdict, judged: usize) -> Verdict {
let rest = format!(
"ctrm: {shown} is over the guard's 16 MiB cap, so only its first \
{judged} bytes were judged; the rest was NOT. `ctrm check \
{shown}` judges it whole."
);
match verdict {
Verdict::Block(why) => Verdict::Block(why),
Verdict::Pass => Verdict::Note(rest),
Verdict::Note(note) => Verdict::Note(format!("{note} {rest}")),
}
}
fn judged(
cwd: &Path,
shown: &str,
bytes: &[u8],
hazards: &Hazards,
) -> (Verdict, bool) {
let config = crate::cli::config::discovered(cwd);
let checker = Checker::configured(&config);
let why = match checker.and_then(|c| c.findings(shown, bytes)) {
Ok(Some(found)) => return (judged_file(shown, &found), true),
Ok(None) => None,
Err(why) => Some(why),
};
hazards_only(shown, unruled(bytes, hazards), why.as_deref())
}
fn judged_file(shown: &str, found: &[Finding]) -> Verdict {
let (hazards, rest): (Vec<&Finding>, Vec<&Finding>) =
found.iter().partition(|f| f.lint.group == Group::Hazard);
let (blocking, noted): (Vec<&Finding>, Vec<&Finding>) =
hazards.into_iter().partition(|f| blocks(f));
match blocking.first() {
Some(first) => Verdict::Block(denied(shown, first, blocking.len())),
None => notes([file_note(shown, ¬ed), noted_rules(shown, &rest)]),
}
}
fn hazards_only(
shown: &str,
unruled: Unruled,
why: Option<&str>,
) -> (Verdict, bool) {
match unruled {
Unruled::NotText(found) => (not_text(shown, &found), false),
Unruled::Text(found) => (unconfigured_file(shown, &found, why), true),
}
}
fn not_text(shown: &str, found: &[Finding]) -> Verdict {
let blocking: Vec<&Finding> = found.iter().filter(|f| blocks(f)).collect();
blocking.first().map_or(Verdict::Pass, |first| {
Verdict::Block(denied_binary(shown, first, blocking.len()))
})
}
fn unconfigured_file(
shown: &str,
found: &[Finding],
why: Option<&str>,
) -> Verdict {
let (blocking, noted): (Vec<&Finding>, Vec<&Finding>) =
found.iter().partition(|f| blocks(f));
match blocking.first() {
Some(first) => Verdict::Block(denied(shown, first, blocking.len())),
None => {
notes([Some(unconfigured(shown, why)), file_note(shown, ¬ed)])
}
}
}
fn unconfigured(shown: &str, why: Option<&str>) -> String {
let why = why.unwrap_or_default();
format!(
"ctrm: the rules could not be applied to {shown} ({why}), so it \
was judged for hazards only, and holds no bidi override or tag \
character."
)
}
fn noted_rules(shown: &str, rest: &[&Finding]) -> Option<String> {
if rest.is_empty() {
return None;
}
Some(format!(
"ctrm: {shown} holds characters its rules report ({}). Not \
blocked; `ctrm check {shown}` lists them and `ctrm fix {shown}` \
rewrites what the map covers.",
tally(rest)
))
}
fn tally(found: &[&Finding]) -> String {
let mut counts: Vec<(&str, usize)> = Vec::new();
for finding in found {
let name = finding.lint.name;
match counts.iter_mut().find(|(seen, _)| *seen == name) {
Some((_, count)) => *count = count.saturating_add(1),
None => counts.push((name, 1)),
}
}
let shown: Vec<String> = counts
.iter()
.map(|(name, n)| format!("{name}: {n}"))
.collect();
shown.join(", ")
}
fn output(
tool: &str,
texts: &[(String, String)],
hazards: &Hazards,
) -> Verdict {
let found = labelled(texts, hazards);
let (blocking, noted): (Vec<_>, Vec<_>) =
found.iter().partition(|(_, f)| blocks(f));
if let Some((at, first)) = blocking.first() {
return Verdict::Block(tainted(tool, at, first, blocking.len()));
}
let at = noted.first().map_or("", |(at, _)| *at);
let noted: Vec<&Finding> = noted.iter().map(|(_, f)| f).collect();
output_note(tool, at, ¬ed).map_or(Verdict::Pass, Verdict::Note)
}
fn labelled<'a>(
texts: &'a [(String, String)],
hazards: &Hazards,
) -> Vec<(&'a str, Finding)> {
texts
.iter()
.flat_map(|(at, text)| {
unsigned(text, hazards)
.into_iter()
.map(move |f| (at.as_str(), f))
})
.collect()
}
#[cfg(test)]
#[path = "adapter_test.rs"]
mod tests;