1use super::Gate;
9use serde::{Deserialize, Serialize};
10use serde_json::Value;
11
12const TITLE_WIDTH: usize = 100;
14
15#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
16pub struct Finding {
17 pub id: String,
19 pub status: String,
21 #[serde(skip_serializing_if = "Option::is_none")]
22 pub severity: Option<String>,
23 #[serde(skip_serializing_if = "std::ops::Not::not")]
25 pub stale: bool,
26 #[serde(skip_serializing_if = "Option::is_none")]
27 pub path: Option<String>,
28 #[serde(skip_serializing_if = "Option::is_none")]
29 pub line: Option<u32>,
30 #[serde(skip_serializing_if = "Option::is_none")]
31 pub end_line: Option<u32>,
32 pub title: String,
34 pub body: String,
35 pub author: String,
37 pub created_at: String,
38 #[serde(skip_serializing_if = "Option::is_none")]
40 pub status_reason: Option<String>,
41}
42
43impl Finding {
44 pub fn is_open(&self) -> bool {
45 self.status == "open"
46 }
47
48 pub fn location(&self) -> String {
51 let Some(path) = &self.path else {
52 return "trail".into();
53 };
54 match (self.line, self.end_line) {
55 (Some(start), Some(end)) if end > start => format!("{path}:{start}-{end}"),
56 (Some(line), _) => format!("{path}:{line}"),
57 _ => path.clone(),
58 }
59 }
60}
61
62#[derive(Deserialize)]
63#[serde(rename_all = "camelCase")]
64struct RawFinding {
65 id: String,
66 status: String,
67 title: Option<String>,
68 #[serde(default)]
69 body: String,
70 severity: Option<String>,
71 status_reason: Option<String>,
72 stale_outcome: Option<String>,
73 #[serde(default)]
74 actor_id: String,
75 #[serde(default)]
76 created_at: String,
77 location: Option<RawLocation>,
78}
79
80#[derive(Deserialize)]
81#[serde(rename_all = "camelCase")]
82struct RawLocation {
83 file_path: Option<String>,
84 start_line: Option<u32>,
85 end_line: Option<u32>,
86}
87
88pub(crate) fn parse(doc: &Value) -> Result<(Vec<Finding>, bool), String> {
91 let raw: Vec<RawFinding> = Vec::deserialize(&doc["findings"])
92 .map_err(|e| format!("entire sent findings jouet could not read: {e}"))?;
93 let findings = raw
94 .into_iter()
95 .map(|r| {
96 let location = r.location.unwrap_or(RawLocation {
97 file_path: None,
98 start_line: None,
99 end_line: None,
100 });
101 Finding {
102 title: r
103 .title
104 .filter(|t| !t.trim().is_empty())
105 .unwrap_or_else(|| first_sentence(&r.body)),
106 id: r.id,
107 status: r.status,
108 severity: r.severity,
109 stale: r.stale_outcome.as_deref() == Some("stale"),
110 path: location.file_path.filter(|p| !p.is_empty()),
111 line: location.start_line,
112 end_line: location.end_line,
113 body: r.body,
114 author: r.actor_id,
115 created_at: r.created_at,
116 status_reason: r.status_reason,
117 }
118 })
119 .collect();
120 Ok((findings, doc["has_more"].as_bool().unwrap_or(false)))
121}
122
123fn first_sentence(body: &str) -> String {
125 let line = body.lines().find(|l| !l.trim().is_empty()).unwrap_or("");
126 let sentence = match line.find(". ") {
127 Some(i) => &line[..=i],
128 None => line,
129 }
130 .trim();
131 if sentence.chars().count() <= TITLE_WIDTH {
132 return sentence.to_string();
133 }
134 let head: String = sentence.chars().take(TITLE_WIDTH).collect();
135 let head = match head.rfind(' ') {
136 Some(i) if i >= TITLE_WIDTH / 2 => &head[..i],
137 _ => &head,
138 };
139 format!("{}...", head.trim_end())
140}
141
142const HANDLE: usize = 10;
144pub const PREFIX: &str = "entire:";
147
148pub fn handles(ids: &[&str]) -> Vec<String> {
151 ids.iter()
152 .map(|id| {
153 let mut n = HANDLE.min(id.len());
154 while n < id.len()
155 && ids
156 .iter()
157 .any(|other| other != id && other.get(..n) == id.get(..n))
158 {
159 n += 1;
160 }
161 format!("{PREFIX}{}", &id[..n])
162 })
163 .collect()
164}
165
166#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
168pub struct Brief {
169 pub id: String,
170 pub handle: String,
172 #[serde(skip_serializing_if = "Option::is_none")]
173 pub severity: Option<String>,
174 #[serde(skip_serializing_if = "Option::is_none")]
175 pub path: Option<String>,
176 #[serde(skip_serializing_if = "Option::is_none")]
177 pub line: Option<u32>,
178 pub title: String,
179 #[serde(skip)]
180 pub location: String,
181}
182
183impl Brief {
184 pub fn of(findings: &[Finding]) -> Vec<Self> {
186 let ids: Vec<&str> = findings.iter().map(|f| f.id.as_str()).collect();
187 findings
188 .iter()
189 .zip(handles(&ids))
190 .map(|(f, handle)| Self {
191 id: f.id.clone(),
192 handle,
193 severity: f.severity.clone(),
194 path: f.path.clone(),
195 line: f.line,
196 title: f.title.clone(),
197 location: f.location(),
198 })
199 .collect()
200 }
201}
202
203#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
205pub struct Trail {
206 pub number: u64,
207 pub url: String,
208 pub branch: String,
210 pub status: String,
212 #[serde(skip_serializing_if = "Vec::is_empty")]
214 pub gates: Vec<Gate>,
215}
216
217impl Trail {
218 pub(crate) fn parse(doc: &Value) -> Option<Self> {
219 let s = |v: &Value| v.as_str().filter(|s| !s.is_empty()).map(str::to_string);
220 Some(Self {
221 number: doc["number"].as_u64()?,
222 url: s(&doc["url"]).unwrap_or_default(),
223 branch: s(&doc["branch"])
224 .or_else(|| s(&doc["original_branch"]))
225 .unwrap_or_default(),
226 status: s(&doc["status"]).unwrap_or_default(),
227 gates: doc["mergeability"]["gates"]
228 .as_array()
229 .into_iter()
230 .flatten()
231 .filter(|g| g["blocking"] == true)
232 .filter_map(|g| {
233 Some(Gate {
234 gate: s(&g["gate_key"])?,
235 status: s(&g["status"])?,
236 reason: s(&g["rationale"]),
237 })
238 })
239 .collect(),
240 })
241 }
242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 const MISE_424: &str = include_str!("fixtures/finding-mise-424.json");
249 const MISE_1159_ANY: &str = include_str!("fixtures/finding-mise-1159-any.json");
250 const SHOW_JOUET_87: &str = include_str!("fixtures/show-jouet-87.json");
251
252 #[test]
253 fn open_findings_have_a_location_and_a_title_from_the_body() {
254 let doc: Value = serde_json::from_str(MISE_424).unwrap();
255 let (findings, more) = parse(&doc).unwrap();
256 assert!(!more);
257 assert_eq!(findings.len(), 2);
258 let f = &findings[0];
259 assert_eq!(f.id, "01M4C997EAAK13R52CVH7GYY7M");
260 assert!(f.is_open() && !f.stale);
261 assert_eq!(f.severity.as_deref(), Some("medium"));
262 assert_eq!(
263 f.location(),
264 "e2e/tasks/test_task_monorepo_deps_tool_install:44"
265 );
266 assert!(f.title.len() <= TITLE_WIDTH + 3, "{}", f.title);
267 assert_eq!(f.author, "agent:trail-review");
268 }
269
270 #[test]
271 fn resolved_and_stale_findings_say_so() {
272 let doc: Value = serde_json::from_str(MISE_1159_ANY).unwrap();
273 let (findings, _) = parse(&doc).unwrap();
274 let resolved = findings.iter().find(|f| f.status == "resolved").unwrap();
275 assert!(resolved.stale);
276 assert!(
277 resolved
278 .status_reason
279 .as_deref()
280 .unwrap()
281 .starts_with("Fixed in 58b789e5d2")
282 );
283 }
284
285 #[test]
286 fn a_trail_keeps_its_branch_once_merged() {
287 let doc: Value = serde_json::from_str(SHOW_JOUET_87).unwrap();
288 let t = Trail::parse(&doc).unwrap();
289 assert_eq!(t.number, 87);
290 assert_eq!(t.branch, "fix/cmd-through-wrappers");
291 assert_eq!(t.status, "open");
292 assert_eq!(
293 t.gates
294 .iter()
295 .find(|g| g.gate == "up_to_date")
296 .unwrap()
297 .reason
298 .as_deref(),
299 Some("Merge conflicts")
300 );
301 let merged = serde_json::json!({"number": 86, "branch": "", "original_branch": "fix/x", "status": "merged"});
302 assert_eq!(Trail::parse(&merged).unwrap().branch, "fix/x");
303 }
304
305 #[test]
306 fn handles_grow_only_where_two_would_clash() {
307 let ids = [
308 "01M4C997EAAK13R52CVH7GYY7M",
309 "01M4C997DZH5KQRP31NW93NQHR",
310 "01M4C997EAZZZZZZZZZZZZZZZZ",
311 ];
312 assert_eq!(
313 handles(&ids),
314 [
315 "entire:01M4C997EAA",
316 "entire:01M4C997DZ",
317 "entire:01M4C997EAZ"
318 ]
319 );
320 }
321
322 #[test]
323 fn titles_stop_at_the_first_sentence() {
324 assert_eq!(first_sentence("One thing. Then more."), "One thing.");
325 assert_eq!(first_sentence("\nno stop"), "no stop");
326 let long = "word ".repeat(40);
327 assert!(first_sentence(&long).ends_with("..."));
328 }
329}