1use serde::{Deserialize, Serialize};
8
9#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
11pub struct RemovedComment {
12 pub id: String,
14 pub author: String,
16 pub replies: Vec<String>,
18 #[serde(default)]
21 pub why: String,
22 #[serde(skip)]
24 pub decision: Option<String>,
25}
26
27#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
29pub struct KeptComment {
30 pub id: String,
32 pub replies: Vec<String>,
34 pub anchor: String,
36}
37
38use crate::revision_processor::Resolution;
39
40#[derive(Debug)]
45#[doc(hidden)]
46pub struct SettlementError {
47 pub code: String,
48 pub message: String,
49}
50
51impl SettlementError {
52 fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
53 Self {
54 code: code.into(),
55 message: message.into(),
56 }
57 }
58}
59
60impl std::fmt::Display for SettlementError {
61 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
62 write!(f, "{}", self.message)
63 }
64}
65
66#[derive(Clone, Debug, PartialEq, Eq)]
69struct Pass {
70 resolution: Resolution,
71 settled: Option<Vec<String>>,
72}
73
74#[derive(Debug, Default, PartialEq, Eq)]
75#[doc(hidden)]
76pub struct AnchorChanges {
77 pub removed: Vec<String>,
78 pub kept: Vec<String>,
79 passes: std::collections::HashMap<String, Pass>,
80}
81
82impl AnchorChanges {
83 pub fn extend(
86 &mut self,
87 removed: Vec<String>,
88 kept: Vec<String>,
89 resolution: Resolution,
90 settled: Option<&[String]>,
91 ) {
92 let pass = Pass {
93 resolution,
94 settled: settled.map(<[String]>::to_vec),
95 };
96 for id in &removed {
97 self.passes.insert(id.clone(), pass.clone());
98 }
99 self.removed.extend(removed);
100 self.kept.extend(kept);
101 self.kept.retain(|id| !self.removed.contains(id));
103 }
104
105 pub fn records(
106 &self,
107 source: &[u8],
108 ) -> Result<(Vec<RemovedComment>, Vec<KeptComment>), SettlementError> {
109 assert!(
110 self.removed.iter().all(|id| !self.kept.contains(id)),
111 "a comment cannot be both removed and kept"
112 );
113 if self.removed.is_empty() && self.kept.is_empty() {
114 return Ok((Vec::new(), Vec::new()));
115 }
116 let comments = crate::comments::list_comments(source)
117 .map_err(|e| SettlementError::new("INVALID_DOCUMENT", e.to_string()))?;
118 let groups = |ids: &[String]| {
119 let wanted: std::collections::HashSet<u32> =
121 ids.iter().filter_map(|id| id.parse().ok()).collect();
122 comments
123 .iter()
124 .filter(|c| {
125 wanted.contains(&c.id) && !c.parent.is_some_and(|p| wanted.contains(&p))
126 })
127 .map(|root| {
128 let mut family = vec![root.id];
129 loop {
130 let before = family.len();
131 for c in &comments {
132 if wanted.contains(&c.id)
133 && !family.contains(&c.id)
134 && c.parent.is_some_and(|p| family.contains(&p))
135 {
136 family.push(c.id);
137 }
138 }
139 if before == family.len() {
140 break;
141 }
142 }
143 let replies = comments
144 .iter()
145 .filter(|c| c.id != root.id && family.contains(&c.id))
146 .map(|c| format!("c{}", c.id))
147 .collect::<Vec<String>>();
148 (root, replies)
149 })
150 .collect::<Vec<_>>()
151 };
152 let (holders, wholes) = if self.removed.is_empty() {
153 (Vec::new(), std::collections::HashMap::new())
154 } else {
155 let invalid = |e: crate::changes::ChangeError| {
156 SettlementError::new("INVALID_DOCUMENT", e.to_string())
157 };
158 (
159 crate::changes::list_changes_tolerant(source).map_err(invalid)?,
160 crate::changes::member_wholes(source).map_err(invalid)?,
161 )
162 };
163 let passes: std::collections::HashMap<u32, _> = self
166 .passes
167 .iter()
168 .filter_map(|(raw, pass)| Some((raw.parse::<u32>().ok()?, pass)))
169 .collect();
170 let removed = groups(&self.removed)
171 .into_iter()
172 .map(|(c, replies)| {
173 let pass = passes
174 .get(&c.id)
175 .expect("every removed thread is recorded with its pass");
176 let id = format!("c{}", c.id);
177 let thread: Vec<String> = std::iter::once(id.clone())
178 .chain(replies.iter().cloned())
179 .collect();
180 let why = crate::changes::why_removed(
181 &holders,
182 &thread,
183 pass.resolution,
184 pass.settled.as_deref(),
185 &wholes,
186 );
187 RemovedComment {
188 id,
189 author: c.author.clone(),
190 replies,
191 why,
192 decision: Some(
193 match pass.resolution {
194 Resolution::Accept => "acceptance",
195 Resolution::Reject => "rejection",
196 }
197 .into(),
198 ),
199 }
200 })
201 .collect();
202 let kept = groups(&self.kept)
203 .into_iter()
204 .map(|(c, replies)| KeptComment {
205 id: format!("c{}", c.id),
206 replies,
207 anchor: "empty".into(),
208 })
209 .collect();
210 Ok((removed, kept))
211 }
212}
213
214#[doc(hidden)]
220pub fn threads_the_clean_copy_drops(
221 clean: &[u8],
222 redline: &[u8],
223 already: &[RemovedComment],
224 deleted: &std::collections::HashSet<String>,
225) -> Result<Vec<RemovedComment>, SettlementError> {
226 let invalid = |error: crate::comments::CommentError| {
227 SettlementError::new(error.code(), error.to_string())
228 };
229 let on_redline = crate::comments::list_comments(redline).map_err(invalid)?;
230 let on_clean = crate::comments::list_comments(clean).map_err(invalid)?;
231 let kept: std::collections::HashSet<u32> = on_clean.iter().map(|comment| comment.id).collect();
232 let dropped: std::collections::HashSet<u32> = on_redline
233 .iter()
234 .map(|comment| comment.id)
235 .filter(|id| !kept.contains(id))
236 .collect();
237 if dropped.is_empty() {
238 return Ok(Vec::new());
239 }
240 let named: std::collections::HashSet<u32> = already
241 .iter()
242 .filter_map(|comment| comment.id.strip_prefix('c')?.parse().ok())
243 .collect();
244 let mut threads = Vec::new();
245 for root in on_redline.iter().filter(|comment| {
246 dropped.contains(&comment.id)
247 && !named.contains(&comment.id)
248 && !comment
249 .parent
250 .is_some_and(|parent| dropped.contains(&parent))
251 }) {
252 let mut family = std::collections::HashSet::from([root.id]);
253 loop {
254 let before = family.len();
255 for comment in &on_redline {
256 if dropped.contains(&comment.id)
257 && !family.contains(&comment.id)
258 && comment
259 .parent
260 .is_some_and(|parent| family.contains(&parent))
261 {
262 family.insert(comment.id);
263 }
264 }
265 if family.len() == before {
266 break;
267 }
268 }
269 let replies = on_redline
270 .iter()
271 .filter(|comment| comment.id != root.id && family.contains(&comment.id))
272 .map(|comment| format!("c{}", comment.id))
273 .collect();
274 let why = match root.paragraph.as_deref() {
275 Some(paragraph) if deleted.contains(paragraph) => {
276 format!("anchor removed by the plan's deletion of {paragraph}")
277 }
278 Some(paragraph) => {
279 format!("anchor removed by the plan's deletion of its text in {paragraph}")
280 }
281 None => "anchor removed by the plan's deletions".to_string(),
282 };
283 threads.push(RemovedComment {
284 id: format!("c{}", root.id),
285 author: root.author.clone(),
286 replies,
287 why,
288 decision: None,
289 });
290 }
291 Ok(threads)
292}