Skip to main content

jouet_github/entire/
mod.rs

1//! Entire (entire.io) on top of a PR: its "Entire Gates" check, and the
2//! review findings on the PR's trail.
3//!
4//! Entire sits beside the forge, not inside it. The gates are read from the
5//! check run's summary with the forge's own token; the findings, and how far
6//! behind the branch is, come from the `entire` CLI. That CLI is used only
7//! when it is on PATH and logged in (`entire auth status`); otherwise
8//! commands carry on without it and say why only in `--json`. Every call has
9//! a timeout, and a read is made once per process however many PRs or
10//! commands ask for it, so one command never asks twice about the same head.
11//!
12//! The CLI's help is the reference for what is called here: `entire
13//! agent-help trail` and `entire agent-help trail finding`. Credentials
14//! never pass through jouet: it runs `entire`, which reads its own.
15
16pub mod findings;
17pub mod gates;
18
19pub use findings::{Brief, Finding, Trail};
20pub use gates::{CHECK, Gate, Gates};
21
22use crate::forge::Forge;
23use crate::pr::target::Repo;
24use serde::Serialize;
25use serde_json::Value;
26use std::collections::HashMap;
27use std::io::Read;
28use std::process::{Command, Stdio};
29use std::sync::{Mutex, OnceLock};
30use std::time::{Duration, Instant};
31
32/// How long one `entire` call may take when jouet's settings were not
33/// passed in: `[entire] timeout_ms`'s default.
34const TIMEOUT: Duration = Duration::from_secs(5);
35
36/// jouet's `[entire]` settings, passed in by [`configure`].
37static SETTINGS: OnceLock<(bool, Duration)> = OnceLock::new();
38
39/// Whether jouet may run `entire` at all, and how long one call may take:
40/// jouet's `[entire] enabled` and `timeout_ms` settings (`JOUET_ENTIRE`,
41/// `JOUET_ENTIRE_TIMEOUT_MS`). Set once, before anything probes.
42pub fn configure(enabled: bool, timeout: Duration) {
43    let _ = SETTINGS.set((enabled, timeout));
44}
45/// Findings per page.
46const PAGE: &str = "100";
47/// Trails listed when looking for a branch's trail by name.
48const TRAILS: &str = "100";
49
50/// Whether Entire could be asked, for `--json`: `{available: true}`, or
51/// `{available: false, reason}`.
52#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
53pub struct Availability {
54    pub available: bool,
55    #[serde(skip_serializing_if = "Option::is_none")]
56    pub reason: Option<String>,
57}
58
59impl Availability {
60    pub fn of(probed: &Result<Entire, String>) -> Self {
61        Self {
62            available: probed.is_ok(),
63            reason: probed.as_ref().err().cloned(),
64        }
65    }
66
67    pub fn unavailable(reason: impl Into<String>) -> Self {
68        Self {
69            available: false,
70            reason: Some(reason.into()),
71        }
72    }
73}
74
75/// What to do with a finding.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum Change {
78    Resolve,
79    Dismiss,
80    Reopen,
81}
82
83impl Change {
84    pub fn verb(self) -> &'static str {
85        match self {
86            Self::Resolve => "resolve",
87            Self::Dismiss => "dismiss",
88            Self::Reopen => "reopen",
89        }
90    }
91
92    pub fn done(self) -> &'static str {
93        match self {
94            Self::Resolve => "resolved",
95            Self::Dismiss => "dismissed",
96            Self::Reopen => "reopened",
97        }
98    }
99}
100
101/// Findings read from a trail, and whether that is all of them.
102#[derive(Debug, Clone, Default)]
103pub struct Findings {
104    pub findings: Vec<Finding>,
105    /// Entire said more pages follow but gave no way to fetch them.
106    pub incomplete: bool,
107}
108
109/// The `entire` CLI, found and logged in.
110pub struct Entire {
111    timeout: Duration,
112    reads: Mutex<HashMap<Vec<String>, Result<Value, String>>>,
113}
114
115/// Entire's selector for a repository: `gh/OWNER/NAME` on GitHub,
116/// `et/OWNER/NAME` on Entire's own forge (which takes no clone URL), else
117/// its clone URL, which Entire takes for other forges.
118pub fn selector(repo: &Repo) -> String {
119    match repo.host.as_deref() {
120        None => format!("gh/{repo}"),
121        Some(_) if repo.forge() == Some(Forge::Entire) => format!("et/{repo}"),
122        Some(host) => format!("https://{host}/{repo}.git"),
123    }
124}
125
126impl Entire {
127    /// `entire`, if it is on PATH and logged in; otherwise why not, in words
128    /// fit for `entire: {available: false, reason}`.
129    pub fn probe() -> Result<Self, String> {
130        let (enabled, timeout) = SETTINGS.get().copied().unwrap_or((true, TIMEOUT));
131        if !enabled {
132            return Err("turned off by [entire] enabled = false (JOUET_ENTIRE)".into());
133        }
134        let entire = Self {
135            timeout,
136            reads: Mutex::new(HashMap::new()),
137        };
138        let status = match entire.run(&["auth", "status", "--json"]) {
139            Ok(status) => status,
140            Err(Run::Missing) => return Err("entire is not on PATH".into()),
141            Err(e) => return Err(format!("entire auth status: {}", e.message())),
142        };
143        let doc: Value = serde_json::from_str(&status)
144            .map_err(|_| "entire auth status --json printed no JSON".to_string())?;
145        if doc["logged_in"].as_bool() == Some(true) {
146            Ok(entire)
147        } else {
148            Err("entire is not logged in (see `entire auth status`)".into())
149        }
150    }
151
152    /// The trail for a PR: the one the gates check links to when there is
153    /// one, else the one tracking the head branch (or, once merged, the one
154    /// that tracked it). `None` when no trail does.
155    pub fn trail(
156        &self,
157        repo: &Repo,
158        linked: Option<u64>,
159        branch: &str,
160    ) -> Result<Option<Trail>, String> {
161        let repo = selector(repo);
162        if let Some(n) = linked {
163            let doc = self.read(&["trail", "show", &n.to_string(), "--json", "--repo", &repo])?;
164            return Ok(Trail::parse(&doc));
165        }
166        match self.read(&[
167            "trail", "show", "--branch", branch, "--json", "--repo", &repo,
168        ]) {
169            Ok(doc) => return Ok(Trail::parse(&doc)),
170            Err(e) if e.contains("no trail") => {}
171            // A repository Entire does not know has no trails.
172            Err(e) if e.contains("not onboarded") => return Ok(None),
173            Err(e) => return Err(e),
174        }
175        // A merged trail keeps its branch only as `original_branch`.
176        let list = self.read(&[
177            "trail", "list", "--status", "any", "--json", "-n", TRAILS, "--repo", &repo,
178        ])?;
179        let mut matching: Vec<&Value> = list
180            .as_array()
181            .into_iter()
182            .flatten()
183            .filter(|t| t["branch"] == branch || t["original_branch"] == branch)
184            .collect();
185        matching.sort_by_key(|t| t["updated_at"].as_str().unwrap_or_default().to_string());
186        Ok(matching.last().and_then(|t| Trail::parse(t)))
187    }
188
189    /// A trail's findings: open and current ones, or with `all` every one,
190    /// resolved, dismissed and stale included.
191    pub fn findings(&self, repo: &Repo, trail: u64, all: bool) -> Result<Findings, String> {
192        let repo = selector(repo);
193        let trail = trail.to_string();
194        let mut args = vec![
195            "trail", "finding", "--trail", &trail, "--json", "-n", PAGE, "--repo", &repo,
196        ];
197        if all {
198            args.extend([
199                "--status",
200                "any",
201                "--freshness",
202                "any",
203                "--include-dismissed",
204            ]);
205        }
206        let mut out = Findings::default();
207        let mut cursor: Option<String> = None;
208        loop {
209            let mut page_args = args.clone();
210            if let Some(c) = &cursor {
211                page_args.extend(["--cursor", c.as_str()]);
212            }
213            let doc = self.read(&page_args)?;
214            let (page, more) = findings::parse(&doc)?;
215            out.findings.extend(page);
216            if !more {
217                return Ok(out);
218            }
219            let next = ["next_cursor", "nextCursor", "cursor"]
220                .iter()
221                .find_map(|k| doc[k].as_str().filter(|c| !c.is_empty()))
222                .map(str::to_string);
223            match next {
224                Some(next) if cursor.as_ref() != Some(&next) => cursor = Some(next),
225                _ => {
226                    out.incomplete = true;
227                    return Ok(out);
228                }
229            }
230        }
231    }
232
233    /// Resolves, dismisses or reopens a finding, recording `message` as the
234    /// reason.
235    pub fn change(
236        &self,
237        repo: &Repo,
238        trail: u64,
239        id: &str,
240        change: Change,
241        message: Option<&str>,
242    ) -> Result<(), String> {
243        let args = change_args(repo, trail, id, change, message);
244        let args: Vec<&str> = args.iter().map(String::as_str).collect();
245        self.run(&args).map(|_| ()).map_err(|e| e.message())
246    }
247
248    /// `entire ARGS`, uncached, returning what it printed: a write, or a
249    /// read that must see changes, as a wait's polls must.
250    pub fn output(&self, args: &[&str]) -> Result<String, String> {
251        self.run(args).map_err(|e| e.message())
252    }
253
254    /// A read, made once per process: `entire ARGS`, which prints one JSON
255    /// document.
256    pub fn read(&self, args: &[&str]) -> Result<Value, String> {
257        let key: Vec<String> = args.iter().map(|a| (*a).to_string()).collect();
258        if let Some(done) = self.reads.lock().ok().and_then(|r| r.get(&key).cloned()) {
259            return done;
260        }
261        let result = self.run(args).map_err(|e| e.message()).and_then(|out| {
262            serde_json::from_str(&out).map_err(|e| {
263                format!(
264                    "entire {} printed JSON jouet could not read: {e}",
265                    args[..2].join(" ")
266                )
267            })
268        });
269        if let Ok(mut reads) = self.reads.lock() {
270            reads.insert(key, result.clone());
271        }
272        result
273    }
274
275    /// Runs `entire ARGS` with no stdin and a deadline, returning stdout.
276    fn run(&self, args: &[&str]) -> Result<String, Run> {
277        let mut child = Command::new("entire")
278            .args(args)
279            // Plain prompts and no colour, should anything ask or paint.
280            .env("ACCESSIBLE", "1")
281            .env("NO_COLOR", "1")
282            .stdin(Stdio::null())
283            .stdout(Stdio::piped())
284            .stderr(Stdio::piped())
285            .spawn()
286            .map_err(|e| match e.kind() {
287                std::io::ErrorKind::NotFound => Run::Missing,
288                _ => Run::Failed(e.to_string()),
289            })?;
290        let mut out = child.stdout.take().expect("piped stdout");
291        let mut err = child.stderr.take().expect("piped stderr");
292        let out = std::thread::spawn(move || {
293            let mut s = String::new();
294            let _ = out.read_to_string(&mut s);
295            s
296        });
297        let err = std::thread::spawn(move || {
298            let mut s = String::new();
299            let _ = err.read_to_string(&mut s);
300            s
301        });
302        let deadline = Instant::now() + self.timeout;
303        let status = loop {
304            match child.try_wait() {
305                Ok(Some(status)) => break status,
306                Ok(None) if Instant::now() < deadline => {
307                    std::thread::sleep(Duration::from_millis(10));
308                }
309                Ok(None) => {
310                    let _ = child.kill();
311                    let _ = child.wait();
312                    return Err(Run::TimedOut(self.timeout));
313                }
314                Err(e) => return Err(Run::Failed(e.to_string())),
315            }
316        };
317        let (out, err) = (
318            out.join().unwrap_or_default(),
319            err.join().unwrap_or_default(),
320        );
321        if status.success() {
322            Ok(out)
323        } else {
324            let line = err
325                .lines()
326                .map(str::trim)
327                .find(|l| !l.is_empty())
328                .unwrap_or("")
329                .trim_start_matches("Error: ")
330                .to_string();
331            Err(Run::Failed(if line.is_empty() {
332                format!("exited with {status}")
333            } else {
334                line
335            }))
336        }
337    }
338}
339
340/// The arguments of `entire trail finding resolve|dismiss|reopen`.
341pub fn change_args(
342    repo: &Repo,
343    trail: u64,
344    id: &str,
345    change: Change,
346    message: Option<&str>,
347) -> Vec<String> {
348    let mut args: Vec<String> = ["trail", "finding", change.verb()].map(String::from).into();
349    args.extend([trail.to_string(), id.to_string()]);
350    if let Some(m) = message {
351        args.extend(["-m".into(), m.to_string()]);
352    }
353    args.extend(["--repo".into(), selector(repo)]);
354    args
355}
356
357/// How a run of `entire` went wrong.
358enum Run {
359    Missing,
360    TimedOut(Duration),
361    Failed(String),
362}
363
364impl Run {
365    fn message(&self) -> String {
366        match self {
367            Self::Missing => "entire is not on PATH".into(),
368            Self::TimedOut(t) if t.as_secs() == 0 => {
369                format!("entire took longer than {}ms", t.as_millis())
370            }
371            Self::TimedOut(t) => format!("entire took longer than {}s", t.as_secs()),
372            Self::Failed(m) => m.clone(),
373        }
374    }
375}
376
377#[cfg(test)]
378mod tests {
379    use super::*;
380
381    #[test]
382    fn a_repository_is_named_for_entire_by_its_forge() {
383        assert_eq!(selector(&Repo::parse("jdx/mise").unwrap()), "gh/jdx/mise");
384        assert_eq!(
385            selector(&Repo::parse("gitlab.com/group/sub/app").unwrap()),
386            "https://gitlab.com/group/sub/app.git"
387        );
388        assert_eq!(
389            selector(&Repo::parse("entire.com/jdx/notes").unwrap()),
390            "et/jdx/notes"
391        );
392    }
393}