1use std::collections::HashMap;
34use std::time::Duration;
35
36use agentmux_common::win32::NoWindow;
37
38use crate::backend::container::mounts::read_exec;
39use crate::backend::rpc_types::{FsGitEntry, FsGitState, FsGitStatus};
40
41use super::container_folders::{self, Inside, Place};
42use super::platform::display_path;
43
44const GIT_TIMEOUT: Duration = Duration::from_secs(4);
47
48const SAFE_CONFIG: &[&str] = &[
50 "-c",
52 "core.fsmonitor=false",
53 "-c",
55 "core.untrackedCache=false",
56];
57
58pub const NO_NETWORK_ENV: &[(&str, &str)] = &[("GIT_NO_LAZY_FETCH", "1"), ("GIT_ALLOW_PROTOCOL", "")];
62
63const QUIET_ENV: &[(&str, &str)] = &[("GIT_OPTIONAL_LOCKS", "0"), ("GIT_TERMINAL_PROMPT", "0")];
66
67pub const NOT_READ_ON_THE_HOST: &str = "Git facts of a container agent's folder are not read on the host.";
70
71const MAX_INSIDE_OUTPUT: usize = 16 * 1024 * 1024;
73
74pub async fn git_status(raw: &str) -> FsGitStatus {
76 let dir = match super::resolve_request_path(raw).and_then(|p| p.canonicalize().map_err(|e| e.to_string())) {
77 Ok(d) if d.is_dir() => d,
78 _ => return FsGitStatus::default(),
79 };
80 let dir_arg = display_path(&dir);
81
82 let prefix = match run_git(&dir_arg, &["rev-parse", "--show-prefix"]).await {
85 Ok(out) => String::from_utf8_lossy(&out).trim_end_matches(['\r', '\n']).to_string(),
86 Err(_) => return FsGitStatus::default(),
87 };
88 let status = ["--ignored=matching", "--", "."];
89 let out = match safe_status_porcelain(&dir_arg, &status).await {
90 Ok(out) => out,
91 Err(StatusError::Settings(what)) => {
92 return FsGitStatus {
93 in_repo: true,
94 error: Some(format!("{what}, so git markers are off here.")),
95 ..Default::default()
96 };
97 }
98 Err(StatusError::Git(e)) => return FsGitStatus { in_repo: true, error: Some(e), ..Default::default() },
99 };
100 summarize(&parse_porcelain_v2(&out), &prefix)
101}
102
103#[derive(Debug)]
105pub(crate) enum StatusError {
106 Settings(&'static str),
109 Git(String),
111}
112
113pub(crate) async fn safe_status_porcelain(dir: &str, extra: &[&str]) -> Result<Vec<u8>, StatusError> {
118 let Ok(filters) = repo_filters(dir).await else {
122 return Err(StatusError::Settings("Couldn't read this repository's settings"));
123 };
124 if filters.iter().any(|n| n.contains('=')) {
128 return Err(StatusError::Settings("This repository's settings can't be read safely"));
129 }
130 let mut args: Vec<String> = Vec::new();
131 for name in filters {
132 for key in ["clean", "smudge", "process"] {
133 args.push("-c".into());
134 args.push(format!("filter.{name}.{key}="));
135 }
136 args.push("-c".into());
137 args.push(format!("filter.{name}.required=false"));
138 }
139 args.extend(
140 ["status", "--porcelain=v2", "-z", "--branch", "--untracked-files=normal", "--ignore-submodules=all"]
141 .map(String::from),
142 );
143 args.extend(extra.iter().map(|s| s.to_string()));
144 let arg_refs: Vec<&str> = args.iter().map(String::as_str).collect();
145 run_git(dir, &arg_refs).await.map_err(|e| StatusError::Git(e.message()))
146}
147
148pub(crate) async fn safe_toplevel(dir: &str) -> Option<String> {
152 let (out, inside) = run_git_where(dir, &["rev-parse", "--show-toplevel"]).await.ok()?;
153 let line = String::from_utf8_lossy(&out).trim_end_matches(['\r', '\n']).to_string();
154 if line.is_empty() {
155 return None;
156 }
157 match inside {
158 None => Some(line),
159 Some(inside) => inside.host_path(&line),
160 }
161}
162
163pub(crate) async fn safe_git_line(dir: &str, args: &[&str]) -> Option<String> {
167 let out = run_git(dir, args).await.ok()?;
168 let line = String::from_utf8_lossy(&out).trim_end_matches(['\r', '\n']).to_string();
169 (!line.is_empty()).then_some(line)
170}
171
172async fn repo_filters(dir: &str) -> Result<Vec<String>, ()> {
179 let scoped = run_git(dir, &["config", "--show-scope", "--name-only", "--get-regexp", r"^filter\."]).await;
180 let (out, scoped) = match scoped {
181 Ok(out) => (out, true),
182 Err(GitError::Exit(1)) => return Ok(Vec::new()),
183 Err(_) => match run_git(dir, &["config", "--name-only", "--get-regexp", r"^filter\."]).await {
185 Ok(out) => (out, false),
186 Err(GitError::Exit(1)) => return Ok(Vec::new()),
187 Err(_) => return Err(()),
188 },
189 };
190 Ok(filter_names(&String::from_utf8_lossy(&out), scoped))
191}
192
193pub fn filter_names(out: &str, scoped: bool) -> Vec<String> {
196 let mut names: Vec<String> = Vec::new();
197 for line in out.lines() {
198 let (scope, key) = if scoped {
199 match line.split_once(|c: char| c.is_whitespace()) {
200 Some((s, k)) => (s, k.trim()),
201 None => continue,
202 }
203 } else {
204 ("", line.trim())
205 };
206 if scoped && (scope == "system" || scope == "global") {
207 continue;
208 }
209 let Some(rest) = key.strip_prefix("filter.") else { continue };
211 let Some((name, _)) = rest.rsplit_once('.') else { continue };
212 if !name.is_empty() && !names.iter().any(|n| n == name) {
213 names.push(name.to_string());
214 }
215 }
216 names
217}
218
219async fn run_git(dir: &str, args: &[&str]) -> Result<Vec<u8>, GitError> {
223 run_git_where(dir, args).await.map(|(out, _)| out)
224}
225
226async fn run_git_where(dir: &str, args: &[&str]) -> Result<(Vec<u8>, Option<Inside>), GitError> {
228 let asked = dir.to_string();
230 let place = tokio::task::spawn_blocking(move || container_folders::place(&asked)).await.unwrap_or(Place::Unknown);
231 match place {
232 Place::Host => run_on_host(dir, args).await.map(|out| (out, None)),
233 Place::Inside(inside) => run_inside(&inside, args).await.map(|out| (out, Some(inside))),
234 Place::Unknown => Err(GitError::Failed(NOT_READ_ON_THE_HOST.to_string())),
235 }
236}
237
238async fn run_inside(inside: &Inside, args: &[&str]) -> Result<Vec<u8>, GitError> {
242 let mut argv = vec!["git".to_string()];
243 argv.extend(git_args(&inside.dir, args));
244 let env: Vec<(String, String)> = QUIET_ENV.iter().chain(NO_NETWORK_ENV).map(|(k, v)| (k.to_string(), v.to_string())).collect();
245 let out = read_exec::read(&inside.container, &argv, &env, GIT_TIMEOUT, MAX_INSIDE_OUTPUT).await.map_err(GitError::Failed)?;
246 match out.exit {
247 Some(0) => Ok(out.stdout),
248 Some(read_exec::TIMED_OUT_EXIT) => Err(GitError::Failed("git took too long to answer.".to_string())),
249 Some(code) if out.stderr.is_empty() => Err(GitError::Exit(i32::try_from(code).unwrap_or(-1))),
250 None if out.stderr.is_empty() => Err(GitError::Failed("git didn't say how it ended.".to_string())),
251 _ => Err(GitError::Failed(String::from_utf8_lossy(&out.stderr).trim().to_string())),
252 }
253}
254
255async fn run_on_host(dir: &str, args: &[&str]) -> Result<Vec<u8>, GitError> {
257 #[cfg(test)]
258 test_support::note_host_run(dir);
259 let mut cmd = git_command(dir, args);
260 let child = cmd.spawn().map_err(|e| GitError::Failed(format!("Couldn't run git: {e}")))?;
261 match tokio::time::timeout(GIT_TIMEOUT, child.wait_with_output()).await {
262 Err(_) => Err(GitError::Failed("git took too long to answer.".to_string())),
263 Ok(Err(e)) => Err(GitError::Failed(format!("git failed: {e}"))),
264 Ok(Ok(out)) if out.status.success() => Ok(out.stdout),
265 Ok(Ok(out)) => match out.status.code() {
266 Some(code) if out.stderr.is_empty() => Err(GitError::Exit(code)),
267 _ => Err(GitError::Failed(String::from_utf8_lossy(&out.stderr).trim().to_string())),
268 },
269 }
270}
271
272fn git_args(dir: &str, args: &[&str]) -> Vec<String> {
275 let mut all = vec!["-C".to_string(), dir.to_string()];
276 all.extend(SAFE_CONFIG.iter().map(|s| s.to_string()));
277 all.push("--no-optional-locks".to_string());
278 all.extend(args.iter().map(|s| s.to_string()));
279 all
280}
281
282fn git_command(dir: &str, args: &[&str]) -> tokio::process::Command {
286 let mut cmd = tokio::process::Command::new("git");
287 cmd.args(git_args(dir, args));
288 cmd.envs(QUIET_ENV.iter().copied());
289 cmd.stdin(std::process::Stdio::null())
290 .stdout(std::process::Stdio::piped())
291 .stderr(std::process::Stdio::piped())
292 .kill_on_drop(true)
293 .no_window();
294 crate::backend::pane_env::sanitize_external_command(&mut cmd);
296 cmd.envs(NO_NETWORK_ENV.iter().copied());
298 cmd
299}
300
301#[derive(Debug)]
302enum GitError {
303 Exit(i32),
305 Failed(String),
306}
307
308impl GitError {
309 fn message(self) -> String {
310 match self {
311 GitError::Exit(code) => format!("git exited with status {code}."),
312 GitError::Failed(m) => m,
313 }
314 }
315}
316
317#[derive(Debug, Clone, PartialEq, Eq)]
319pub struct GitRecord {
320 pub path: String,
321 pub state: FsGitState,
322}
323
324#[derive(Debug, Default, PartialEq, Eq)]
326pub struct Porcelain {
327 pub branch: Option<String>,
328 pub ahead: Option<u64>,
329 pub behind: Option<u64>,
330 pub records: Vec<GitRecord>,
331}
332
333fn state_of_xy(xy: &str) -> FsGitState {
336 let mut state = FsGitState::Added;
337 let mut seen = false;
338 for c in xy.chars() {
339 let s = match c {
340 'M' | 'T' => FsGitState::Modified,
341 'D' => FsGitState::Deleted,
342 'R' | 'C' => FsGitState::Renamed,
343 'A' => FsGitState::Added,
344 _ => continue,
345 };
346 state = if seen { state.max(s) } else { s };
347 seen = true;
348 }
349 state
350}
351
352pub fn parse_porcelain_v2(out: &[u8]) -> Porcelain {
355 let mut p = Porcelain::default();
356 let mut fields = out.split(|b| *b == 0).map(|f| String::from_utf8_lossy(f).into_owned());
357 while let Some(line) = fields.next() {
358 if line.is_empty() {
359 continue;
360 }
361 let kind = line.as_bytes()[0];
362 match kind {
363 b'#' => {
364 if let Some(head) = line.strip_prefix("# branch.head ") {
365 if head != "(detached)" {
366 p.branch = Some(head.to_string());
367 }
368 } else if let Some(ab) = line.strip_prefix("# branch.ab ") {
369 let mut it = ab.split(' ');
370 p.ahead = it.next().and_then(|a| a.trim_start_matches('+').parse().ok());
371 p.behind = it.next().and_then(|b| b.trim_start_matches('-').parse().ok());
372 }
373 }
374 b'1' => {
375 let parts: Vec<&str> = line.splitn(9, ' ').collect();
377 if parts.len() == 9 {
378 p.records.push(GitRecord { path: parts[8].to_string(), state: state_of_xy(parts[1]) });
379 }
380 }
381 b'2' => {
382 let parts: Vec<&str> = line.splitn(10, ' ').collect();
384 let _orig = fields.next();
385 if parts.len() == 10 {
386 p.records.push(GitRecord { path: parts[9].to_string(), state: state_of_xy(parts[1]).max(FsGitState::Renamed) });
387 }
388 }
389 b'u' => {
390 let parts: Vec<&str> = line.splitn(11, ' ').collect();
392 if parts.len() == 11 {
393 p.records.push(GitRecord { path: parts[10].to_string(), state: FsGitState::Conflicted });
394 }
395 }
396 b'?' | b'!' => {
397 if let Some(path) = line.get(2..) {
398 let state = if kind == b'?' { FsGitState::Untracked } else { FsGitState::Ignored };
399 p.records.push(GitRecord { path: path.to_string(), state });
400 }
401 }
402 _ => {}
403 }
404 }
405 p
406}
407
408pub fn summarize(p: &Porcelain, prefix: &str) -> FsGitStatus {
414 let mut by_child: HashMap<String, FsGitState> = HashMap::new();
415 let mut changes = 0u64;
416 for r in &p.records {
417 let Some(rel) = r.path.strip_prefix(prefix) else { continue };
418 let rel = rel.trim_end_matches('/');
419 if rel.is_empty() {
420 continue;
421 }
422 if r.state != FsGitState::Ignored {
423 changes += 1;
424 }
425 let (child, nested) = match rel.split_once('/') {
426 Some((c, _)) => (c, true),
427 None => (rel, false),
428 };
429 if nested && r.state == FsGitState::Ignored {
431 continue;
432 }
433 by_child.entry(child.to_string()).and_modify(|s| *s = (*s).max(r.state)).or_insert(r.state);
434 }
435 let mut entries: Vec<FsGitEntry> = by_child.into_iter().map(|(name, state)| FsGitEntry { name, state }).collect();
436 entries.sort_by(|a, b| a.name.cmp(&b.name));
437 FsGitStatus {
438 in_repo: true,
439 branch: p.branch.clone(),
440 ahead: p.ahead,
441 behind: p.behind,
442 entries,
443 changes,
444 error: None,
445 }
446}
447
448#[cfg(test)]
451pub(crate) mod test_support {
452 use std::sync::Arc;
453
454 use crate::backend::container::mounts::read_exec::{self, ReadOutput};
455
456 fn host_runs() -> &'static parking_lot::Mutex<Vec<String>> {
457 static RUNS: std::sync::LazyLock<parking_lot::Mutex<Vec<String>>> = std::sync::LazyLock::new(Default::default);
458 &RUNS
459 }
460
461 pub(super) fn note_host_run(dir: &str) {
462 host_runs().lock().push(dir.replace('\\', "/"));
463 }
464
465 pub(crate) fn host_runs_for(part: &str) -> usize {
467 host_runs().lock().iter().filter(|dir| dir.contains(part)).count()
468 }
469
470 pub(crate) type Seen = Arc<parking_lot::Mutex<Vec<(Vec<String>, Vec<(String, String)>)>>>;
472
473 pub(crate) fn container_git(container: &str) -> Seen {
477 let seen = Seen::default();
478 let log = seen.clone();
479 read_exec::stand_in_for_test(container, move |argv, env| {
480 log.lock().push((argv.to_vec(), env.to_vec()));
481 let has = |word: &str| argv.iter().any(|a| a == word);
482 let says = |out: &[u8]| Ok(ReadOutput { exit: Some(0), stdout: out.to_vec(), stderr: Vec::new() });
483 let dir = argv.get(2).map(String::as_str).unwrap_or_default();
484 if !(dir == "/workspace" || dir.starts_with("/workspace/")) {
485 return Ok(ReadOutput { exit: Some(128), stdout: Vec::new(), stderr: b"fatal: not a git repository".to_vec() });
486 }
487 if has("--show-toplevel") {
488 says(b"/workspace\n")
489 } else if has("--show-prefix") {
490 let below = dir.trim_start_matches("/workspace").trim_start_matches('/');
491 says(if below.is_empty() { String::new() } else { format!("{below}/\n") }.as_bytes())
492 } else if has("get-url") {
493 says(b"https://github.com/AgentMuxAI/Inside.git\n")
494 } else if has("status") {
495 says(b"# branch.head inside\x001 .M N... 100644 100644 100644 abc abc in-container.txt\x00? sub/new-inside.txt\x00")
496 } else {
497 Ok(ReadOutput { exit: Some(1), ..Default::default() })
499 }
500 });
501 seen
502 }
503}
504
505#[cfg(test)]
506mod tests {
507 use super::*;
508
509 fn z(records: &[&str]) -> Vec<u8> {
510 let mut out = Vec::new();
511 for r in records {
512 out.extend_from_slice(r.as_bytes());
513 out.push(0);
514 }
515 out
516 }
517
518 #[test]
519 fn parses_branch_ahead_and_behind() {
520 let p = parse_porcelain_v2(&z(&["# branch.oid abc", "# branch.head main", "# branch.upstream origin/main", "# branch.ab +2 -5"]));
521 assert_eq!(p.branch.as_deref(), Some("main"));
522 assert_eq!((p.ahead, p.behind), (Some(2), Some(5)));
523 let detached = parse_porcelain_v2(&z(&["# branch.head (detached)"]));
524 assert_eq!(detached.branch, None);
525 }
526
527 #[test]
528 fn parses_every_record_kind_including_spaces_and_renames() {
529 let out = z(&[
530 "1 .M N... 100644 100644 100644 aaa bbb src/a file.ts",
531 "1 A. N... 000000 100644 100644 000 ccc new.ts",
532 "1 D. N... 100644 000000 000000 ddd 000 gone.ts",
533 "2 R. N... 100644 100644 100644 eee eee R100 docs/new name.md",
534 "docs/old name.md",
535 "u UU N... 100644 100644 100644 100644 a b c conflict.rs",
536 "? notes.txt",
537 "! target/",
538 ]);
539 let p = parse_porcelain_v2(&out);
540 let got: Vec<(&str, FsGitState)> = p.records.iter().map(|r| (r.path.as_str(), r.state)).collect();
541 assert_eq!(
542 got,
543 vec![
544 ("src/a file.ts", FsGitState::Modified),
545 ("new.ts", FsGitState::Added),
546 ("gone.ts", FsGitState::Deleted),
547 ("docs/new name.md", FsGitState::Renamed),
548 ("conflict.rs", FsGitState::Conflicted),
549 ("notes.txt", FsGitState::Untracked),
550 ("target/", FsGitState::Ignored),
551 ]
552 );
553 }
554
555 #[test]
556 fn a_staged_add_with_later_edits_reads_as_modified() {
557 assert_eq!(state_of_xy("AM"), FsGitState::Modified);
558 assert_eq!(state_of_xy("MD"), FsGitState::Modified);
559 assert_eq!(state_of_xy("R."), FsGitState::Renamed);
560 }
561
562 #[test]
563 fn folds_records_into_the_listed_folders_children() {
564 let p = parse_porcelain_v2(&z(&[
565 "# branch.head main",
566 "1 .M N... 1 1 1 a b app/src/x.ts",
567 "? app/src/new/",
568 "1 .M N... 1 1 1 a b app/README.md",
569 "! app/node_modules/",
570 "! app/src/cache/",
571 "? app/notes.txt",
572 "1 .M N... 1 1 1 a b other/y.ts",
573 ]));
574 let s = summarize(&p, "app/");
575 let got: Vec<(&str, FsGitState)> = s.entries.iter().map(|e| (e.name.as_str(), e.state)).collect();
576 assert_eq!(
577 got,
578 vec![
579 ("README.md", FsGitState::Modified),
580 ("node_modules", FsGitState::Ignored),
581 ("notes.txt", FsGitState::Untracked),
582 ("src", FsGitState::Modified),
584 ]
585 );
586 assert_eq!(s.changes, 4);
587 assert_eq!(s.branch.as_deref(), Some("main"));
588 }
589
590 #[test]
591 fn at_the_top_the_prefix_is_empty() {
592 let p = parse_porcelain_v2(&z(&["? a.txt", "1 .M N... 1 1 1 a b dir/b.txt"]));
593 let s = summarize(&p, "");
594 assert_eq!(s.entries.len(), 2);
595 }
596
597 #[tokio::test]
600 async fn runs_git_without_the_repositorys_fsmonitor() {
601 let dir = tempfile::tempdir().unwrap();
602 let git = |args: &[&str]| {
603 std::process::Command::new("git")
604 .args(["-c", "user.email=a@b", "-c", "user.name=a"])
605 .args(args)
606 .current_dir(dir.path())
607 .no_window()
608 .output()
609 };
610 if git(&["init", "-q"]).map(|o| !o.status.success()).unwrap_or(true) {
611 return; }
613 std::fs::write(dir.path().join("tracked.txt"), "a").unwrap();
614 let _ = git(&["add", "."]);
615 let _ = git(&["commit", "-qm", "x"]);
616 std::fs::write(dir.path().join("tracked.txt"), "b").unwrap();
617 std::fs::write(dir.path().join("new.txt"), "n").unwrap();
618 let mark = dir.path().join("fsmonitor-ran");
620 let _ = git(&["config", "core.fsmonitor", &format!("touch '{}'", mark.display())]);
621
622 let s = git_status(&dir.path().to_string_lossy()).await;
623 assert!(s.in_repo, "{s:?}");
624 let get = |n: &str| s.entries.iter().find(|e| e.name == n).map(|e| e.state);
625 assert_eq!(get("tracked.txt"), Some(FsGitState::Modified));
626 assert_eq!(get("new.txt"), Some(FsGitState::Untracked));
627 assert!(!mark.exists(), "the repository's fsmonitor program ran");
628 }
629
630 #[test]
631 fn blanks_the_repositorys_filters_and_keeps_the_users() {
632 let out = "system\tfilter.lfs.clean\nglobal\tfilter.lfs.process\nlocal\tfilter.evil.clean\nlocal\tfilter.evil.process\nworktree\tfilter.a.b.smudge\n";
633 assert_eq!(filter_names(out, true), vec!["evil".to_string(), "a.b".to_string()]);
634 assert_eq!(filter_names("filter.lfs.clean\nfilter.x.process\n", false), vec!["lfs".to_string(), "x".to_string()]);
636 }
637
638 #[tokio::test]
642 async fn runs_git_without_the_repositorys_clean_filter() {
643 let dir = tempfile::tempdir().unwrap();
644 let git = |args: &[&str]| {
645 std::process::Command::new("git")
646 .args(["-c", "user.email=a@b", "-c", "user.name=a"])
647 .args(args)
648 .current_dir(dir.path())
649 .no_window()
650 .output()
651 };
652 if git(&["init", "-q"]).map(|o| !o.status.success()).unwrap_or(true) {
653 return; }
655 std::fs::write(dir.path().join(".gitattributes"), "*.txt filter=evil\n").unwrap();
656 std::fs::write(dir.path().join("t.txt"), "a\n").unwrap();
657 let _ = git(&["add", "."]);
658 let _ = git(&["commit", "-qm", "x"]);
659 let mark = dir.path().join("filter-ran");
660 let mark_arg = mark.display().to_string().replace('\\', "/");
661 let _ = git(&["config", "filter.evil.clean", &format!("sh -c 'touch \"{mark_arg}\"; cat'")]);
662 std::thread::sleep(std::time::Duration::from_millis(1100));
665 std::fs::write(dir.path().join("t.txt"), "a\n").unwrap();
666
667 let s = git_status(&dir.path().to_string_lossy()).await;
668 assert!(s.in_repo && s.error.is_none(), "{s:?}");
669 assert!(!mark.exists(), "the repository's clean filter ran");
670 }
671
672 #[tokio::test]
675 async fn refuses_a_filter_name_that_c_cannot_blank() {
676 let dir = tempfile::tempdir().unwrap();
677 let git = |args: &[&str]| {
678 std::process::Command::new("git")
679 .args(["-c", "user.email=a@b", "-c", "user.name=a"])
680 .args(args)
681 .current_dir(dir.path())
682 .no_window()
683 .output()
684 };
685 if git(&["init", "-q"]).map(|o| !o.status.success()).unwrap_or(true) {
686 return; }
688 std::fs::write(dir.path().join(".gitattributes"), "*.txt filter=x=y\n").unwrap();
689 std::fs::write(dir.path().join("t.txt"), "a\n").unwrap();
690 let _ = git(&["add", "."]);
691 let _ = git(&["commit", "-qm", "x"]);
692 let mark = dir.path().join("filter-ran");
693 let mark_arg = mark.display().to_string().replace('\\', "/");
694 let _ = git(&["config", "filter.x=y.clean", &format!("sh -c 'touch \"{mark_arg}\"; cat'")]);
695 std::thread::sleep(std::time::Duration::from_millis(1100));
696 std::fs::write(dir.path().join("t.txt"), "a\n").unwrap();
697
698 let s = git_status(&dir.path().to_string_lossy()).await;
699 assert!(s.entries.is_empty() && s.error.is_some(), "{s:?}");
700 assert!(!mark.exists(), "the repository's clean filter ran");
701 }
702
703 #[tokio::test]
706 async fn an_unreadable_config_turns_markers_off() {
707 let dir = tempfile::tempdir().unwrap();
708 let ok = std::process::Command::new("git").args(["init", "-q"]).current_dir(dir.path()).no_window().output();
709 if ok.map(|o| !o.status.success()).unwrap_or(true) {
710 return; }
712 let config = dir.path().join(".git").join("config");
713 let mut text = std::fs::read_to_string(&config).unwrap();
714 text.push_str("\n[filter \"evil\"\n\tclean = broken\n");
715 std::fs::write(&config, text).unwrap();
716 let s = git_status(&dir.path().to_string_lossy()).await;
719 assert!(s.entries.is_empty(), "{s:?}");
720 assert!(!s.in_repo || s.error.is_some(), "{s:?}");
721 }
722
723 fn test_git(dir: &std::path::Path, args: &[&str]) -> Option<String> {
724 let out = std::process::Command::new("git")
725 .args(["-c", "user.email=a@b", "-c", "user.name=a"])
726 .args(args)
727 .current_dir(dir)
728 .no_window()
729 .output()
730 .ok()?;
731 out.status.success().then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
732 }
733
734 fn repository_missing_an_object(dir: &std::path::Path, mark: &std::path::Path) -> Option<String> {
739 test_git(dir, &["init", "-q"])?;
740 std::fs::write(dir.join("a.txt"), "a\n").unwrap();
741 test_git(dir, &["add", "."])?;
742 test_git(dir, &["commit", "-qm", "x"])?;
743 let tree = test_git(dir, &["rev-parse", "HEAD^{tree}"])?;
744 let source = dir.join("source");
745 std::fs::create_dir_all(&source).unwrap();
746 let slashes = |p: &std::path::Path| p.display().to_string().replace('\\', "/");
747 for (key, value) in [
748 ("core.repositoryformatversion", "1".to_string()),
749 ("extensions.partialClone", "origin".to_string()),
750 ("remote.origin.url", slashes(&source)),
751 ("remote.origin.promisor", "true".to_string()),
752 ("remote.origin.uploadpack", format!("echo ran > '{}' ; true", slashes(mark))),
753 ("protocol.allow", "always".to_string()),
754 ("protocol.file.allow", "always".to_string()),
755 ] {
756 test_git(dir, &["config", key, &value])?;
757 }
758 let object = dir.join(".git").join("objects").join(&tree[..2]).join(&tree[2..]);
759 std::fs::remove_file(object).ok()?;
760 Some(tree)
761 }
762
763 #[test]
764 fn every_git_run_is_set_to_fetch_nothing_and_allow_no_transport() {
765 let cmd = git_command(".", &["status"]);
766 let env: std::collections::HashMap<String, Option<String>> = cmd
767 .as_std()
768 .get_envs()
769 .map(|(k, v)| (k.to_string_lossy().into_owned(), v.map(|v| v.to_string_lossy().into_owned())))
770 .collect();
771 assert_eq!(env.get("GIT_NO_LAZY_FETCH"), Some(&Some("1".to_string())));
772 assert_eq!(env.get("GIT_ALLOW_PROTOCOL"), Some(&Some(String::new())), "set, and empty: no protocol is allowed");
773 }
774
775 #[tokio::test]
778 async fn a_status_read_never_fetches_and_allows_no_transport() {
779 let dir = tempfile::tempdir().unwrap();
780 let mark = dir.path().join("fetch-ran");
781 if repository_missing_an_object(dir.path(), &mark).is_none() {
782 return; }
784 let s = git_status(&dir.path().to_string_lossy()).await;
785 assert!(s.in_repo && s.entries.is_empty(), "{s:?}");
786 assert!(!mark.exists(), "the status read went to fetch the missing object");
787 }
788
789 #[tokio::test]
791 async fn a_ref_check_never_fetches_and_allows_no_transport() {
792 let dir = tempfile::tempdir().unwrap();
793 let mark = dir.path().join("fetch-ran");
794 let Some(tree) = repository_missing_an_object(dir.path(), &mark) else {
795 return; };
797 let found = safe_git_line(&dir.path().to_string_lossy(), &["rev-parse", "--verify", "--quiet", &format!("{tree}^{{tree}}")]).await;
798 assert_eq!(found, None, "the object is not there");
799 assert!(!mark.exists(), "the ref check went to fetch the missing object");
800 }
801
802 fn repository_with_changes(dir: &std::path::Path) -> Option<()> {
804 test_git(dir, &["init", "-q"])?;
805 std::fs::write(dir.join("tracked.txt"), "a").unwrap();
806 test_git(dir, &["add", "."])?;
807 test_git(dir, &["commit", "-qm", "x"])?;
808 std::fs::write(dir.join("tracked.txt"), "b").unwrap();
809 std::fs::write(dir.join("new.txt"), "n").unwrap();
810 Some(())
811 }
812
813 fn host_repository() -> (tempfile::TempDir, String, String, String) {
816 let dir = tempfile::tempdir().unwrap();
817 let _ = repository_with_changes(dir.path());
818 let inner = dir.path().join("sub");
819 std::fs::create_dir_all(&inner).unwrap();
820 let (top, sub) = (dir.path().to_string_lossy().into_owned(), inner.to_string_lossy().into_owned());
821 let name = dir.path().file_name().unwrap().to_string_lossy().into_owned();
822 (dir, top, sub, name)
823 }
824
825 #[tokio::test]
830 async fn git_facts_of_a_container_agent_are_read_inside_its_container() {
831 let (dir, top, sub, name) = host_repository();
832 let on_host = git_status(&top).await;
834 let host_runs = test_support::host_runs_for(&name);
835
836 let container = format!("agentmux-{name}");
837 container_folders::add_for_test(dir.path(), &container, "/workspace");
838 let seen = test_support::container_git(&container);
839
840 let s = git_status(&top).await;
841 assert!(s.in_repo && s.error.is_none(), "{s:?}");
842 assert_eq!(s.branch.as_deref(), Some("inside"));
843 let names: Vec<&str> = s.entries.iter().map(|e| e.name.as_str()).collect();
844 assert_eq!(names, vec!["in-container.txt", "sub"], "the container's changes, not the host's: {on_host:?}");
845 let below = git_status(&sub).await;
846 assert_eq!(below.entries.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), vec!["new-inside.txt"]);
847 assert_eq!(safe_git_line(&sub, &["remote", "get-url", "origin"]).await.as_deref(), Some("https://github.com/AgentMuxAI/Inside.git"));
848 assert!(safe_status_porcelain(&top, &[]).await.is_ok());
849
850 let root = safe_toplevel(&sub).await.expect("inside a repository");
852 assert!(root.ends_with(&name), "{root}");
853 assert!(matches!(container_folders::place(&root), Place::Inside(at) if at.dir == "/workspace"));
854
855 let seen = seen.lock().clone();
856 assert!(seen.len() >= 8, "{seen:?}");
857 for (argv, env) in &seen {
858 assert_eq!(&argv[..2], ["git", "-C"]);
859 assert!(argv[2] == "/workspace" || argv[2] == "/workspace/sub", "the same folder, as the container names it: {argv:?}");
860 assert_eq!(&argv[3..8], ["-c", "core.fsmonitor=false", "-c", "core.untrackedCache=false", "--no-optional-locks"]);
861 for pair in [("GIT_NO_LAZY_FETCH", "1"), ("GIT_ALLOW_PROTOCOL", ""), ("GIT_TERMINAL_PROMPT", "0"), ("GIT_OPTIONAL_LOCKS", "0")] {
862 assert!(env.contains(&(pair.0.to_string(), pair.1.to_string())), "{pair:?} is set inside too: {env:?}");
863 }
864 }
865 assert_eq!(test_support::host_runs_for(&name), host_runs, "git was started on the host for a container agent's folder");
866 }
867
868 #[tokio::test]
870 async fn a_container_agents_folder_has_no_git_facts_while_its_container_is_not_running() {
871 let (dir, top, sub, name) = host_repository();
872 container_folders::add_for_test(dir.path(), &format!("agentmux-stopped-{name}"), "/workspace");
873 for folder in [&top, &sub] {
874 let s = git_status(folder).await;
875 assert!(!s.in_repo && s.entries.is_empty() && s.error.is_none(), "{s:?}");
876 assert_eq!(safe_git_line(folder, &["rev-parse", "--show-prefix"]).await, None);
877 assert_eq!(safe_toplevel(folder).await, None);
878 assert!(matches!(safe_status_porcelain(folder, &[]).await, Err(StatusError::Settings(_))), "no status run");
879 }
880 assert_eq!(test_support::host_runs_for(&name), 0, "git was started on the host for a container agent's folder");
881 }
882
883 #[tokio::test]
884 async fn a_folder_outside_any_repository_has_no_markers() {
885 let dir = tempfile::tempdir().unwrap();
886 let s = git_status(&dir.path().to_string_lossy()).await;
887 assert!(s.error.is_none(), "{s:?}");
890 }
891}