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, the hook before its 3.30.0 and relais
7//! before 0.54 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//! - `.amont-audit-waivers` → `.greengate-audit-waivers`, the same way.
17//! - the AGENTS.md / CLAUDE.md marker pair, old spelling to new; what lies
18//!   between the markers is left for `greengate agents-md` to regenerate.
19//! - `.github/attest-inputs`: a path token naming an old file.
20//!
21//! Then it lists, without touching them, the tracked lines that still name
22//! an old file or an `AMONT_` variable (CI, dotfiles, docs): those need a
23//! person's reading, not a substitution.
24
25use std::path::{Path, PathBuf};
26
27use super::{run_git, GitFn, MigrateError};
28use crate::names as n;
29use crate::names::old;
30
31/// The committed files renamed, old name first.
32const FILES: &[(&str, &str)] = &[
33    (old::MANIFEST, n::MANIFEST),
34    (old::PACK_FILE, n::PACK_FILE),
35    (old::AUDIT_WAIVERS, n::AUDIT_WAIVERS),
36];
37
38/// The generated files whose marker pair is rewritten.
39const MARKED: &[&str] = &["AGENTS.md", "CLAUDE.md"];
40
41/// The attest inputs file, which lists the manifest by name.
42const ATTEST_INPUTS: &str = ".github/attest-inputs";
43
44/// At most this many leftover lines are listed; the rest are counted.
45const LEFTOVER_LINES: usize = 20;
46
47/// What `migrate --tracked` changed and staged, and what it left.
48#[derive(Debug, Default, Clone, PartialEq, Eq)]
49pub struct Staged {
50    /// Files renamed, old name first.
51    pub renamed: Vec<(&'static str, &'static str)>,
52    /// Files whose marker pair was rewritten.
53    pub markers: Vec<&'static str>,
54    /// Whether `.github/attest-inputs` was rewritten.
55    pub attest_inputs: bool,
56    /// Tracked lines still naming an old name, `path:line:text`, at most
57    /// [`LEFTOVER_LINES`] of them.
58    pub leftovers: Vec<String>,
59    /// How many leftover lines there were in all.
60    pub leftover_count: usize,
61}
62
63impl Staged {
64    /// Whether anything was changed.
65    pub fn changed(&self) -> bool {
66        !self.renamed.is_empty() || !self.markers.is_empty() || self.attest_inputs
67    }
68}
69
70/// Does the work tree at `root` still commit a 3.x name that
71/// [`migrate_tracked`] would change? The same tests it applies, so a
72/// repository listed as due is one it changes.
73pub 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
87/// Is `name` tracked, and would `edit` change it? An untracked file is a
88/// local one, never the rename's to touch.
89fn 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
101/// The file's text, `None` when it does not exist; any other read error is
102/// an error, never "absent".
103fn 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
111/// Rename the tracked names in the work tree at `root` (its top level) and
112/// stage them. Refuses, changing nothing, when both spellings of a file
113/// exist.
114pub 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        // An untracked old file is a local one, left as it is: no conflict.
119        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
142/// `git -C <root> <args>`.
143fn 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
154/// Rewrite and stage `name` under `root` with `edit`, when the file is
155/// tracked and `edit` changes it; an untracked one is never touched, since
156/// nothing could put it back. Whether it was rewritten.
157fn 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
178/// The old marker pair, respelled, when the file carries it and not the new
179/// one; `None` when there is nothing to change.
180fn 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
191/// Each whitespace-separated token naming an old file, respelled, on the
192/// lines that are not comments; `None` when no token named one. Spacing and
193/// comments are kept byte for byte.
194fn 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
199/// One line of [`swap_inputs`]: a comment as it is, else each token that
200/// names an old file respelled, with the whitespace after it kept.
201fn 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
214/// `token`'s new spelling, when it names an old file.
215fn 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
222/// The tracked lines that still name an old file or an `AMONT_` variable,
223/// at most [`LEFTOVER_LINES`], and how many there were.
224fn 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    // A line naming only greenbelay's own variables is greenbelay's.
244    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    /// A file carrying both pairs is a hand edit: not guessed at.
277    #[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}