1pub 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
32const TIMEOUT: Duration = Duration::from_secs(5);
35
36static SETTINGS: OnceLock<(bool, Duration)> = OnceLock::new();
38
39pub fn configure(enabled: bool, timeout: Duration) {
43 let _ = SETTINGS.set((enabled, timeout));
44}
45const PAGE: &str = "100";
47const TRAILS: &str = "100";
49
50#[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#[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#[derive(Debug, Clone, Default)]
103pub struct Findings {
104 pub findings: Vec<Finding>,
105 pub incomplete: bool,
107}
108
109pub struct Entire {
111 timeout: Duration,
112 reads: Mutex<HashMap<Vec<String>, Result<Value, String>>>,
113}
114
115pub 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 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 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 Err(e) if e.contains("not onboarded") => return Ok(None),
173 Err(e) => return Err(e),
174 }
175 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 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 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 pub fn output(&self, args: &[&str]) -> Result<String, String> {
251 self.run(args).map_err(|e| e.message())
252 }
253
254 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 fn run(&self, args: &[&str]) -> Result<String, Run> {
277 let mut child = Command::new("entire")
278 .args(args)
279 .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
340pub 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
357enum 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}