use std::collections::BTreeMap;
use openmoat_core::{Kind, Policy, RuleGroup};
use serde_json::Value;
use crate::upgrade::Change;
const NAMED_PATTERNS: usize = 3;
const NAMED_PATTERN_CHARS: usize = 40;
#[derive(Debug, Default, PartialEq, Eq)]
pub(super) struct Summary {
pub protections: Vec<String>,
pub fewer: Vec<String>,
pub renamed: bool,
pub wording: usize,
pub other: Vec<String>,
pub unexplained: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum List {
Deny,
Review,
Allow,
Defer,
}
impl List {
fn lets_through(self) -> bool {
matches!(self, Self::Allow | Self::Defer)
}
fn name(self) -> &'static str {
match self {
Self::Deny => "deny",
Self::Review => "review",
Self::Allow => "allow",
Self::Defer => "defer",
}
}
}
pub(super) fn summarise(
current: &str,
merged: &str,
changes: &[&Change],
renamed: bool,
) -> Summary {
let mut summary = Summary {
renamed,
..Summary::default()
};
let wording_only = changes
.iter()
.filter(|c| without_comments(&c.yours) == without_comments(&c.default))
.count();
let code = changes.len() - wording_only;
summary.wording = wording_only;
match (Policy::parse(current), Policy::parse(merged)) {
(Ok(before), Ok(after)) => {
summary.wording += rules(&before, &after, &mut summary);
sections(&before, &after, &mut summary);
let named = summary.protections.len() + summary.fewer.len() + summary.other.len();
if named == 0 && summary.wording == wording_only {
summary.unexplained = code;
}
}
_ => summary.unexplained = code,
}
summary
}
impl Summary {
pub fn write(&self, out: &mut impl std::io::Write) -> std::io::Result<()> {
let groups = [
("New protections", "+", &self.protections),
("Fewer interruptions", "−", &self.fewer),
("Other changes", "·", &self.other),
];
for (heading, mark, lines) in groups {
if lines.is_empty() {
continue;
}
writeln!(out, " {heading}")?;
for line in lines {
writeln!(out, " {mark} {}", crate::render::clean(line))?;
}
}
if self.renamed {
writeln!(out, " Renamed")?;
writeln!(out, " ~ `ask` is now `review` (same behaviour)")?;
}
if self.wording > 0 {
let updates = crate::report::count(self.wording, "comment and wording update");
writeln!(out, " + {updates}")?;
}
if self.unexplained > 0 {
writeln!(out, " Other changes: {} (d to see)", self.unexplained)?;
}
Ok(())
}
}
fn groups(policy: &Policy) -> BTreeMap<&str, (List, &RuleGroup)> {
let lists = [
(List::Deny, &policy.deny),
(List::Review, &policy.review),
(List::Allow, &policy.allow),
(List::Defer, &policy.defer),
];
lists
.into_iter()
.flat_map(|(list, groups)| groups.iter().map(move |g| (g.id.as_str(), (list, g))))
.collect()
}
fn rules(before: &Policy, after: &Policy, summary: &mut Summary) -> usize {
let (old, new) = (groups(before), groups(after));
let mut reworded = 0;
for (id, (list, group)) in &new {
match old.get(id) {
None => added_group(*list, group, summary),
Some((was, _)) if was != list => summary.other.push(format!(
"`{id}` moved from `{}:` to `{}:`",
was.name(),
list.name()
)),
Some((_, was)) => {
let patterns = pattern_changes(*list, id, was, group, summary);
let rest_same = RuleGroup {
reason: group.reason.clone(),
title: group.title.clone(),
why: group.why.clone(),
..(*was).clone()
} == **group;
let words = (&was.reason, &was.title, &was.why)
!= (&group.reason, &group.title, &group.why);
if !patterns && words && rest_same {
reworded += 1;
} else if was.hook_only != group.hook_only {
summary.other.push(format!("`{id}`: `hook_only` changed"));
}
}
}
}
for (id, (list, _)) in old.iter().filter(|(id, _)| !new.contains_key(*id)) {
let line = format!("`{id}` removed (it was a `{}:` rule)", list.name());
if list.lets_through() {
summary.protections.push(line);
} else {
summary.fewer.push(line);
}
}
reworded
}
fn added_group(list: List, group: &RuleGroup, summary: &mut Summary) {
let what = group
.title
.clone()
.or_else(|| group.reason.clone())
.unwrap_or_else(|| patterns_phrase(&all_patterns(group)));
let id = &group.id;
match list {
List::Deny => summary.protections.push(format!("Denied: {what} (`{id}`)")),
List::Review => summary
.protections
.push(format!("Needs your review: {what} (`{id}`)")),
List::Allow => summary.fewer.push(format!("Allowed: {what} (`{id}`)")),
List::Defer => summary
.fewer
.push(format!("Left to the agent: {what} (`{id}`)")),
}
}
fn pattern_changes(
list: List,
id: &str,
was: &RuleGroup,
now: &RuleGroup,
summary: &mut Summary,
) -> bool {
let (mut tighter, mut wider) = (Vec::new(), Vec::new());
for kind in Kind::ALL {
let (old, new) = (was.patterns(kind), now.patterns(kind));
let added = new.iter().filter(|p| !old.contains(p)).map(|p| (p, true));
let removed = old.iter().filter(|p| !new.contains(p)).map(|p| (p, false));
for (pattern, added) in added.chain(removed) {
let shown = pattern.strip_prefix('!');
let side = if added ^ shown.is_some() ^ list.lets_through() {
&mut tighter
} else {
&mut wider
};
side.push(shown.unwrap_or(pattern.as_str()));
}
}
let (now_covers, no_longer) = match list {
List::Deny => ("now also denies", "no longer denies"),
List::Review => ("now also holds for review", "no longer holds for review"),
List::Allow => ("no longer allows", "now also allows"),
List::Defer => (
"no longer leaves to the agent",
"now also leaves to the agent",
),
};
if !tighter.is_empty() {
let line = format!("`{id}` {now_covers} {}", patterns_phrase(&tighter));
summary.protections.push(line);
}
if !wider.is_empty() {
let line = format!("`{id}` {no_longer} {}", patterns_phrase(&wider));
summary.fewer.push(line);
}
!(tighter.is_empty() && wider.is_empty())
}
fn all_patterns(group: &RuleGroup) -> Vec<&str> {
Kind::ALL
.iter()
.flat_map(|k| group.patterns(*k))
.map(String::as_str)
.collect()
}
fn patterns_phrase(patterns: &[&str]) -> String {
let short = patterns.len() <= NAMED_PATTERNS
&& patterns
.iter()
.all(|p| p.chars().count() <= NAMED_PATTERN_CHARS);
if short && !patterns.is_empty() {
let named: Vec<String> = patterns.iter().map(|p| format!("`{p}`")).collect();
named.join(", ")
} else {
crate::report::count(patterns.len(), "pattern")
}
}
fn sections(before: &Policy, after: &Policy, summary: &mut Summary) {
let rest = |policy: &Policy| -> Option<serde_json::Map<String, Value>> {
let Value::Object(mut map) = serde_json::to_value(policy).ok()? else {
return None;
};
for list in ["deny", "review", "allow", "defer"] {
map.remove(list);
}
Some(map)
};
let (Some(old), Some(new)) = (rest(before), rest(after)) else {
return;
};
let keys: std::collections::BTreeSet<&String> = old.keys().chain(new.keys()).collect();
for key in keys {
if old.get(key) != new.get(key) {
summary.other.push(format!("`{key}:` changed"));
}
}
}
fn without_comments(text: &str) -> Vec<String> {
text.lines()
.map(|line| strip_comment(line).trim_end().to_owned())
.filter(|line| !line.trim().is_empty())
.collect()
}
fn strip_comment(line: &str) -> &str {
let (mut single, mut double) = (false, false);
let mut previous = ' ';
for (at, c) in line.char_indices() {
match c {
'\'' if !double => single = !single,
'"' if !single => double = !double,
'#' if !single && !double && previous.is_whitespace() => return &line[..at],
_ => {}
}
previous = c;
}
line
}
#[cfg(test)]
mod tests;