1use std::path::{Path, PathBuf};
11use std::time::Duration;
12
13use super::{GitOutput, run_git};
14
15const FIELD: char = '\u{1f}'; #[derive(Debug, Clone, PartialEq, Eq)]
19pub struct Checkpoint {
20 pub sha: String,
21 pub time: String,
23 pub message: String,
24 pub files_changed: Option<usize>,
26}
27
28pub fn init(project: &Path) -> Result<(), String> {
30 let git_dir = shadow_git_dir(project)?;
31 if git_dir.join("HEAD").exists() {
32 return Ok(());
33 }
34 std::fs::create_dir_all(&git_dir).map_err(|e| format!("cannot create shadow dir: {e}"))?;
35
36 let env = base_env(&git_dir, project);
37 git(&["init", "-q"], project, Duration::from_secs(15), &env)?.ok_stdout()?;
38
39 let excludes = write_excludes(&git_dir)?;
42 let exc = excludes.to_string_lossy();
43 for (k, v) in [
44 ("core.excludesFile", exc.as_ref()),
45 ("commit.gpgsign", "false"),
46 ("gc.auto", "0"),
47 ("core.autocrlf", "false"),
51 ("core.safecrlf", "false"),
52 ] {
53 git(&["config", k, v], project, Duration::from_secs(10), &env)?.ok_stdout()?;
54 }
55 Ok(())
56}
57
58pub fn snapshot(project: &Path, message: &str) -> Result<Checkpoint, String> {
61 init(project)?;
62 let git_dir = shadow_git_dir(project)?;
63 let env = base_env(&git_dir, project);
64
65 git(&["add", "-A"], project, Duration::from_mins(2), &env)?.ok_stdout()?;
66
67 let msg = if message.trim().is_empty() {
68 "lean-ctx checkpoint"
69 } else {
70 message
71 };
72 let commit = git(
73 &["commit", "--no-verify", "-q", "-m", msg],
74 project,
75 Duration::from_mins(1),
76 &env,
77 )?;
78
79 if commit.success {
80 let sha = head_sha(project, &env)?;
81 let files = count_changed(project, &env, &sha);
82 return Ok(Checkpoint {
83 sha,
84 time: now_iso(project, &env),
85 message: msg.to_string(),
86 files_changed: Some(files),
87 });
88 }
89
90 if let Ok(sha) = head_sha(project, &env) {
92 return Ok(Checkpoint {
93 sha,
94 time: now_iso(project, &env),
95 message: "(no changes since last checkpoint)".to_string(),
96 files_changed: Some(0),
97 });
98 }
99 Err(commit.ok_stdout().unwrap_err())
100}
101
102pub fn log(project: &Path, limit: usize) -> Result<Vec<Checkpoint>, String> {
104 let git_dir = shadow_git_dir(project)?;
105 if !git_dir.join("HEAD").exists() {
106 return Ok(Vec::new());
107 }
108 let env = base_env(&git_dir, project);
109 let fmt = format!("--pretty=format:%H{FIELD}%cI{FIELD}%s");
110 let out = git(
111 &["log", &fmt, &format!("--max-count={}", limit.max(1))],
112 project,
113 Duration::from_secs(15),
114 &env,
115 )?;
116 if !out.success {
117 return Ok(Vec::new()); }
119 Ok(out
120 .stdout
121 .lines()
122 .filter_map(|line| {
123 let mut parts = line.splitn(3, FIELD);
124 Some(Checkpoint {
125 sha: parts.next()?.to_string(),
126 time: parts.next().unwrap_or("").to_string(),
127 message: parts.next().unwrap_or("").to_string(),
128 files_changed: None,
129 })
130 })
131 .collect())
132}
133
134pub fn diff(project: &Path, from: Option<&str>, to: Option<&str>) -> Result<String, String> {
137 let git_dir = shadow_git_dir(project)?;
138 if !git_dir.join("HEAD").exists() {
139 return Err("no checkpoints yet — run snapshot first".to_string());
140 }
141 let env = base_env(&git_dir, project);
142 let mut args: Vec<String> = vec!["diff".to_string()];
143 match (from, to) {
144 (Some(f), Some(t)) => {
145 args.push(f.to_string());
146 args.push(t.to_string());
147 }
148 (Some(f), None) => args.push(f.to_string()),
149 (None, _) => args.push("HEAD".to_string()),
150 }
151 let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
152 git(&arg_refs, project, Duration::from_secs(30), &env)?.ok_stdout()
153}
154
155pub fn restore(project: &Path, git_ref: &str, path: Option<&str>) -> Result<String, String> {
158 let git_dir = shadow_git_dir(project)?;
159 if !git_dir.join("HEAD").exists() {
160 return Err("no checkpoints yet — nothing to restore".to_string());
161 }
162 let env = base_env(&git_dir, project);
163 let target = path.unwrap_or(".");
164 git(
165 &["checkout", git_ref, "--", target],
166 project,
167 Duration::from_mins(1),
168 &env,
169 )?
170 .ok_stdout()?;
171 Ok(format!("restored {target} from {git_ref}"))
172}
173
174fn git(
177 args: &[&str],
178 cwd: &Path,
179 timeout: Duration,
180 env: &[(String, String)],
181) -> Result<GitOutput, String> {
182 let refs: Vec<(&str, &str)> = env.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
183 run_git(args, cwd, timeout, &refs)
184}
185
186fn base_env(git_dir: &Path, work_tree: &Path) -> Vec<(String, String)> {
187 vec![
188 ("GIT_DIR".into(), git_dir.to_string_lossy().into_owned()),
189 (
190 "GIT_WORK_TREE".into(),
191 work_tree.to_string_lossy().into_owned(),
192 ),
193 ("GIT_AUTHOR_NAME".into(), "lean-ctx".into()),
194 ("GIT_AUTHOR_EMAIL".into(), "agent@lean-ctx.local".into()),
195 ("GIT_COMMITTER_NAME".into(), "lean-ctx".into()),
196 ("GIT_COMMITTER_EMAIL".into(), "agent@lean-ctx.local".into()),
197 ]
198}
199
200fn head_sha(project: &Path, env: &[(String, String)]) -> Result<String, String> {
201 let out = git(
202 &["rev-parse", "--short", "HEAD"],
203 project,
204 Duration::from_secs(10),
205 env,
206 )?
207 .ok_stdout()?;
208 Ok(out.trim().to_string())
209}
210
211fn now_iso(project: &Path, env: &[(String, String)]) -> String {
212 git(
213 &["show", "-s", "--format=%cI", "HEAD"],
214 project,
215 Duration::from_secs(10),
216 env,
217 )
218 .ok()
219 .and_then(|o| o.ok_stdout().ok())
220 .map(|s| s.trim().to_string())
221 .unwrap_or_default()
222}
223
224fn count_changed(project: &Path, env: &[(String, String)], sha: &str) -> usize {
225 let range = format!("{sha}^..{sha}");
227 let out = git(
228 &["diff", "--name-only", &range],
229 project,
230 Duration::from_secs(15),
231 env,
232 );
233 match out {
234 Ok(o) if o.success => o.stdout.lines().filter(|l| !l.trim().is_empty()).count(),
235 _ => {
236 git(
238 &["show", "--name-only", "--pretty=format:", sha],
239 project,
240 Duration::from_secs(15),
241 env,
242 )
243 .ok()
244 .and_then(|o| o.ok_stdout().ok())
245 .map_or(0, |s| s.lines().filter(|l| !l.trim().is_empty()).count())
246 }
247 }
248}
249
250fn shadow_git_dir(project: &Path) -> Result<PathBuf, String> {
251 let hash = project_hash(project);
252 Ok(crate::core::data_dir::lean_ctx_data_dir()?
253 .join("shadow")
254 .join(hash)
255 .join("git"))
256}
257
258fn project_hash(project: &Path) -> String {
260 let canonical = std::fs::canonicalize(project).unwrap_or_else(|_| project.to_path_buf());
261 let bytes = canonical.to_string_lossy();
262 let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
263 for b in bytes.as_bytes() {
264 hash ^= u64::from(*b);
265 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
266 }
267 format!("{hash:016x}")
268}
269
270fn write_excludes(git_dir: &Path) -> Result<PathBuf, String> {
271 let path = git_dir
272 .parent()
273 .unwrap_or(git_dir)
274 .join("lean-ctx-excludes");
275 let defaults = "\
276# lean-ctx shadow-history excludes (keeps snapshots lean even without a project .gitignore)
277.git/
278target/
279node_modules/
280dist/
281build/
282.venv/
283__pycache__/
284*.lock
285";
286 std::fs::write(&path, defaults).map_err(|e| format!("cannot write excludes: {e}"))?;
287 Ok(path)
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293
294 fn git_ready() -> bool {
295 super::super::git_available()
296 }
297
298 fn temp_project(tag: &str) -> PathBuf {
299 let dir = std::env::temp_dir().join(format!("lc_shadow_{tag}_{}", std::process::id()));
300 let _ = std::fs::remove_dir_all(&dir);
301 std::fs::create_dir_all(&dir).unwrap();
302 dir
303 }
304
305 #[test]
306 fn project_hash_is_stable_and_hex() {
307 let h1 = project_hash(Path::new("/some/project"));
308 let h2 = project_hash(Path::new("/some/project"));
309 assert_eq!(h1, h2);
310 assert_eq!(h1.len(), 16);
311 assert!(h1.chars().all(|c| c.is_ascii_hexdigit()));
312 }
313
314 #[test]
315 fn snapshot_log_diff_restore_roundtrip() {
316 if !git_ready() {
317 return;
318 }
319 let _lock = crate::core::data_dir::test_env_lock();
320 let data = temp_project("data");
321 crate::test_env::set_var("LEAN_CTX_DATA_DIR", &data);
322 let project = temp_project("proj");
323
324 std::fs::write(project.join("a.txt"), "v1\n").unwrap();
325 let c1 = snapshot(&project, "first").expect("snapshot 1");
326 assert_eq!(c1.files_changed, Some(1));
327
328 let c1b = snapshot(&project, "again").expect("snapshot noop");
330 assert_eq!(c1b.files_changed, Some(0));
331
332 std::fs::write(project.join("a.txt"), "v2\n").unwrap();
333 let d = diff(&project, None, None).expect("diff vs HEAD");
334 assert!(d.contains("-v1") && d.contains("+v2"), "diff was: {d}");
335
336 let c2 = snapshot(&project, "second").expect("snapshot 2");
337 assert_ne!(c1.sha, c2.sha);
338
339 let entries = log(&project, 10).expect("log");
340 assert!(entries.len() >= 2, "expected >=2 checkpoints");
341
342 restore(&project, &c1.sha, Some("a.txt")).expect("restore");
344 let restored = std::fs::read_to_string(project.join("a.txt")).unwrap();
345 assert_eq!(restored, "v1\n");
346
347 assert!(
349 !project.join(".git").exists(),
350 "shadow history must not touch the user's project .git"
351 );
352
353 crate::test_env::remove_var("LEAN_CTX_DATA_DIR");
354 let _ = std::fs::remove_dir_all(&data);
355 let _ = std::fs::remove_dir_all(&project);
356 }
357}