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