Skip to main content

jouet_github/pr/threads/
write.rs

1//! Replying to, resolving and unresolving threads.
2//!
3//! Every request is checked against the PR before anything is posted, so a
4//! bad ID fails the whole call with nothing written. A thread someone already
5//! resolved, often a review bot after a push, still takes a reply and stays
6//! resolved. Writes then go one at a time and stop at the first failure. A
7//! retry is safe: a thread already resolved is not resolved again, and a reply
8//! whose exact text is already the thread's last comment from the same user
9//! is not posted again.
10
11use super::{PrThreads, Thread, same_login};
12use crate::host::Host;
13use jouet_output::exit::Exit;
14use serde::{Deserialize, Deserializer, Serialize};
15
16/// What to do to one thread.
17#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
18#[serde(deny_unknown_fields)]
19pub struct Entry {
20    #[serde(deserialize_with = "thread_id")]
21    pub id: u64,
22    #[serde(default)]
23    pub reply: Option<String>,
24    #[serde(default)]
25    pub resolve: bool,
26    #[serde(skip)]
27    pub unresolve: bool,
28    /// Named among `resolve`'s or `unresolve`'s arguments, where a PR written
29    /// after the IDs (`resolve 4435734278 1098`) arrives as one: then an ID
30    /// that is the PR's own number and no thread's is the PR. An `apply`
31    /// file names threads only, so there it is an unknown thread.
32    #[serde(skip)]
33    pub among_args: bool,
34}
35
36/// A thread ID as a JSON number or a string of digits.
37fn thread_id<'de, D: Deserializer<'de>>(d: D) -> Result<u64, D::Error> {
38    #[derive(Deserialize)]
39    #[serde(untagged)]
40    enum Id {
41        Number(u64),
42        Text(String),
43    }
44    match Id::deserialize(d)? {
45        Id::Number(n) => Ok(n),
46        Id::Text(s) => parse_id(&s)
47            .ok_or_else(|| serde::de::Error::custom(format!("`{s}` is not a thread ID"))),
48    }
49}
50
51/// A thread ID: the database ID of its first comment.
52pub fn parse_id(s: &str) -> Option<u64> {
53    (!s.is_empty() && s.bytes().all(|b| b.is_ascii_digit()))
54        .then(|| s.parse().ok())
55        .flatten()
56        .filter(|&n| n > 0)
57}
58
59/// Reads an `apply` file: a JSON list of `{id, reply?, resolve?}`.
60pub fn parse_apply(text: &str) -> Result<Vec<Entry>, String> {
61    let entries: Vec<Entry> = serde_json::from_str(text).map_err(|e| format!("apply file: {e}"))?;
62    if entries.is_empty() {
63        return Err("apply file: the list is empty".into());
64    }
65    for (i, e) in entries.iter().enumerate() {
66        if e.reply.is_none() && !e.resolve {
67            return Err(format!("apply file: {} neither replies nor resolves", e.id));
68        }
69        if e.reply.as_deref().is_some_and(|r| r.trim().is_empty()) {
70            return Err(format!("apply file: the reply to {} is empty", e.id));
71        }
72        if entries[..i].iter().any(|o| o.id == e.id) {
73            return Err(format!("apply file: {} is listed twice", e.id));
74        }
75    }
76    Ok(entries)
77}
78
79pub struct Options {
80    /// Appended to every reply after a blank line.
81    pub footer: Option<String>,
82    /// The short HEAD SHA that `{sha}` expands to, when there is one.
83    pub sha: Option<String>,
84    /// Leave threads already resolved alone, posting nothing to them.
85    pub ignore_resolved: bool,
86}
87
88/// What happened to one thread, or in a dry run what would.
89#[derive(Debug, Default, Serialize)]
90pub struct Outcome {
91    pub id: u64,
92    #[serde(skip_serializing_if = "is_false")]
93    pub replied: bool,
94    /// The reply was already the thread's last comment, so it was not
95    /// posted again.
96    #[serde(skip_serializing_if = "is_false")]
97    pub already_replied: bool,
98    /// The thread was resolved before: the reply went in, and it stays
99    /// resolved.
100    #[serde(skip_serializing_if = "is_false")]
101    pub already_resolved: bool,
102    #[serde(skip_serializing_if = "is_false")]
103    pub resolved: bool,
104    #[serde(skip_serializing_if = "is_false")]
105    pub unresolved: bool,
106    /// The reply's URL.
107    #[serde(skip_serializing_if = "Option::is_none")]
108    pub url: Option<String>,
109    /// In a dry run, the reply exactly as it would be posted.
110    #[serde(skip_serializing_if = "Option::is_none")]
111    pub body: Option<String>,
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub skipped: Option<String>,
114    #[serde(skip_serializing_if = "Option::is_none")]
115    pub failed: Option<String>,
116    #[serde(skip)]
117    post: Option<String>,
118    #[serde(skip)]
119    resolve: bool,
120    #[serde(skip)]
121    unresolve: bool,
122    #[serde(skip)]
123    uses_sha: bool,
124}
125
126fn is_false(b: &bool) -> bool {
127    !*b
128}
129
130impl Outcome {
131    /// Whether this will post a reply that names `{sha}`.
132    pub fn posts_sha(&self) -> bool {
133        self.uses_sha && self.post.is_some()
134    }
135
136    /// Whether this will resolve or unresolve the thread.
137    pub fn changes_resolution(&self) -> bool {
138        self.skipped.is_none() && (self.resolve || self.unresolve)
139    }
140}
141
142#[derive(Debug, PartialEq, Eq)]
143pub struct PlanError {
144    pub exit: Exit,
145    pub message: String,
146    pub hint: Option<String>,
147}
148
149/// The entries with each ID as the thread it means. A reply's comment ID
150/// stands for the thread it is in. A number among the arguments that is the
151/// PR's own and no thread's was the PR, written after the IDs (`resolve
152/// 4435734278 1098`), so it is dropped (see [`Entry::among_args`]).
153fn addressed(entries: &[Entry], pr: &PrThreads) -> Result<Vec<Entry>, PlanError> {
154    let mut out: Vec<Entry> = Vec::new();
155    for e in entries {
156        let thread = pr
157            .threads
158            .iter()
159            .find(|t| t.id == e.id || t.comments.iter().any(|c| c.id == e.id));
160        let id = match thread {
161            Some(t) => t.id,
162            None if e.among_args && e.id == pr.number => continue,
163            None => e.id,
164        };
165        if out.iter().any(|o| o.id == id) {
166            return Err(PlanError {
167                exit: Exit::Usage,
168                message: format!("thread {id} is named twice; nothing was posted"),
169                hint: Some("a reply's ID stands for the thread it is in".into()),
170            });
171        }
172        out.push(Entry { id, ..e.clone() });
173    }
174    if out.is_empty() {
175        return Err(PlanError {
176            exit: Exit::Usage,
177            message: format!(
178                "{} is the PR, not a thread; name at least one thread ID",
179                pr.number
180            ),
181            hint: Some(
182                "a thread's ID is its first comment's ID, as `jouet pr threads --all` lists".into(),
183            ),
184        });
185    }
186    Ok(out)
187}
188
189/// Checks every entry against the PR and works out what is left to do.
190pub fn plan(entries: &[Entry], pr: &PrThreads, o: &Options) -> Result<Vec<Outcome>, PlanError> {
191    let find = |id: u64| pr.threads.iter().find(|t| t.id == id);
192    let entries = &addressed(entries, pr)?;
193    let unknown: Vec<String> = entries
194        .iter()
195        .filter(|e| find(e.id).is_none())
196        .map(|e| e.id.to_string())
197        .collect();
198    if !unknown.is_empty() {
199        let noun = if unknown.len() == 1 {
200            "thread"
201        } else {
202            "threads"
203        };
204        return Err(PlanError {
205            exit: Exit::NotFound,
206            message: format!(
207                "no review {noun} {} on {}#{}; nothing was posted",
208                unknown.join(", "),
209                pr.repo,
210                pr.number
211            ),
212            hint: Some(
213                "a thread's ID is its first comment's ID, as `jouet pr threads --all` lists".into(),
214            ),
215        });
216    }
217    let mut outcomes = Vec::new();
218    for e in entries {
219        let t = find(e.id).expect("unknown IDs were rejected");
220        let mut out = Outcome {
221            id: e.id,
222            ..Outcome::default()
223        };
224        if let Some(reply) = &e.reply {
225            out.uses_sha = reply.contains("{sha}");
226            let text = reply_text(reply, o)?;
227            match last_reply(t, &pr.viewer, &text) {
228                Some(url) => {
229                    out.already_replied = true;
230                    out.url = Some(url.to_string());
231                }
232                None => out.post = Some(text),
233            }
234        }
235        if e.unresolve {
236            if t.resolved {
237                out.unresolve = true;
238            } else {
239                out.skipped = Some("not resolved".into());
240            }
241        } else if t.resolved && (out.post.is_some() || e.resolve) {
242            // A reviewer, often a bot after a push, resolved it already: a
243            // reply still goes in, and the thread stays resolved.
244            if out.post.is_some() && !o.ignore_resolved {
245                out.already_resolved = true;
246            } else {
247                out.skipped = Some("already resolved".into());
248                out.post = None;
249            }
250        } else if out.post.is_none() && !e.resolve {
251            out.skipped = Some("reply already posted".into());
252        } else {
253            out.resolve = e.resolve;
254        }
255        outcomes.push(out);
256    }
257    Ok(outcomes)
258}
259
260/// The reply as it will be posted: `{sha}` expanded, then the footer.
261fn reply_text(reply: &str, o: &Options) -> Result<String, PlanError> {
262    let mut text = reply.trim_end().to_string();
263    if text.contains("{sha}") {
264        let Some(sha) = &o.sha else {
265            return Err(PlanError {
266                exit: Exit::Precondition,
267                message: "a reply uses {sha}, but there is no git commit here for it to name; nothing was posted".into(),
268                hint: Some("run jouet in the PR's checkout".into()),
269            });
270        };
271        text = text.replace("{sha}", sha);
272    }
273    if let Some(footer) = &o.footer {
274        text = format!("{text}\n\n{footer}");
275    }
276    Ok(text)
277}
278
279/// The URL of the thread's last comment when the viewer wrote it and it
280/// reads exactly `text`.
281fn last_reply<'a>(t: &'a Thread, viewer: &str, text: &str) -> Option<&'a str> {
282    let norm = |s: &str| s.replace("\r\n", "\n").trim().to_string();
283    let last = t.comments.last()?;
284    (!viewer.is_empty() && same_login(viewer, &last.author) && norm(&last.body) == norm(text))
285        .then_some(last.url.as_str())
286}
287
288/// Fills in a dry run's outcomes with what would happen.
289pub fn dry_run(outcomes: &mut [Outcome]) {
290    for o in outcomes {
291        o.replied = o.post.is_some();
292        o.body = o.post.take();
293        o.resolved = o.resolve;
294        o.unresolved = o.unresolve;
295    }
296}
297
298/// Carries out the plan through the PR's host, stopping at the first
299/// failure. Returns whether every write succeeded.
300pub fn execute(host: &mut dyn Host, pr: &PrThreads, outcomes: &mut [Outcome]) -> bool {
301    let mut ok = true;
302    for o in outcomes {
303        if o.skipped.is_some() {
304            continue;
305        }
306        if !ok {
307            o.failed = Some("not attempted after an earlier failure".into());
308            continue;
309        }
310        if let Err(e) = apply(host, pr, o) {
311            o.failed = Some(e);
312            ok = false;
313        }
314    }
315    ok
316}
317
318fn apply(host: &mut dyn Host, pr: &PrThreads, o: &mut Outcome) -> Result<(), String> {
319    let thread = pr
320        .threads
321        .iter()
322        .find(|t| t.id == o.id)
323        .ok_or("the thread is gone")?;
324    if let Some(body) = o.post.take() {
325        o.url = Some(host.reply(pr, thread, &body)?);
326        o.replied = true;
327    }
328    if o.resolve {
329        host.set_resolved(pr, thread, true)?;
330        o.resolved = true;
331    }
332    if o.unresolve {
333        host.set_resolved(pr, thread, false)?;
334        o.unresolved = true;
335    }
336    Ok(())
337}