agentmux_srv_core/backend/
git_exclude.rs1use std::fs;
19use std::io::Write;
20use std::path::{Path, PathBuf};
21
22const MOST_PARENTS: usize = 64;
24const COMMENT: &str = "# AgentMux: the startup files it writes for an agent, kept out of commits";
25
26pub fn keep_out_of_git(work_dir: &Path, names: &[&str]) {
29 let resolved = fs::canonicalize(work_dir).unwrap_or_else(|_| work_dir.to_path_buf());
32 let work_dir = resolved.as_path();
33 let Some((root, exclude)) = find_exclude(work_dir) else {
34 return;
35 };
36 let Ok(under_root) = work_dir.strip_prefix(&root) else {
37 return;
38 };
39 let patterns: Vec<String> = names
40 .iter()
41 .map(|name| pattern_for(under_root, name))
42 .collect();
43 if let Err(e) = add_patterns(&exclude, &patterns) {
44 tracing::warn!(exclude = %exclude.display(), error = %e, "git_exclude: could not keep the startup file out of commits");
45 }
46}
47
48fn find_exclude(work_dir: &Path) -> Option<(PathBuf, PathBuf)> {
50 for dir in work_dir.ancestors().take(MOST_PARENTS) {
51 let dot_git = dir.join(".git");
52 let meta = match fs::symlink_metadata(&dot_git) {
53 Ok(m) => m,
54 Err(_) => continue,
55 };
56 let git_dir = if meta.is_dir() {
57 dot_git
58 } else if meta.is_file() {
59 git_dir_from_file(dir, &dot_git)?
60 } else {
61 return None;
62 };
63 return Some((
64 dir.to_path_buf(),
65 common_dir(&git_dir).join("info").join("exclude"),
66 ));
67 }
68 None
69}
70
71fn git_dir_from_file(dir: &Path, dot_git: &Path) -> Option<PathBuf> {
74 let text = fs::read_to_string(dot_git).ok()?;
75 let target = text.lines().find_map(|l| l.strip_prefix("gitdir:"))?.trim();
76 if target.is_empty() {
77 return None;
78 }
79 Some(dir.join(target))
80}
81
82fn common_dir(git_dir: &Path) -> PathBuf {
84 match fs::read_to_string(git_dir.join("commondir")) {
85 Ok(text) if !text.trim().is_empty() => git_dir.join(text.trim()),
86 _ => git_dir.to_path_buf(),
87 }
88}
89
90fn pattern_for(under_root: &Path, name: &str) -> String {
93 let mut parts: Vec<String> = under_root
94 .components()
95 .map(|c| c.as_os_str().to_string_lossy().into_owned())
96 .collect();
97 parts.extend(
98 name.split('/')
99 .filter(|p| !p.is_empty())
100 .map(str::to_string),
101 );
102 format!("/{}", escape(&parts.join("/")))
103}
104
105fn escape(path: &str) -> String {
106 let mut out = String::with_capacity(path.len());
107 for c in path.chars() {
108 if matches!(c, '\\' | '*' | '?' | '[') {
109 out.push('\\');
110 }
111 out.push(c);
112 }
113 if out.ends_with(' ') {
114 out.insert(out.len() - 1, '\\');
115 }
116 out
117}
118
119fn add_patterns(exclude: &Path, patterns: &[String]) -> std::io::Result<()> {
120 if let Ok(m) = fs::symlink_metadata(exclude) {
122 if !m.is_file() {
123 return Ok(());
124 }
125 }
126 let existing = fs::read_to_string(exclude).unwrap_or_default();
127 let missing: Vec<&String> = patterns
128 .iter()
129 .filter(|p| !existing.lines().any(|l| l.trim_end() == p.as_str()))
130 .collect();
131 if missing.is_empty() {
132 return Ok(());
133 }
134 if let Some(parent) = exclude.parent() {
135 fs::create_dir_all(parent)?;
136 }
137 let mut add = String::new();
138 if !existing.is_empty() && !existing.ends_with('\n') {
139 add.push('\n');
140 }
141 if !existing.lines().any(|l| l == COMMENT) {
142 add.push_str(COMMENT);
143 add.push('\n');
144 }
145 for p in missing {
146 add.push_str(p);
147 add.push('\n');
148 }
149 fs::OpenOptions::new()
150 .create(true)
151 .append(true)
152 .open(exclude)?
153 .write_all(add.as_bytes())
154}
155
156#[cfg(test)]
157#[path = "git_exclude_tests.rs"]
158mod tests;