Skip to main content

git_editor/rewrite/
engine.rs

1//! History rewrite engine shared by every write mode.
2//!
3//! Callers describe *what* should change with a [`Plan`] (edits keyed by the
4//! original commit id); [`apply`] recreates only the commits that must change:
5//!
6//! * a commit with no edit whose parents are unchanged is reused as-is, so its
7//!   id, signature and every header stay byte-identical;
8//! * a recreated commit keeps its raw headers (`encoding`, `mergetag`, …) and
9//!   raw message bytes; only `parent`, the edited `author`/`committer` fields
10//!   and the now-invalid `gpgsig` headers change;
11//! * the branch ref is moved with a compare-and-swap against the tip the plan
12//!   was built from.
13
14use crate::utils::message_trailers::rewrite_author_trailers;
15use crate::utils::types::Result;
16use git2::{ErrorCode, ObjectType, Oid, Repository, Sort};
17use std::collections::HashMap;
18
19/// What happens to the committer of a commit whose author fields are edited.
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
21pub enum CommitterMode {
22    /// Committer name/email/date follow whichever author fields were edited.
23    #[default]
24    MatchAuthor,
25    /// Committer line is left byte-identical.
26    Keep,
27}
28
29/// A git timestamp: seconds since the epoch plus the UTC offset in minutes.
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31pub struct GitTime {
32    pub seconds: i64,
33    pub offset_minutes: i32,
34}
35
36impl GitTime {
37    pub fn new(seconds: i64, offset_minutes: i32) -> Self {
38        Self {
39            seconds,
40            offset_minutes,
41        }
42    }
43
44    fn header_value(&self) -> String {
45        let sign = if self.offset_minutes < 0 { '-' } else { '+' };
46        let abs = self.offset_minutes.abs();
47        format!("{} {}{:02}{:02}", self.seconds, sign, abs / 60, abs % 60)
48    }
49}
50
51/// Requested changes for one commit. `None` keeps the original value.
52#[derive(Debug, Clone, Default, PartialEq, Eq)]
53pub struct Edit {
54    pub name: Option<String>,
55    pub email: Option<String>,
56    pub time: Option<GitTime>,
57    pub message: Option<String>,
58}
59
60impl Edit {
61    pub fn is_empty(&self) -> bool {
62        self.name.is_none() && self.email.is_none() && self.time.is_none() && self.message.is_none()
63    }
64
65    fn touches_author(&self) -> bool {
66        self.name.is_some() || self.email.is_some() || self.time.is_some()
67    }
68}
69
70/// Edits keyed by original commit id, plus the committer policy.
71#[derive(Debug, Clone, Default)]
72pub struct Plan {
73    pub edits: HashMap<Oid, Edit>,
74    pub committer: CommitterMode,
75}
76
77/// The branch a rewrite will move.
78#[derive(Debug, Clone)]
79pub struct BranchHead {
80    pub refname: String,
81    pub shorthand: String,
82    pub head: Oid,
83}
84
85/// Result of [`apply`].
86#[derive(Debug, Clone)]
87pub struct Outcome {
88    pub branch: String,
89    pub old_head: Oid,
90    pub new_head: Oid,
91    /// `(original, rewritten)` for every commit that was recreated.
92    pub rewritten: Vec<(Oid, Oid)>,
93    /// Commits reused unchanged (same id).
94    pub reused: usize,
95    /// Recreated commits that carried a signature which had to be dropped.
96    pub signatures_dropped: usize,
97    /// Ref holding the pre-rewrite tip (`refs/git-editor/backup/<branch>`).
98    pub backup_ref: Option<String>,
99    /// Other branches/tags that still contain rewritten (old) commits.
100    pub stale_refs: Vec<String>,
101}
102
103impl Outcome {
104    pub fn changed(&self) -> bool {
105        self.old_head != self.new_head
106    }
107}
108
109/// Resolve the checked-out branch, rejecting states a rewrite cannot handle.
110pub fn current_branch(repo: &Repository) -> Result<BranchHead> {
111    if repo.head_detached().unwrap_or(false) {
112        return Err(
113            "HEAD is detached; check out a branch before rewriting (e.g. `git switch main`)".into(),
114        );
115    }
116    let head = match repo.head() {
117        Ok(head) => head,
118        Err(e) if matches!(e.code(), ErrorCode::UnbornBranch | ErrorCode::NotFound) => {
119            return Err("Repository has no commits yet; nothing to rewrite".into())
120        }
121        Err(e) => return Err(e.into()),
122    };
123    if !head.is_branch() {
124        return Err("HEAD does not point to a local branch; check out a branch first".into());
125    }
126    let refname = head
127        .name()
128        .map_err(|_| "HEAD reference name is not valid UTF-8")?
129        .to_string();
130    let shorthand = head.shorthand().unwrap_or(&refname).to_string();
131    let head_oid = head.target().ok_or("HEAD is a symbolic reference")?;
132    Ok(BranchHead {
133        refname,
134        shorthand,
135        head: head_oid,
136    })
137}
138
139/// Commits reachable from `tip`, oldest first (parents before children).
140pub fn history(repo: &Repository, tip: Oid) -> Result<Vec<Oid>> {
141    let mut revwalk = repo.revwalk()?;
142    revwalk.push(tip)?;
143    revwalk.set_sorting(Sort::TOPOLOGICAL | Sort::TIME)?;
144    let mut oids = revwalk.collect::<std::result::Result<Vec<_>, _>>()?;
145    oids.reverse();
146    Ok(oids)
147}
148
149/// Reject values that would corrupt a commit header line.
150pub fn validate_identity_part(value: &str, what: &str) -> Result<()> {
151    if value.trim().is_empty() {
152        return Err(format!("{what} cannot be empty").into());
153    }
154    if let Some(c) = value
155        .chars()
156        .find(|c| matches!(c, '<' | '>' | '\n' | '\r' | '\0'))
157    {
158        return Err(format!("{what} contains an invalid character {c:?}").into());
159    }
160    Ok(())
161}
162
163/// Apply `plan` to the checked-out branch, which must still point at `expected_head`.
164pub fn apply(repo: &Repository, plan: &Plan, expected_head: Oid) -> Result<Outcome> {
165    for edit in plan.edits.values() {
166        if let Some(name) = &edit.name {
167            validate_identity_part(name, "Author name")?;
168        }
169        if let Some(email) = &edit.email {
170            validate_identity_part(email, "Author email")?;
171        }
172    }
173
174    let branch = current_branch(repo)?;
175    if branch.head != expected_head {
176        return Err(format!(
177            "Branch '{}' moved while preparing the rewrite (expected {}, found {}); nothing was changed, re-run the command",
178            branch.shorthand, expected_head, branch.head
179        )
180        .into());
181    }
182
183    let odb = repo.odb()?;
184    let mut new_ids: HashMap<Oid, Oid> = HashMap::new();
185    let mut rewritten = Vec::new();
186    let mut reused = 0;
187    let mut signatures_dropped = 0;
188
189    for oid in history(repo, branch.head)? {
190        let commit = repo.find_commit(oid)?;
191        let parents: Vec<Oid> = commit
192            .parent_ids()
193            .map(|p| *new_ids.get(&p).unwrap_or(&p))
194            .collect();
195        let parents_changed = parents
196            .iter()
197            .ne(commit.parent_ids().collect::<Vec<_>>().iter());
198        let edit = plan.edits.get(&oid).filter(|e| !e.is_empty());
199
200        if edit.is_none() && !parents_changed {
201            new_ids.insert(oid, oid);
202            reused += 1;
203            continue;
204        }
205
206        let (buffer, had_signature) = build_commit(
207            &commit,
208            &parents,
209            edit.unwrap_or(&Edit::default()),
210            plan.committer,
211        )?;
212        let new_oid = odb.write(ObjectType::Commit, &buffer)?;
213        if had_signature {
214            signatures_dropped += 1;
215        }
216        if new_oid == oid {
217            reused += 1;
218        } else {
219            rewritten.push((oid, new_oid));
220        }
221        new_ids.insert(oid, new_oid);
222    }
223
224    let new_head = *new_ids.get(&branch.head).unwrap_or(&branch.head);
225    let mut backup_ref = None;
226    let mut stale_refs = Vec::new();
227    if new_head != branch.head {
228        let backup = format!("{BACKUP_PREFIX}{}", branch.shorthand);
229        repo.reference(
230            &backup,
231            branch.head,
232            true,
233            "git-editor: tip before history rewrite",
234        )?;
235        repo.reference_matching(
236            &branch.refname,
237            new_head,
238            true,
239            branch.head,
240            "git-editor: history rewritten",
241        )?;
242        backup_ref = Some(backup);
243        stale_refs = refs_containing(repo, &branch.refname, &rewritten, &new_ids)?;
244    }
245
246    Ok(Outcome {
247        branch: branch.shorthand,
248        old_head: branch.head,
249        new_head,
250        rewritten,
251        reused,
252        signatures_dropped,
253        backup_ref,
254        stale_refs,
255    })
256}
257
258/// Namespace of the backup refs written before every rewrite.
259pub const BACKUP_PREFIX: &str = "refs/git-editor/backup/";
260
261/// Local branches and tags (other than `current`) that still reach a rewritten commit.
262fn refs_containing(
263    repo: &Repository,
264    current: &str,
265    rewritten: &[(Oid, Oid)],
266    new_ids: &HashMap<Oid, Oid>,
267) -> Result<Vec<String>> {
268    // Only the earliest rewritten commits matter: anything reaching a later
269    // rewritten commit also reaches one of these.
270    let roots: Vec<Oid> = rewritten
271        .iter()
272        .map(|(old, _)| *old)
273        .filter(|old| {
274            repo.find_commit(*old)
275                .map(|c| c.parent_ids().all(|p| new_ids.get(&p) == Some(&p)))
276                .unwrap_or(false)
277        })
278        .collect();
279
280    let mut stale = Vec::new();
281    for reference in repo.references()? {
282        let reference = reference?;
283        let Ok(name) = reference.name() else {
284            continue;
285        };
286        if name == current || !(name.starts_with("refs/heads/") || name.starts_with("refs/tags/")) {
287            continue;
288        }
289        let Ok(target) = reference.peel_to_commit() else {
290            continue;
291        };
292        let target = target.id();
293        let reaches_old = roots.iter().any(|root| {
294            target == *root || repo.graph_descendant_of(target, *root).unwrap_or(false)
295        });
296        if reaches_old {
297            stale.push(name.to_string());
298        }
299    }
300    stale.sort();
301    Ok(stale)
302}
303
304/// One header field of a raw commit: its key and the full bytes of the field
305/// (key, value and continuation lines, each terminated by `\n`).
306struct HeaderField<'a> {
307    key: &'a [u8],
308    raw: &'a [u8],
309}
310
311fn parse_header(raw: &[u8]) -> Vec<HeaderField<'_>> {
312    let mut fields: Vec<HeaderField<'_>> = Vec::new();
313    let mut start = 0;
314    while start < raw.len() {
315        let end = raw[start..]
316            .iter()
317            .position(|&b| b == b'\n')
318            .map_or(raw.len(), |p| start + p + 1);
319        if raw[start] == b' ' {
320            // Continuation line: extend the previous field.
321            if let Some(last) = fields.last_mut() {
322                let field_start = last.raw.as_ptr() as usize - raw.as_ptr() as usize;
323                last.raw = &raw[field_start..end];
324            }
325        } else {
326            let line = &raw[start..end];
327            let key_len = line.iter().position(|&b| b == b' ').unwrap_or(line.len());
328            fields.push(HeaderField {
329                key: &line[..key_len],
330                raw: line,
331            });
332        }
333        start = end;
334    }
335    fields
336}
337
338/// Split a raw `Name <email> seconds offset` signature value.
339struct RawSignature {
340    name: Vec<u8>,
341    email: Vec<u8>,
342    time: Vec<u8>,
343}
344
345fn parse_signature(field: &[u8], key: &[u8]) -> Option<RawSignature> {
346    let value = field.strip_prefix(key)?.strip_prefix(b" ")?;
347    let value = value.strip_suffix(b"\n").unwrap_or(value);
348    let lt = value.iter().position(|&b| b == b'<')?;
349    let gt = value.iter().rposition(|&b| b == b'>')?;
350    if gt < lt {
351        return None;
352    }
353    let name = value[..lt]
354        .strip_suffix(b" ")
355        .unwrap_or(&value[..lt])
356        .to_vec();
357    let email = value[lt + 1..gt].to_vec();
358    let time = value[gt + 1..]
359        .strip_prefix(b" ")
360        .unwrap_or(&value[gt + 1..])
361        .to_vec();
362    Some(RawSignature { name, email, time })
363}
364
365fn signature_line(key: &str, name: &[u8], email: &[u8], time: &[u8]) -> Vec<u8> {
366    let mut line = Vec::with_capacity(key.len() + name.len() + email.len() + time.len() + 8);
367    line.extend_from_slice(key.as_bytes());
368    line.push(b' ');
369    line.extend_from_slice(name);
370    line.extend_from_slice(b" <");
371    line.extend_from_slice(email);
372    line.extend_from_slice(b"> ");
373    line.extend_from_slice(time);
374    line.push(b'\n');
375    line
376}
377
378/// Build the raw bytes of the recreated commit. Returns whether a signature was dropped.
379fn build_commit(
380    commit: &git2::Commit<'_>,
381    parents: &[Oid],
382    edit: &Edit,
383    committer_mode: CommitterMode,
384) -> Result<(Vec<u8>, bool)> {
385    let header = commit.raw_header_bytes();
386    let fields = parse_header(header);
387    let mut out = Vec::with_capacity(header.len() + commit.message_raw_bytes().len() + 64);
388    let mut had_signature = false;
389
390    let orig_author = fields
391        .iter()
392        .find(|f| f.key == b"author")
393        .and_then(|f| parse_signature(f.raw, b"author"))
394        .ok_or("commit has an unparsable author line")?;
395    let new_name = edit
396        .name
397        .as_ref()
398        .map_or(orig_author.name.clone(), |n| n.as_bytes().to_vec());
399    let new_email = edit
400        .email
401        .as_ref()
402        .map_or(orig_author.email.clone(), |e| e.as_bytes().to_vec());
403    let new_time = edit
404        .time
405        .map_or(orig_author.time.clone(), |t| t.header_value().into_bytes());
406
407    for field in &fields {
408        match field.key {
409            b"tree" => {
410                out.extend_from_slice(field.raw);
411                for parent in parents {
412                    out.extend_from_slice(format!("parent {parent}\n").as_bytes());
413                }
414            }
415            b"parent" => {}
416            b"author" if edit.touches_author() => {
417                out.extend(signature_line("author", &new_name, &new_email, &new_time));
418            }
419            b"committer"
420                if edit.touches_author() && committer_mode == CommitterMode::MatchAuthor =>
421            {
422                let orig = parse_signature(field.raw, b"committer")
423                    .ok_or("commit has an unparsable committer line")?;
424                let name = if edit.name.is_some() {
425                    &new_name
426                } else {
427                    &orig.name
428                };
429                let email = if edit.email.is_some() {
430                    &new_email
431                } else {
432                    &orig.email
433                };
434                let time = if edit.time.is_some() {
435                    &new_time
436                } else {
437                    &orig.time
438                };
439                out.extend(signature_line("committer", name, email, time));
440            }
441            b"gpgsig" | b"gpgsig-sha256" => had_signature = true,
442            _ => out.extend_from_slice(field.raw),
443        }
444    }
445
446    out.push(b'\n');
447    out.extend(new_message(
448        commit,
449        edit,
450        &orig_author,
451        &new_name,
452        &new_email,
453    ));
454    Ok((out, had_signature))
455}
456
457fn new_message(
458    commit: &git2::Commit<'_>,
459    edit: &Edit,
460    orig_author: &RawSignature,
461    new_name: &[u8],
462    new_email: &[u8],
463) -> Vec<u8> {
464    let base: Vec<u8> = match &edit.message {
465        Some(message) if message.ends_with('\n') => message.as_bytes().to_vec(),
466        Some(message) => format!("{message}\n").into_bytes(),
467        None => commit.message_raw_bytes().to_vec(),
468    };
469    let identity_changed = edit.name.is_some() || edit.email.is_some();
470    if !identity_changed {
471        return base;
472    }
473    match (
474        std::str::from_utf8(&base),
475        std::str::from_utf8(&orig_author.name),
476        std::str::from_utf8(&orig_author.email),
477        std::str::from_utf8(new_name),
478        std::str::from_utf8(new_email),
479    ) {
480        (Ok(message), Ok(old_name), Ok(old_email), Ok(name), Ok(email)) => {
481            rewrite_author_trailers(message, old_name, old_email, name, email).into_bytes()
482        }
483        // Non-UTF-8 message or identity: keep the bytes untouched.
484        _ => base,
485    }
486}