use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct RemovedComment {
pub id: String,
pub author: String,
pub replies: Vec<String>,
#[serde(default)]
pub why: String,
#[serde(skip)]
pub decision: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct KeptComment {
pub id: String,
pub replies: Vec<String>,
pub anchor: String,
}
use crate::revision_processor::Resolution;
#[derive(Debug)]
#[doc(hidden)]
pub struct SettlementError {
pub code: String,
pub message: String,
}
impl SettlementError {
fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
Self {
code: code.into(),
message: message.into(),
}
}
}
impl std::fmt::Display for SettlementError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.message)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Pass {
resolution: Resolution,
settled: Option<Vec<String>>,
}
#[derive(Debug, Default, PartialEq, Eq)]
#[doc(hidden)]
pub struct AnchorChanges {
pub removed: Vec<String>,
pub kept: Vec<String>,
passes: std::collections::HashMap<String, Pass>,
}
impl AnchorChanges {
pub fn extend(
&mut self,
removed: Vec<String>,
kept: Vec<String>,
resolution: Resolution,
settled: Option<&[String]>,
) {
let pass = Pass {
resolution,
settled: settled.map(<[String]>::to_vec),
};
for id in &removed {
self.passes.insert(id.clone(), pass.clone());
}
self.removed.extend(removed);
self.kept.extend(kept);
self.kept.retain(|id| !self.removed.contains(id));
}
pub fn records(
&self,
source: &[u8],
) -> Result<(Vec<RemovedComment>, Vec<KeptComment>), SettlementError> {
assert!(
self.removed.iter().all(|id| !self.kept.contains(id)),
"a comment cannot be both removed and kept"
);
if self.removed.is_empty() && self.kept.is_empty() {
return Ok((Vec::new(), Vec::new()));
}
let comments = crate::comments::list_comments(source)
.map_err(|e| SettlementError::new("INVALID_DOCUMENT", e.to_string()))?;
let groups = |ids: &[String]| {
let wanted: std::collections::HashSet<u32> =
ids.iter().filter_map(|id| id.parse().ok()).collect();
comments
.iter()
.filter(|c| {
wanted.contains(&c.id) && !c.parent.is_some_and(|p| wanted.contains(&p))
})
.map(|root| {
let mut family = vec![root.id];
loop {
let before = family.len();
for c in &comments {
if wanted.contains(&c.id)
&& !family.contains(&c.id)
&& c.parent.is_some_and(|p| family.contains(&p))
{
family.push(c.id);
}
}
if before == family.len() {
break;
}
}
let replies = comments
.iter()
.filter(|c| c.id != root.id && family.contains(&c.id))
.map(|c| format!("c{}", c.id))
.collect::<Vec<String>>();
(root, replies)
})
.collect::<Vec<_>>()
};
let (holders, wholes) = if self.removed.is_empty() {
(Vec::new(), std::collections::HashMap::new())
} else {
let invalid = |e: crate::changes::ChangeError| {
SettlementError::new("INVALID_DOCUMENT", e.to_string())
};
(
crate::changes::list_changes_tolerant(source).map_err(invalid)?,
crate::changes::member_wholes(source).map_err(invalid)?,
)
};
let passes: std::collections::HashMap<u32, _> = self
.passes
.iter()
.filter_map(|(raw, pass)| Some((raw.parse::<u32>().ok()?, pass)))
.collect();
let removed = groups(&self.removed)
.into_iter()
.map(|(c, replies)| {
let pass = passes
.get(&c.id)
.expect("every removed thread is recorded with its pass");
let id = format!("c{}", c.id);
let thread: Vec<String> = std::iter::once(id.clone())
.chain(replies.iter().cloned())
.collect();
let why = crate::changes::why_removed(
&holders,
&thread,
pass.resolution,
pass.settled.as_deref(),
&wholes,
);
RemovedComment {
id,
author: c.author.clone(),
replies,
why,
decision: Some(
match pass.resolution {
Resolution::Accept => "acceptance",
Resolution::Reject => "rejection",
}
.into(),
),
}
})
.collect();
let kept = groups(&self.kept)
.into_iter()
.map(|(c, replies)| KeptComment {
id: format!("c{}", c.id),
replies,
anchor: "empty".into(),
})
.collect();
Ok((removed, kept))
}
}
#[doc(hidden)]
pub fn threads_the_clean_copy_drops(
clean: &[u8],
redline: &[u8],
already: &[RemovedComment],
deleted: &std::collections::HashSet<String>,
) -> Result<Vec<RemovedComment>, SettlementError> {
let invalid = |error: crate::comments::CommentError| {
SettlementError::new(error.code(), error.to_string())
};
let on_redline = crate::comments::list_comments(redline).map_err(invalid)?;
let on_clean = crate::comments::list_comments(clean).map_err(invalid)?;
let kept: std::collections::HashSet<u32> = on_clean.iter().map(|comment| comment.id).collect();
let dropped: std::collections::HashSet<u32> = on_redline
.iter()
.map(|comment| comment.id)
.filter(|id| !kept.contains(id))
.collect();
if dropped.is_empty() {
return Ok(Vec::new());
}
let named: std::collections::HashSet<u32> = already
.iter()
.filter_map(|comment| comment.id.strip_prefix('c')?.parse().ok())
.collect();
let mut threads = Vec::new();
for root in on_redline.iter().filter(|comment| {
dropped.contains(&comment.id)
&& !named.contains(&comment.id)
&& !comment
.parent
.is_some_and(|parent| dropped.contains(&parent))
}) {
let mut family = std::collections::HashSet::from([root.id]);
loop {
let before = family.len();
for comment in &on_redline {
if dropped.contains(&comment.id)
&& !family.contains(&comment.id)
&& comment
.parent
.is_some_and(|parent| family.contains(&parent))
{
family.insert(comment.id);
}
}
if family.len() == before {
break;
}
}
let replies = on_redline
.iter()
.filter(|comment| comment.id != root.id && family.contains(&comment.id))
.map(|comment| format!("c{}", comment.id))
.collect();
let why = match root.paragraph.as_deref() {
Some(paragraph) if deleted.contains(paragraph) => {
format!("anchor removed by the plan's deletion of {paragraph}")
}
Some(paragraph) => {
format!("anchor removed by the plan's deletion of its text in {paragraph}")
}
None => "anchor removed by the plan's deletions".to_string(),
};
threads.push(RemovedComment {
id: format!("c{}", root.id),
author: root.author.clone(),
replies,
why,
decision: None,
});
}
Ok(threads)
}