Skip to main content

greengate_runtime/migrate/
tracked.rs

1//! `greengate migrate --tracked`: the names a repository COMMITS, renamed in
2//! its work tree and staged, for the repository to commit (the fleet sweep
3//! lands one such commit per repository).
4//!
5//! Never part of the automatic first run: a tracked rename is a change to
6//! the repository, and greengate 3.x, greenpiste and relais before 0.54
7//! read only `amont.conf`, so it happens when someone asks for it.
8//!
9//! What it does, each step skipped when there is nothing to do:
10//!
11//! - `amont.conf` → `greengate.conf` and `amont.pack` → `greengate.pack`,
12//!   with `git mv`, when tracked (an untracked one is a local file, left as
13//!   it is). The content is unchanged: trust is the
14//!   content's blob id, so a trusted manifest stays trusted, and the
15//!   `amont:pack:*` markers inside it are still read until the census.
16//! - the AGENTS.md / CLAUDE.md marker pair, old spelling to new; what lies
17//!   between the markers is left for `greengate agents-md` to regenerate.
18//! - `.github/attest-inputs`: a path token naming an old file.
19//!
20//! Then it lists, without touching them, the tracked lines that still name
21//! an old file or an `AMONT_` variable (CI, dotfiles, docs): those need a
22//! person's reading, not a substitution.
23
24use std::path::{Path, PathBuf};
25
26use super::{run_git, GitFn, MigrateError};
27use crate::names as n;
28use crate::names::old;
29
30/// The committed files renamed, old name first.
31const FILES: &[(&str, &str)] = &[(old::MANIFEST, n::MANIFEST), (old::PACK_FILE, n::PACK_FILE)];
32
33/// The generated files whose marker pair is rewritten.
34const MARKED: &[&str] = &["AGENTS.md", "CLAUDE.md"];
35
36/// The attest inputs file, which lists the manifest by name.
37const ATTEST_INPUTS: &str = ".github/attest-inputs";
38
39/// At most this many leftover lines are listed; the rest are counted.
40const LEFTOVER_LINES: usize = 20;
41
42/// What `migrate --tracked` changed and staged, and what it left.
43#[derive(Debug, Default, Clone, PartialEq, Eq)]
44pub struct Staged {
45    /// Files renamed, old name first.
46    pub renamed: Vec<(&'static str, &'static str)>,
47    /// Files whose marker pair was rewritten.
48    pub markers: Vec<&'static str>,
49    /// Whether `.github/attest-inputs` was rewritten.
50    pub attest_inputs: bool,
51    /// Tracked lines still naming an old name, `path:line:text`, at most
52    /// [`LEFTOVER_LINES`] of them.
53    pub leftovers: Vec<String>,
54    /// How many leftover lines there were in all.
55    pub leftover_count: usize,
56}
57
58impl Staged {
59    /// Whether anything was changed.
60    pub fn changed(&self) -> bool {
61        !self.renamed.is_empty() || !self.markers.is_empty() || self.attest_inputs
62    }
63}
64
65/// Does the work tree at `root` still commit a 3.x name that
66/// [`migrate_tracked`] would change? The same tests it applies, so a
67/// repository listed as due is one it changes.
68pub 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
82/// Is `name` tracked, and would `edit` change it? An untracked file is a
83/// local one, never the rename's to touch.
84fn 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
96/// The file's text, `None` when it does not exist; any other read error is
97/// an error, never "absent".
98fn 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
106/// Rename the tracked names in the work tree at `root` (its top level) and
107/// stage them. Refuses, changing nothing, when both spellings of a file
108/// exist.
109pub 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        // An untracked old file is a local one, left as it is: no conflict.
114        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
137/// `git -C <root> <args>`.
138fn 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
149/// Rewrite and stage `name` under `root` with `edit`, when the file is
150/// tracked and `edit` changes it; an untracked one is never touched, since
151/// nothing could put it back. Whether it was rewritten.
152fn 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
173/// The old marker pair, respelled, when the file carries it and not the new
174/// one; `None` when there is nothing to change.
175fn 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
186/// Each whitespace-separated token naming an old file, respelled, on the
187/// lines that are not comments; `None` when no token named one. Spacing and
188/// comments are kept byte for byte.
189fn 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
194/// One line of [`swap_inputs`]: a comment as it is, else each token that
195/// names an old file respelled, with the whitespace after it kept.
196fn 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
209/// `token`'s new spelling, when it names an old file.
210fn 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
217/// The tracked lines that still name an old file or an `AMONT_` variable,
218/// at most [`LEFTOVER_LINES`], and how many there were.
219fn 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    // A line naming only greenpiste's own variables is greenpiste's.
239    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    /// A file carrying both pairs is a hand edit: not guessed at.
272    #[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}