1use serde::{Deserialize, Serialize};
8
9use super::{EditError, Transaction, v2::Target};
10use crate::namespaces::W;
11use crate::result::NextAction;
12use crate::xmllinq::NodeId;
13
14pub(super) const INSERTION_SIDE_PREFIX: &str = "requested insertion side cannot be preserved: ";
17
18#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
20#[serde(rename_all = "snake_case")]
21pub enum RevisionSyntax {
22 #[default]
24 V1Plan,
25 V2Plan,
27 LegacyFlags,
29 TypedAction,
31}
32
33#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
34struct Revision {
35 target: Target,
36 kind: String,
37 author: String,
38 accept: String,
39 reject: String,
40}
41
42#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
44pub struct RevisionRefusal {
45 reason: String,
46 revisions: Vec<Revision>,
47 syntax: RevisionSyntax,
48 #[serde(skip)]
51 keep_others: bool,
52 #[serde(skip)]
54 actor: String,
55}
56
57impl RevisionRefusal {
58 pub(super) fn new(tx: &Transaction<'_>, reason: &str, nodes: &[NodeId]) -> Self {
59 let dom = &tx.opened.dom;
60 let mut revisions = Vec::new();
61 for &node in nodes {
62 let ancestors = dom.ancestors(node, None);
63 let story = tx
64 .stories
65 .iter()
66 .find(|s| ancestors.contains(&s.root))
67 .expect("a blocking revision belongs to a loaded story");
68 let pair = super::for_edit::revision_pair(dom, node, &story.id, &story.part);
69 let target = Target {
70 short_id: pair.short_id,
71 long_id: pair.long_id,
72 };
73 if revisions.iter().any(|r: &Revision| r.target == target) {
74 continue;
75 }
76 let local = dom
77 .name(node)
78 .expect("revision element")
79 .local_name()
80 .to_string();
81 let mark = dom.parent(node).is_some_and(|rpr| {
82 dom.name_is(rpr, &W::r_pr())
83 && dom
84 .parent(rpr)
85 .is_some_and(|ppr| dom.name_is(ppr, &W::p_pr()))
86 });
87 let (kind, accept, reject) = match (local.as_str(), mark) {
88 ("ins", true) => (
89 "insertion",
90 "keeps the proposed paragraph break",
91 "removes the proposed paragraph break",
92 ),
93 ("ins", false) => (
94 "insertion",
95 "keeps the proposed content as plain text",
96 "removes the proposed content",
97 ),
98 ("del", true) => (
99 "deletion",
100 "removes the deleted paragraph break",
101 "restores the deleted paragraph break",
102 ),
103 ("del", false) => (
104 "deletion",
105 "removes the deleted content",
106 "restores the deleted content",
107 ),
108 ("moveFrom" | "moveTo", _) => (
109 "move",
110 "keeps the moved content at its destination",
111 "restores the moved content at its origin",
112 ),
113 _ => (
114 "formatting",
115 "keeps the proposed formatting",
116 "restores the previous formatting",
117 ),
118 };
119 revisions.push(Revision {
120 target,
121 kind: kind.into(),
122 author: dom.attribute(node, &W::author()).unwrap_or_default().into(),
123 accept: accept.into(),
124 reject: reject.into(),
125 });
126 }
127 Self {
128 reason: reason.into(),
129 revisions,
130 syntax: tx.syntax.revision(),
132 keep_others: tx.plan.others.keeps(),
133 actor: tx.plan.author.clone(),
134 }
135 }
136
137 fn foreign(&self, author: &str) -> bool {
140 author != self.actor
141 }
142
143 fn effect(&self, revision: &Revision, accept: bool) -> String {
144 if !accept && revision.kind == "deletion" && self.foreign(&revision.author) {
147 "rejecting erases their change".to_string()
148 } else if accept {
149 revision.accept.clone()
150 } else {
151 revision.reject.clone()
152 }
153 }
154
155 fn consequence(&self, accept: bool) -> String {
156 self.revisions
157 .iter()
158 .map(|r| {
159 let effect = self.effect(r, accept);
160 if self.revisions.len() == 1 {
161 effect
162 } else {
163 format!("{effect} for {}", r.target.short_id)
164 }
165 })
166 .collect::<Vec<_>>()
167 .join(" and ")
168 }
169}
170
171impl EditError {
172 #[must_use]
174 pub fn with_revision_syntax(mut self, syntax: RevisionSyntax) -> Self {
175 for refusal in self.revision_refusals.iter_mut() {
178 refusal.syntax = syntax;
179 }
180 self
181 }
182
183 #[must_use]
186 pub fn revision_next_actions(&self, source_path: &str, source_digest: &str) -> Vec<NextAction> {
187 let header = self.message.lines().next().unwrap_or_default();
194 let header = header.strip_prefix(INSERTION_SIDE_PREFIX).unwrap_or(header);
195 let Some(refusal) = self.revision_refusals.first().filter(|refusal| {
196 refusal.revisions.first().is_some_and(|first| {
197 header.starts_with(&format!("{} {}", refusal.reason, first.target.short_id))
198 }) && refusal
199 .revisions
200 .iter()
201 .all(|r| self.message.contains(&r.target.short_id))
202 }) else {
203 return Vec::new();
204 };
205 let all_foreign = refusal.revisions.iter().all(|r| refusal.foreign(&r.author));
206 let any_foreign = refusal.revisions.iter().any(|r| refusal.foreign(&r.author));
207 let keeping = if all_foreign {
211 if refusal.revisions.iter().all(|r| r.kind == "deletion") {
212 Some("restore")
213 } else if refusal.revisions.iter().all(|r| r.kind == "insertion") {
214 Some("strike")
215 } else {
216 None
217 }
218 } else {
219 None
220 };
221 let mut actions = Vec::new();
222 if let Some(flag) = keeping {
223 let mut argv = vec!["jubarte".into(), "edit".into(), source_path.into()];
224 for revision in &refusal.revisions {
225 argv.extend([
226 "-p".into(),
227 revision.target.short_id.clone(),
228 format!("--{flag}"),
229 ]);
230 }
231 argv.extend(["--author".into(), refusal.actor.clone()]);
232 if refusal.keep_others {
233 argv.push("--keep-others".into());
234 }
235 argv.extend(["-o".into(), "-".into()]);
236 let purpose = if flag == "restore" {
237 "their deletion stays, your insertion shows"
238 } else {
239 "their insertion stays, your deletion shows"
240 };
241 actions.push(NextAction::new(argv).with_purpose(purpose));
242 }
243 if refusal.keep_others && any_foreign {
245 return actions;
246 }
247 actions.extend([true, false].into_iter().map(|accept| {
248 let key = if accept { "accept" } else { "reject" };
249 let mut argv = vec!["jubarte".into(), "edit".into(), "template".into(), source_path.into(),
250 "--expect-sha256".into(), source_digest.into()];
251 for revision in &refusal.revisions {
252 argv.extend([format!("--{key}-change"), revision.target.short_id.clone()]);
253 }
254 argv.extend(["-o".into(), "-".into()]);
255 let action = NextAction::new(argv).with_purpose(format!(
256 "{}; generate a fresh plan and deliberately author the refreshed edit before applying it",
257 refusal.consequence(accept)
258 ));
259 if any_foreign { action.with_destructive() } else { action }
260 }));
261 actions
262 }
263}
264
265impl Transaction<'_> {
266 pub(super) fn attach_revision_refusal(&self, mut error: EditError) -> EditError {
267 if let Some(refusal) = self.revision_refusal.take() {
268 let mut refusals = error.revision_refusals.into_vec();
269 refusals.push(refusal);
270 error.revision_refusals = refusals.into_boxed_slice();
271 }
272 error
273 }
274}