Skip to main content

verctl_git/
history.rs

1use std::collections::BTreeMap;
2use std::path::{Path, PathBuf};
3
4use anyhow::{Context, Result, anyhow, bail};
5use gix::bstr::ByteSlice;
6use gix::objs::tree::EntryKind;
7use semver::Version;
8use verctl_core::lookup;
9
10use crate::discover;
11use crate::merge_base::{blob_at, git_path};
12use crate::remote::shallow_hint;
13
14/// The commit that added a file, as the changelog names it.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct AddedBy {
17    /// Full hex SHA of the commit.
18    pub sha: String,
19    /// First line of the commit message.
20    pub subject: String,
21}
22
23/// The commit that added `path`. It is the newest commit on HEAD's
24/// first-parent history whose tree has the file and whose first parent's tree
25/// does not.
26///
27/// A squash merge is that commit, and its subject carries the pull request
28/// number.
29///
30/// When that commit is a merge and another parent already has the file, the
31/// file arrived with the merged branch. The walk then continues down that
32/// parent's first-parent history. A fragment merged from `next` links the pull
33/// request that added it there, instead of the merge.
34///
35/// A merge titled with its pull request, `Title (#N)`, may have branch commits
36/// that name none. That merge is then the commit named instead. A repository
37/// that merges with merge commits thus keeps its pull request links. The
38/// deepest such merge on the way down wins.
39///
40/// The result is `None` in these cases:
41///
42/// - There is no repository, or HEAD does not track the file. A fixture outside
43///   git, or a fragment not committed yet, has no commit to name.
44/// - A shallow clone ends before the adding commit. A commit listed in
45///   `.git/shallow` is the boundary and counts as parentless, and naming it
46///   would link the wrong commit.
47/// - A parent exists but cannot be loaded. It is treated like the shallow
48///   boundary.
49///
50/// # Errors
51///
52/// Returns an error when the shallow boundary cannot be read, or when a tree
53/// or commit message on the walk cannot be read.
54pub fn added_by(root: &Path, path: &Path) -> Result<Option<AddedBy>> {
55    let Ok(repo) = discover(root) else {
56        return Ok(None);
57    };
58    let Ok(head) = repo.head_commit() else {
59        return Ok(None);
60    };
61    added_from(&repo, root, path, head)
62}
63
64/// [`added_by`] from `start` instead of HEAD.
65///
66/// A fragment a candidate's Version PR deleted is gone from HEAD, so its
67/// origin is found from a commit that still contains it: the first parent of
68/// the commit that deleted it.
69///
70/// # Errors
71///
72/// Returns an error when `start` names no commit in the repository, and under
73/// the conditions of [`added_by`].
74pub fn added_by_from(root: &Path, path: &Path, start: &str) -> Result<Option<AddedBy>> {
75    let Ok(repo) = discover(root) else {
76        return Ok(None);
77    };
78    let id =
79        gix::ObjectId::from_hex(start.as_bytes()).with_context(|| format!("commit {start}"))?;
80    let commit = repo
81        .find_commit(id)
82        .with_context(|| format!("commit {start} is not in the repository"))?;
83    added_from(&repo, root, path, commit)
84}
85
86fn added_from(
87    repo: &gix::Repository,
88    root: &Path,
89    path: &Path,
90    head: gix::Commit<'_>,
91) -> Result<Option<AddedBy>> {
92    let Some(rel) = git_path(root, path, repo.workdir()) else {
93        return Ok(None);
94    };
95    if !has_path(&head, &rel)? {
96        return Ok(None);
97    }
98    let boundary: Vec<gix::ObjectId> = repo
99        .shallow_commits()?
100        .map_or_default(|commits| commits.iter().copied().collect());
101    let mut commit = head;
102    let mut named_merge = None;
103    loop {
104        let parents: Vec<gix::ObjectId> = if boundary.contains(&commit.id().detach()) {
105            Vec::new()
106        } else {
107            commit.parent_ids().map(gix::Id::detach).collect()
108        };
109        if parents.is_empty() && !boundary.is_empty() {
110            return Ok(None);
111        }
112        let mut holder = None;
113        for (index, id) in parents.into_iter().enumerate() {
114            let Ok(parent) = repo.find_commit(id) else {
115                return Ok(None);
116            };
117            if has_path(&parent, &rel)? {
118                holder = Some((index, parent));
119                break;
120            }
121        }
122        let added = named(&commit)?;
123        let Some((index, parent)) = holder else {
124            return Ok(Some(match named_merge {
125                Some(merge) if pull_request_number(&added.subject).is_none() => merge,
126                Some(_) | None => added,
127            }));
128        };
129        if index > 0 && pull_request_number(&added.subject).is_some() {
130            named_merge = Some(added);
131        }
132        commit = parent;
133    }
134}
135
136/// A file a commit deleted, as its first parent had it.
137#[derive(Debug, Clone, PartialEq, Eq)]
138#[non_exhaustive]
139pub struct Deleted {
140    /// The file: `dir` as the caller gave it, joined with the file name.
141    pub path: PathBuf,
142    /// Its text in the first parent.
143    pub text: String,
144    /// Full hex SHA of the first parent: the newest commit that contains the
145    /// file.
146    pub parent: String,
147}
148
149/// The files under `dir` that each candidate's Version PR deleted since the
150/// version in `manifest` was last stable, newest first.
151///
152/// The walk follows HEAD's first parents. A commit whose first parent contains
153/// another version in `manifest` set a version. The first such commit that set
154/// a version with no prerelease ends the walk, and its own deletions are left
155/// out: they belong to that stable release. Every other commit that set a
156/// version is a candidate's Version PR, and each file under `dir` its first
157/// parent contains and it does not is listed. The merge queue lands a Version
158/// PR as a merge commit, so the fragments it consumed show in that diff. A
159/// commit that set no version deleted no fragment a release consumed, so its
160/// deletions are skipped. With no stable version on the history, the walk
161/// reads to the root commit.
162///
163/// `read` returns `None` when a revision of the file contains no version, which
164/// counts as a different version.
165///
166/// # Errors
167///
168/// Returns an error when `root` is in no repository, when `manifest` or `dir`
169/// is outside it, or when a commit or tree cannot be read. It returns a
170/// [`lookup::Unavailable`] error naming the commit when the walk reaches a
171/// shallow clone's boundary first, because a stable section built without
172/// the rest would leave changes out.
173pub fn candidate_deletions(
174    root: &Path,
175    manifest: &Path,
176    read: &dyn Fn(&str) -> Option<String>,
177    dir: &Path,
178) -> Result<Vec<Deleted>> {
179    let repo = discover(root).context("reading earlier candidates needs a git repository")?;
180    let workdir = repo.workdir().map(Path::to_path_buf);
181    let manifest_rel = git_path(root, manifest, workdir.as_deref())
182        .with_context(|| format!("{} is not in the repository", manifest.display()))?;
183    let dir_rel = git_path(root, dir, workdir.as_deref())
184        .with_context(|| format!("{} is not in the repository", dir.display()))?;
185    let version_at = |commit: &gix::Commit<'_>| -> Result<Option<String>> {
186        Ok(blob_at(&commit.tree()?, &manifest_rel).and_then(|raw| read(&raw)))
187    };
188    let boundary: Vec<gix::ObjectId> = repo
189        .shallow_commits()?
190        .map_or_default(|commits| commits.iter().copied().collect());
191    let mut commit = repo
192        .head_commit()
193        .context("reading earlier candidates needs HEAD")?;
194    let mut deleted = Vec::new();
195    loop {
196        let version = version_at(&commit)?;
197        if boundary.contains(&commit.id().detach()) {
198            return Err(lookup::unavailable(anyhow!(
199                "cannot read the candidates before commit {}: the clone is shallow; fetch the full history{}",
200                commit.id(),
201                shallow_hint()
202            )));
203        }
204        let Some(parent) = commit.parent_ids().next() else {
205            break;
206        };
207        let parent = repo.find_commit(parent.detach())?;
208        if version_at(&parent)? != version {
209            if version.as_deref().is_some_and(stable) {
210                break;
211            }
212            let files = files_under(&parent, &dir_rel)?;
213            let kept = files_under(&commit, &dir_rel)?;
214            for (name, text) in files {
215                if !kept.contains_key(&name) {
216                    deleted.push(Deleted {
217                        path: dir.join(&name),
218                        text,
219                        parent: parent.id().to_string(),
220                    });
221                }
222            }
223        }
224        commit = parent;
225    }
226    Ok(deleted)
227}
228
229/// Whether `version` is semver with no prerelease.
230fn stable(version: &str) -> bool {
231    Version::parse(version).is_ok_and(|version| version.pre.is_empty())
232}
233
234/// Each file directly under `dir` in `commit`, by its file name, with its
235/// text. `dir` is the directory's path in the repository.
236fn files_under(commit: &gix::Commit<'_>, dir: &Path) -> Result<BTreeMap<PathBuf, String>> {
237    let tree = commit.tree()?;
238    let Some(entry) = tree.lookup_entry_by_path(dir)? else {
239        return Ok(BTreeMap::new());
240    };
241    let Ok(subtree) = entry.object()?.try_into_tree() else {
242        return Ok(BTreeMap::new());
243    };
244    let mut files = BTreeMap::new();
245    for entry in subtree.iter() {
246        let entry = entry?;
247        if !entry.mode().is_blob() {
248            continue;
249        }
250        let blob = entry.object()?.try_into_blob()?;
251        files.insert(
252            PathBuf::from(entry.filename().to_str_lossy().as_ref()),
253            String::from_utf8_lossy(&blob.data).into_owned(),
254        );
255    }
256    Ok(files)
257}
258
259/// A commit that carries a package's release, and how far it sits below HEAD.
260#[derive(Debug, Clone, PartialEq, Eq)]
261#[non_exhaustive]
262pub struct VersionCommit {
263    /// Full hex SHA of the commit.
264    pub sha: String,
265    /// First-parent steps from HEAD: 0 is HEAD itself.
266    pub depth: usize,
267}
268
269impl VersionCommit {
270    /// Build a version commit at `sha` and `depth` first-parent steps below
271    /// HEAD.
272    #[must_use]
273    pub const fn new(sha: String, depth: usize) -> Self {
274        Self { sha, depth }
275    }
276}
277
278/// What a commit contains at a package's path.
279#[derive(Debug)]
280enum PackageFile {
281    /// The commit contains no file at the path.
282    Missing,
283    /// The commit contains a file there, and `read` finds this version in it,
284    /// or none.
285    Present(Option<String>),
286}
287
288/// What `commit` contains at `rel`. Only a path with no tree entry is
289/// [`PackageFile::Missing`]. A directory, submodule or symlink there contains
290/// no version, and a lookup or read failure is an error, so neither passes
291/// as a commit made before the file existed.
292fn package_file_at(
293    commit: &gix::Commit<'_>,
294    rel: &Path,
295    read: &dyn Fn(&str) -> Option<String>,
296) -> Result<PackageFile> {
297    let tree = commit.tree()?;
298    let Some(entry) = tree
299        .lookup_entry_by_path(rel)
300        .with_context(|| format!("reading {} at commit {}", rel.display(), commit.id()))?
301    else {
302        return Ok(PackageFile::Missing);
303    };
304    match entry.mode().kind() {
305        EntryKind::Blob | EntryKind::BlobExecutable => {
306            let blob = entry
307                .object()
308                .with_context(|| format!("reading {} at commit {}", rel.display(), commit.id()))?
309                .detach();
310            Ok(PackageFile::Present(read(&String::from_utf8_lossy(
311                &blob.data,
312            ))))
313        }
314        EntryKind::Tree | EntryKind::Link | EntryKind::Commit => Ok(PackageFile::Present(None)),
315    }
316}
317
318impl PackageFile {
319    /// Whether a release tag on a commit containing this names `wanted`. A
320    /// commit made before the file existed does, because the tag's name renders
321    /// the version. A file that contains another version, or none, does not.
322    fn is_release_of(&self, wanted: &str) -> bool {
323        match self {
324            Self::Missing => true,
325            Self::Present(version) => version.as_deref() == Some(wanted),
326        }
327    }
328}
329
330/// `sha` as the release commit of the version `read` finds in `path` at HEAD,
331/// when HEAD contains `sha` and `sha` carries that version.
332///
333/// A release tag can name a commit other than HEAD and still be that
334/// version's release. Four cases qualify:
335///
336/// - A publish rerun after later commits tagged a newer HEAD at the same
337///   version.
338/// - A version set again after a revert, which keeps the tag from its first
339///   release.
340/// - A tagged commit that left the first-parent history while HEAD keeps it. A
341///   forkctl append publish rewrites a branch and merges it back with its old
342///   tip as the second parent. Only that parent then contains the tagged
343///   commit. The new first-parent commit at the same version may change other
344///   files.
345/// - A tag on a commit made before the package's file existed, such as one
346///   before the version moved to a `VERSION` file. The tag's name renders the
347///   version, so that commit is the release.
348///
349/// In every case the registry already has the version, so the tag's commit is
350/// the release. Only the version is compared, never the tree, and a commit
351/// with no file at `path` has no version to compare.
352///
353/// On the first-parent history the depth is the tagged commit's own. Off it,
354/// the depth is that of the oldest first-parent commit that contains the
355/// tagged commit, the merge that brought it in. `None` means the tag is on a
356/// commit with another version, or on a commit HEAD does not contain.
357///
358/// # Errors
359///
360/// Returns an error when:
361///
362/// - `root` is in no repository;
363/// - `path` is outside it;
364/// - HEAD has no version in `path`;
365/// - a commit or tree cannot be read.
366///
367/// It also returns a [`lookup::Unavailable`] error when the walk reaches a
368/// shallow clone's boundary before finding `sha`. It returns an error too when
369/// no merge-base can be computed between a first-parent commit and `sha`.
370pub fn tagged_commit(
371    root: &Path,
372    path: &Path,
373    sha: &str,
374    read: &dyn Fn(&str) -> Option<String>,
375) -> Result<Option<VersionCommit>> {
376    let repo = discover(root).context("reading a tagged commit needs a git repository")?;
377    let commit = repo
378        .head_commit()
379        .context("reading a tagged commit needs HEAD")?;
380    tagged_commit_from_commit(&repo, commit, "HEAD", root, path, sha, read)
381}
382
383/// Like [`tagged_commit`], starting from commit `start` instead of HEAD.
384///
385/// # Errors
386///
387/// Returns an error when `root` is not a git repository, when `start` does not
388/// resolve to a commit, or when the ancestry walk fails.
389pub fn tagged_commit_from(
390    root: &Path,
391    start: &str,
392    path: &Path,
393    sha: &str,
394    read: &dyn Fn(&str) -> Option<String>,
395) -> Result<Option<VersionCommit>> {
396    let repo = discover(root).context("reading a tagged commit needs a git repository")?;
397    let id =
398        gix::ObjectId::from_hex(start.as_bytes()).with_context(|| format!("commit {start}"))?;
399    let commit = repo
400        .find_commit(id)
401        .with_context(|| format!("commit {start} is not in the repository"))?;
402    tagged_commit_from_commit(&repo, commit, start, root, path, sha, read)
403}
404
405fn tagged_commit_from_commit<'a>(
406    repo: &'a gix::Repository,
407    mut commit: gix::Commit<'a>,
408    start_label: &str,
409    root: &Path,
410    path: &Path,
411    sha: &str,
412    read: &dyn Fn(&str) -> Option<String>,
413) -> Result<Option<VersionCommit>> {
414    let rel = git_path(root, path, repo.workdir())
415        .with_context(|| format!("{} is not in the repository", path.display()))?;
416    let version_at =
417        |commit: &gix::Commit<'_>| -> Result<PackageFile> { package_file_at(commit, &rel, read) };
418    let wanted = match version_at(&commit)? {
419        PackageFile::Present(Some(version)) => version,
420        PackageFile::Missing | PackageFile::Present(None) => {
421            bail!("{start_label} has no version in {}", rel.display())
422        }
423    };
424    let boundary: Vec<gix::ObjectId> = repo
425        .shallow_commits()?
426        .map_or_default(|commits| commits.iter().copied().collect());
427    let mut line = Vec::new();
428    loop {
429        if commit.id().to_string().eq_ignore_ascii_case(sha) {
430            return Ok(version_at(&commit)?
431                .is_release_of(&wanted)
432                .then(|| VersionCommit {
433                    sha: commit.id().to_string(),
434                    depth: line.len(),
435                }));
436        }
437        if boundary.contains(&commit.id().detach()) {
438            return Err(lookup::unavailable(anyhow!(
439                "cannot find tagged commit {sha}: the clone is shallow; fetch the full history{}",
440                shallow_hint()
441            )));
442        }
443        line.push(commit.id().detach());
444        let Some(parent) = commit.parent_ids().next() else {
445            break;
446        };
447        commit = repo.find_commit(parent.detach())?;
448    }
449    merged_release(repo, &line, sha, &wanted, &version_at)
450}
451
452/// `sha` as a release that HEAD has only through a merge: a commit off the
453/// first-parent `line` (HEAD first) that carries `wanted`. Its depth is the
454/// index of the oldest commit on `line` that contains it.
455///
456/// Every commit on `line` newer than the merge that brought `sha` in contains
457/// it too. The search tests HEAD, then indices 1, 2, 4, 8, … until one does
458/// not contain `sha` or `line` ends. It then bisects that last interval, so
459/// finding a merge `d` commits below HEAD takes O(log d) merge-base walks.
460///
461/// `None` when `sha` names no commit, carries another version, or HEAD does
462/// not contain it. A commit with no file at the package's path carries no
463/// version and counts as `wanted`.
464fn merged_release(
465    repo: &gix::Repository,
466    line: &[gix::ObjectId],
467    sha: &str,
468    wanted: &str,
469    version_at: &dyn Fn(&gix::Commit<'_>) -> Result<PackageFile>,
470) -> Result<Option<VersionCommit>> {
471    let Ok(tagged) = gix::ObjectId::from_hex(sha.as_bytes()) else {
472        return Ok(None);
473    };
474    let Ok(commit) = repo.find_commit(tagged) else {
475        return Ok(None);
476    };
477    if !version_at(&commit)?.is_release_of(wanted) {
478        return Ok(None);
479    }
480    let contains = |at: gix::ObjectId| -> Result<bool> {
481        let base = repo.merge_base(at, tagged).with_context(|| {
482            format!("cannot tell whether HEAD contains tagged commit {sha}; fetch the full history")
483        })?;
484        Ok(base.is_some_and(|base| base == tagged))
485    };
486    let Some(&head) = line.first() else {
487        return Ok(None);
488    };
489    if !contains(head)? {
490        return Ok(None);
491    }
492    let mut inside = 0;
493    let mut outside = line.len();
494    let mut probe = 1;
495    while probe < line.len() {
496        if !contains(line[probe])? {
497            outside = probe;
498            break;
499        }
500        inside = probe;
501        probe *= 2;
502    }
503    while outside - inside > 1 {
504        let mid = inside + (outside - inside) / 2;
505        if contains(line[mid])? {
506            inside = mid;
507        } else {
508            outside = mid;
509        }
510    }
511    Ok(Some(VersionCommit {
512        sha: tagged.to_string(),
513        depth: inside,
514    }))
515}
516
517fn has_path(commit: &gix::Commit<'_>, rel: &Path) -> Result<bool> {
518    Ok(commit.tree()?.lookup_entry_by_path(rel)?.is_some())
519}
520
521fn named(commit: &gix::Commit<'_>) -> Result<AddedBy> {
522    Ok(AddedBy {
523        sha: commit.id().to_string(),
524        subject: commit.message()?.summary().to_str_lossy().into_owned(),
525    })
526}
527
528/// The pull request a squash-merge subject names: a trailing `(#N)`.
529#[must_use]
530pub fn pull_request_number(subject: &str) -> Option<u64> {
531    let (_, digits) = subject.trim_end().strip_suffix(')')?.rsplit_once("(#")?;
532    if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
533        return None;
534    }
535    digits.parse().ok()
536}