greengate_runtime/migrate/
tracked.rs1use std::path::{Path, PathBuf};
25
26use super::{run_git, GitFn, MigrateError};
27use crate::names as n;
28use crate::names::old;
29
30const FILES: &[(&str, &str)] = &[(old::MANIFEST, n::MANIFEST), (old::PACK_FILE, n::PACK_FILE)];
32
33const MARKED: &[&str] = &["AGENTS.md", "CLAUDE.md"];
35
36const ATTEST_INPUTS: &str = ".github/attest-inputs";
38
39const LEFTOVER_LINES: usize = 20;
41
42#[derive(Debug, Default, Clone, PartialEq, Eq)]
44pub struct Staged {
45 pub renamed: Vec<(&'static str, &'static str)>,
47 pub markers: Vec<&'static str>,
49 pub attest_inputs: bool,
51 pub leftovers: Vec<String>,
54 pub leftover_count: usize,
56}
57
58impl Staged {
59 pub fn changed(&self) -> bool {
61 !self.renamed.is_empty() || !self.markers.is_empty() || self.attest_inputs
62 }
63}
64
65pub fn needs(root: &Path, git: &GitFn<'_>) -> Result<bool, MigrateError> {
69 for &(old_name, _) in FILES {
70 if root.join(old_name).exists() && is_tracked(root, old_name, git)? {
71 return Ok(true);
72 }
73 }
74 for &name in MARKED {
75 if tracked_needs_edit(root, name, git, swap_markers)? {
76 return Ok(true);
77 }
78 }
79 tracked_needs_edit(root, ATTEST_INPUTS, git, swap_inputs)
80}
81
82fn tracked_needs_edit(
85 root: &Path,
86 name: &str,
87 git: &GitFn<'_>,
88 edit: fn(&str) -> Option<String>,
89) -> Result<bool, MigrateError> {
90 let Some(text) = read_if_present(&root.join(name))? else {
91 return Ok(false);
92 };
93 Ok(edit(&text).is_some() && is_tracked(root, name, git)?)
94}
95
96fn read_if_present(path: &Path) -> Result<Option<String>, MigrateError> {
99 match std::fs::read_to_string(path) {
100 Ok(text) => Ok(Some(text)),
101 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
102 Err(e) => Err(super::io("read", path)(e)),
103 }
104}
105
106pub fn migrate_tracked(root: &Path, git: &GitFn<'_>) -> Result<Staged, MigrateError> {
110 let mut staged = Staged::default();
111 for &(old_name, new_name) in FILES {
112 let (source, target) = (root.join(old_name), root.join(new_name));
113 if source.exists() && target.exists() && is_tracked(root, old_name, git)? {
115 return Err(MigrateError::BothCommitted { source, target });
116 }
117 }
118 for &(old_name, new_name) in FILES {
119 if !root.join(old_name).exists() || !is_tracked(root, old_name, git)? {
120 continue;
121 }
122 in_tree(root, git, &["mv", "--", old_name, new_name])?;
123 staged.renamed.push((old_name, new_name));
124 }
125 for &name in MARKED {
126 if rewrite(root, name, git, swap_markers)? {
127 staged.markers.push(name);
128 }
129 }
130 staged.attest_inputs = rewrite(root, ATTEST_INPUTS, git, swap_inputs)?;
131 let (leftovers, count) = leftovers(root, git)?;
132 staged.leftovers = leftovers;
133 staged.leftover_count = count;
134 Ok(staged)
135}
136
137fn in_tree(root: &Path, git: &GitFn<'_>, args: &[&str]) -> Result<Option<String>, MigrateError> {
139 let root_arg = root.to_string_lossy();
140 let mut all = vec!["-C", root_arg.as_ref()];
141 all.extend_from_slice(args);
142 run_git(git, None, &all)
143}
144
145fn is_tracked(root: &Path, name: &str, git: &GitFn<'_>) -> Result<bool, MigrateError> {
146 Ok(in_tree(root, git, &["ls-files", "--", name])?.is_some_and(|out| !out.trim().is_empty()))
147}
148
149fn rewrite(
153 root: &Path,
154 name: &str,
155 git: &GitFn<'_>,
156 edit: fn(&str) -> Option<String>,
157) -> Result<bool, MigrateError> {
158 let path: PathBuf = root.join(name);
159 let Some(text) = read_if_present(&path)? else {
160 return Ok(false);
161 };
162 let Some(edited) = edit(&text) else {
163 return Ok(false);
164 };
165 if !is_tracked(root, name, git)? {
166 return Ok(false);
167 }
168 std::fs::write(&path, edited).map_err(super::io("write", &path))?;
169 in_tree(root, git, &["add", "--", name])?;
170 Ok(true)
171}
172
173fn swap_markers(text: &str) -> Option<String> {
176 let has_old = text.contains(old::AGENTS_START) || text.contains(old::AGENTS_END);
177 if !has_old || text.contains(n::AGENTS_START) || text.contains(n::AGENTS_END) {
178 return None;
179 }
180 Some(
181 text.replacen(old::AGENTS_START, n::AGENTS_START, 1)
182 .replacen(old::AGENTS_END, n::AGENTS_END, 1),
183 )
184}
185
186fn swap_inputs(text: &str) -> Option<String> {
190 let respelled: String = text.split_inclusive('\n').map(respell_line).collect();
191 (respelled != text).then_some(respelled)
192}
193
194fn respell_line(line: &str) -> String {
197 if line.trim_start().starts_with('#') {
198 return line.to_string();
199 }
200 line.split_inclusive(char::is_whitespace)
201 .map(|piece| {
202 let token = piece.trim_end_matches(char::is_whitespace);
203 let gap = &piece[token.len()..];
204 format!("{}{gap}", respelled(token).unwrap_or(token))
205 })
206 .collect()
207}
208
209fn respelled(token: &str) -> Option<&'static str> {
211 FILES
212 .iter()
213 .find(|(old_name, _)| *old_name == token)
214 .map(|(_, new_name)| *new_name)
215}
216
217fn leftovers(root: &Path, git: &GitFn<'_>) -> Result<(Vec<String>, usize), MigrateError> {
220 let out = in_tree(
221 root,
222 git,
223 &[
224 "grep",
225 "-n",
226 "-I",
227 "-F",
228 "-e",
229 old::MANIFEST,
230 "-e",
231 old::PACK_FILE,
232 "-e",
233 old::ENV_PREFIX,
234 "--",
235 ".",
236 ],
237 )?;
238 let lines: Vec<String> = out
240 .unwrap_or_default()
241 .lines()
242 .filter(|line| {
243 line.contains(old::MANIFEST)
244 || line.contains(old::PACK_FILE)
245 || line
246 .replace(old::FOREIGN_ENV_PREFIX, "")
247 .contains(old::ENV_PREFIX)
248 })
249 .map(|line| line.chars().take(200).collect())
250 .collect();
251 let count = lines.len();
252 Ok((lines.into_iter().take(LEFTOVER_LINES).collect(), count))
253}
254
255#[cfg(test)]
256mod tests {
257 use super::*;
258
259 #[test]
260 fn the_old_marker_pair_is_respelled_once() {
261 let before = format!("a\n{}\nbody\n{}\nb\n", old::AGENTS_START, old::AGENTS_END);
262 let after = swap_markers(&before).unwrap();
263 assert_eq!(
264 after,
265 format!("a\n{}\nbody\n{}\nb\n", n::AGENTS_START, n::AGENTS_END)
266 );
267 assert_eq!(swap_markers(&after), None, "a second run changes nothing");
268 assert_eq!(swap_markers("no markers\n"), None);
269 }
270
271 #[test]
273 fn a_file_with_both_pairs_is_left_alone() {
274 let both = format!(
275 "{}\n{}\n{}\n{}\n",
276 old::AGENTS_START,
277 old::AGENTS_END,
278 n::AGENTS_START,
279 n::AGENTS_END
280 );
281 assert_eq!(swap_markers(&both), None);
282 }
283
284 #[test]
285 fn attest_inputs_tokens_are_respelled_and_comments_kept() {
286 let before = format!(
287 "# lists {m} on purpose\ngate a {m} b\tc {p}\nother x{m} y\n",
288 m = old::MANIFEST,
289 p = old::PACK_FILE
290 );
291 let after = swap_inputs(&before).unwrap();
292 assert_eq!(
293 after,
294 format!(
295 "# lists {m} on purpose\ngate a {nm} b\tc {np}\nother x{m} y\n",
296 m = old::MANIFEST,
297 nm = n::MANIFEST,
298 np = n::PACK_FILE
299 )
300 );
301 assert_eq!(swap_inputs(&after), None);
302 }
303}