1use serde::{Deserialize, Serialize};
10use std::collections::BTreeMap;
11use std::path::{Path, PathBuf};
12
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
14pub struct CheckRun {
15 pub kind: String,
17 pub command: String,
18 pub exit_code: i32,
19}
20
21#[derive(Deserialize)]
22struct State {
23 #[serde(default)]
24 trees: BTreeMap<String, Tree>,
25}
26
27#[derive(Deserialize)]
28struct Tree {
29 #[serde(default)]
30 runs: BTreeMap<String, Run>,
31}
32
33#[derive(Deserialize)]
34struct Run {
35 command: String,
36 exit_code: i32,
37}
38
39pub fn id_from_env() -> Option<String> {
42 ["JOUET_SESSION_ID", "CLAUDE_CODE_SESSION_ID"]
43 .iter()
44 .filter_map(|name| std::env::var(name).ok())
45 .find(|v| !v.trim().is_empty())
46}
47
48fn path(dir: &Path, id: &str) -> Option<PathBuf> {
50 let safe: String = id
51 .chars()
52 .filter(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
53 .take(128)
54 .collect();
55 (!safe.is_empty()).then(|| dir.join(format!("{safe}.json")))
56}
57
58pub fn last_checks(dir: &Path, id: &str, worktree: &Path) -> Option<Vec<CheckRun>> {
61 let bytes = std::fs::read(path(dir, id)?).ok()?;
62 let mut state: State = serde_json::from_slice(&bytes).ok()?;
63 let root = worktree
65 .canonicalize()
66 .unwrap_or_else(|_| worktree.to_path_buf());
67 let tree = state.trees.remove(root.to_string_lossy().as_ref())?;
68 let runs: Vec<CheckRun> = tree
69 .runs
70 .into_iter()
71 .map(|(kind, run)| CheckRun {
72 kind,
73 command: run.command,
74 exit_code: run.exit_code,
75 })
76 .collect();
77 (!runs.is_empty()).then_some(runs)
78}
79
80#[cfg(test)]
81mod tests {
82 use super::*;
83
84 #[test]
85 fn reads_what_the_hooks_record() {
86 let dir = tempfile::tempdir().unwrap();
87 std::fs::write(
88 dir.path().join("abc-123.json"),
89 r#"{"trees":{"/src/app":{"runs":{"test":{"command":"cargo test","exit_code":101},"lint":{"command":"mise run lint","exit_code":0}}},"/src/other":{"runs":{"build":{"command":"cargo build","exit_code":0}}}}}"#,
90 )
91 .unwrap();
92 let app = Path::new("/src/app");
93 let runs = last_checks(dir.path(), "abc-123", app).unwrap();
94 assert_eq!(
95 runs,
96 [
97 CheckRun {
98 kind: "lint".into(),
99 command: "mise run lint".into(),
100 exit_code: 0
101 },
102 CheckRun {
103 kind: "test".into(),
104 command: "cargo test".into(),
105 exit_code: 101
106 },
107 ]
108 );
109 assert_eq!(
111 last_checks(dir.path(), "abc-123", Path::new("/src/elsewhere")),
112 None
113 );
114 assert_eq!(last_checks(dir.path(), "other", app), None);
115 assert_eq!(last_checks(dir.path(), "../../etc", app), None);
116 std::fs::write(dir.path().join("bad.json"), "not json").unwrap();
117 assert_eq!(last_checks(dir.path(), "bad", app), None);
118 std::fs::write(
119 dir.path().join("empty.json"),
120 r#"{"trees":{"/src/app":{"runs":{}}}}"#,
121 )
122 .unwrap();
123 assert_eq!(last_checks(dir.path(), "empty", app), None);
124 }
125}