verctl-git 0.9.6

Git repository access and history queries for verctl
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, anyhow, bail};
use gix::bstr::ByteSlice;
use gix::objs::tree::EntryKind;
use semver::Version;
use verctl_core::lookup;

use crate::discover;
use crate::merge_base::{blob_at, git_path};
use crate::remote::shallow_hint;

/// The commit that added a file, as the changelog names it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddedBy {
    /// Full hex SHA of the commit.
    pub sha: String,
    /// First line of the commit message.
    pub subject: String,
}

/// The commit that added `path`. It is the newest commit on HEAD's
/// first-parent history whose tree has the file and whose first parent's tree
/// does not.
///
/// A squash merge is that commit, and its subject carries the pull request
/// number.
///
/// When that commit is a merge and another parent already has the file, the
/// file arrived with the merged branch. The walk then continues down that
/// parent's first-parent history. A fragment merged from `next` links the pull
/// request that added it there, instead of the merge.
///
/// A merge titled with its pull request, `Title (#N)`, may have branch commits
/// that name none. That merge is then the commit named instead. A repository
/// that merges with merge commits thus keeps its pull request links. The
/// deepest such merge on the way down wins.
///
/// The result is `None` in these cases:
///
/// - There is no repository, or HEAD does not track the file. A fixture outside
///   git, or a fragment not committed yet, has no commit to name.
/// - A shallow clone ends before the adding commit. A commit listed in
///   `.git/shallow` is the boundary and counts as parentless, and naming it
///   would link the wrong commit.
/// - A parent exists but cannot be loaded. It is treated like the shallow
///   boundary.
///
/// # Errors
///
/// Returns an error when the shallow boundary cannot be read, or when a tree
/// or commit message on the walk cannot be read.
pub fn added_by(root: &Path, path: &Path) -> Result<Option<AddedBy>> {
    let Ok(repo) = discover(root) else {
        return Ok(None);
    };
    let Ok(head) = repo.head_commit() else {
        return Ok(None);
    };
    added_from(&repo, root, path, head)
}

/// [`added_by`] from `start` instead of HEAD.
///
/// A fragment a candidate's Version PR deleted is gone from HEAD, so its
/// origin is found from a commit that still contains it: the first parent of
/// the commit that deleted it.
///
/// # Errors
///
/// Returns an error when `start` names no commit in the repository, and under
/// the conditions of [`added_by`].
pub fn added_by_from(root: &Path, path: &Path, start: &str) -> Result<Option<AddedBy>> {
    let Ok(repo) = discover(root) else {
        return Ok(None);
    };
    let id =
        gix::ObjectId::from_hex(start.as_bytes()).with_context(|| format!("commit {start}"))?;
    let commit = repo
        .find_commit(id)
        .with_context(|| format!("commit {start} is not in the repository"))?;
    added_from(&repo, root, path, commit)
}

fn added_from(
    repo: &gix::Repository,
    root: &Path,
    path: &Path,
    head: gix::Commit<'_>,
) -> Result<Option<AddedBy>> {
    let Some(rel) = git_path(root, path, repo.workdir()) else {
        return Ok(None);
    };
    if !has_path(&head, &rel)? {
        return Ok(None);
    }
    let boundary: Vec<gix::ObjectId> = repo
        .shallow_commits()?
        .map_or_default(|commits| commits.iter().copied().collect());
    let mut commit = head;
    let mut named_merge = None;
    loop {
        let parents: Vec<gix::ObjectId> = if boundary.contains(&commit.id().detach()) {
            Vec::new()
        } else {
            commit.parent_ids().map(gix::Id::detach).collect()
        };
        if parents.is_empty() && !boundary.is_empty() {
            return Ok(None);
        }
        let mut holder = None;
        for (index, id) in parents.into_iter().enumerate() {
            let Ok(parent) = repo.find_commit(id) else {
                return Ok(None);
            };
            if has_path(&parent, &rel)? {
                holder = Some((index, parent));
                break;
            }
        }
        let added = named(&commit)?;
        let Some((index, parent)) = holder else {
            return Ok(Some(match named_merge {
                Some(merge) if pull_request_number(&added.subject).is_none() => merge,
                Some(_) | None => added,
            }));
        };
        if index > 0 && pull_request_number(&added.subject).is_some() {
            named_merge = Some(added);
        }
        commit = parent;
    }
}

/// A file a commit deleted, as its first parent had it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Deleted {
    /// The file: `dir` as the caller gave it, joined with the file name.
    pub path: PathBuf,
    /// Its text in the first parent.
    pub text: String,
    /// Full hex SHA of the first parent: the newest commit that contains the
    /// file.
    pub parent: String,
}

/// The files under `dir` that each candidate's Version PR deleted since the
/// version in `manifest` was last stable, newest first.
///
/// The walk follows HEAD's first parents. A commit whose first parent contains
/// another version in `manifest` set a version. The first such commit that set
/// a version with no prerelease ends the walk, and its own deletions are left
/// out: they belong to that stable release. Every other commit that set a
/// version is a candidate's Version PR, and each file under `dir` its first
/// parent contains and it does not is listed. The merge queue lands a Version
/// PR as a merge commit, so the fragments it consumed show in that diff. A
/// commit that set no version deleted no fragment a release consumed, so its
/// deletions are skipped. With no stable version on the history, the walk
/// reads to the root commit.
///
/// `read` returns `None` when a revision of the file contains no version, which
/// counts as a different version.
///
/// # Errors
///
/// Returns an error when `root` is in no repository, when `manifest` or `dir`
/// is outside it, or when a commit or tree cannot be read. It returns a
/// [`lookup::Unavailable`] error naming the commit when the walk reaches a
/// shallow clone's boundary first, because a stable section built without
/// the rest would leave changes out.
pub fn candidate_deletions(
    root: &Path,
    manifest: &Path,
    read: &dyn Fn(&str) -> Option<String>,
    dir: &Path,
) -> Result<Vec<Deleted>> {
    let repo = discover(root).context("reading earlier candidates needs a git repository")?;
    let workdir = repo.workdir().map(Path::to_path_buf);
    let manifest_rel = git_path(root, manifest, workdir.as_deref())
        .with_context(|| format!("{} is not in the repository", manifest.display()))?;
    let dir_rel = git_path(root, dir, workdir.as_deref())
        .with_context(|| format!("{} is not in the repository", dir.display()))?;
    let version_at = |commit: &gix::Commit<'_>| -> Result<Option<String>> {
        Ok(blob_at(&commit.tree()?, &manifest_rel).and_then(|raw| read(&raw)))
    };
    let boundary: Vec<gix::ObjectId> = repo
        .shallow_commits()?
        .map_or_default(|commits| commits.iter().copied().collect());
    let mut commit = repo
        .head_commit()
        .context("reading earlier candidates needs HEAD")?;
    let mut deleted = Vec::new();
    loop {
        let version = version_at(&commit)?;
        if boundary.contains(&commit.id().detach()) {
            return Err(lookup::unavailable(anyhow!(
                "cannot read the candidates before commit {}: the clone is shallow; fetch the full history{}",
                commit.id(),
                shallow_hint()
            )));
        }
        let Some(parent) = commit.parent_ids().next() else {
            break;
        };
        let parent = repo.find_commit(parent.detach())?;
        if version_at(&parent)? != version {
            if version.as_deref().is_some_and(stable) {
                break;
            }
            let files = files_under(&parent, &dir_rel)?;
            let kept = files_under(&commit, &dir_rel)?;
            for (name, text) in files {
                if !kept.contains_key(&name) {
                    deleted.push(Deleted {
                        path: dir.join(&name),
                        text,
                        parent: parent.id().to_string(),
                    });
                }
            }
        }
        commit = parent;
    }
    Ok(deleted)
}

/// Whether `version` is semver with no prerelease.
fn stable(version: &str) -> bool {
    Version::parse(version).is_ok_and(|version| version.pre.is_empty())
}

/// Each file directly under `dir` in `commit`, by its file name, with its
/// text. `dir` is the directory's path in the repository.
fn files_under(commit: &gix::Commit<'_>, dir: &Path) -> Result<BTreeMap<PathBuf, String>> {
    let tree = commit.tree()?;
    let Some(entry) = tree.lookup_entry_by_path(dir)? else {
        return Ok(BTreeMap::new());
    };
    let Ok(subtree) = entry.object()?.try_into_tree() else {
        return Ok(BTreeMap::new());
    };
    let mut files = BTreeMap::new();
    for entry in subtree.iter() {
        let entry = entry?;
        if !entry.mode().is_blob() {
            continue;
        }
        let blob = entry.object()?.try_into_blob()?;
        files.insert(
            PathBuf::from(entry.filename().to_str_lossy().as_ref()),
            String::from_utf8_lossy(&blob.data).into_owned(),
        );
    }
    Ok(files)
}

/// A commit that carries a package's release, and how far it sits below HEAD.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct VersionCommit {
    /// Full hex SHA of the commit.
    pub sha: String,
    /// First-parent steps from HEAD: 0 is HEAD itself.
    pub depth: usize,
}

impl VersionCommit {
    /// Build a version commit at `sha` and `depth` first-parent steps below
    /// HEAD.
    #[must_use]
    pub const fn new(sha: String, depth: usize) -> Self {
        Self { sha, depth }
    }
}

/// What a commit contains at a package's path.
#[derive(Debug)]
enum PackageFile {
    /// The commit contains no file at the path.
    Missing,
    /// The commit contains a file there, and `read` finds this version in it,
    /// or none.
    Present(Option<String>),
}

/// What `commit` contains at `rel`. Only a path with no tree entry is
/// [`PackageFile::Missing`]. A directory, submodule or symlink there contains
/// no version, and a lookup or read failure is an error, so neither passes
/// as a commit made before the file existed.
fn package_file_at(
    commit: &gix::Commit<'_>,
    rel: &Path,
    read: &dyn Fn(&str) -> Option<String>,
) -> Result<PackageFile> {
    let tree = commit.tree()?;
    let Some(entry) = tree
        .lookup_entry_by_path(rel)
        .with_context(|| format!("reading {} at commit {}", rel.display(), commit.id()))?
    else {
        return Ok(PackageFile::Missing);
    };
    match entry.mode().kind() {
        EntryKind::Blob | EntryKind::BlobExecutable => {
            let blob = entry
                .object()
                .with_context(|| format!("reading {} at commit {}", rel.display(), commit.id()))?
                .detach();
            Ok(PackageFile::Present(read(&String::from_utf8_lossy(
                &blob.data,
            ))))
        }
        EntryKind::Tree | EntryKind::Link | EntryKind::Commit => Ok(PackageFile::Present(None)),
    }
}

impl PackageFile {
    /// Whether a release tag on a commit containing this names `wanted`. A
    /// commit made before the file existed does, because the tag's name renders
    /// the version. A file that contains another version, or none, does not.
    fn is_release_of(&self, wanted: &str) -> bool {
        match self {
            Self::Missing => true,
            Self::Present(version) => version.as_deref() == Some(wanted),
        }
    }
}

/// `sha` as the release commit of the version `read` finds in `path` at HEAD,
/// when HEAD contains `sha` and `sha` carries that version.
///
/// A release tag can name a commit other than HEAD and still be that
/// version's release. Four cases qualify:
///
/// - A publish rerun after later commits tagged a newer HEAD at the same
///   version.
/// - A version set again after a revert, which keeps the tag from its first
///   release.
/// - A tagged commit that left the first-parent history while HEAD keeps it. A
///   forkctl append publish rewrites a branch and merges it back with its old
///   tip as the second parent. Only that parent then contains the tagged
///   commit. The new first-parent commit at the same version may change other
///   files.
/// - A tag on a commit made before the package's file existed, such as one
///   before the version moved to a `VERSION` file. The tag's name renders the
///   version, so that commit is the release.
///
/// In every case the registry already has the version, so the tag's commit is
/// the release. Only the version is compared, never the tree, and a commit
/// with no file at `path` has no version to compare.
///
/// On the first-parent history the depth is the tagged commit's own. Off it,
/// the depth is that of the oldest first-parent commit that contains the
/// tagged commit, the merge that brought it in. `None` means the tag is on a
/// commit with another version, or on a commit HEAD does not contain.
///
/// # Errors
///
/// Returns an error when:
///
/// - `root` is in no repository;
/// - `path` is outside it;
/// - HEAD has no version in `path`;
/// - a commit or tree cannot be read.
///
/// It also returns a [`lookup::Unavailable`] error when the walk reaches a
/// shallow clone's boundary before finding `sha`. It returns an error too when
/// no merge-base can be computed between a first-parent commit and `sha`.
pub fn tagged_commit(
    root: &Path,
    path: &Path,
    sha: &str,
    read: &dyn Fn(&str) -> Option<String>,
) -> Result<Option<VersionCommit>> {
    let repo = discover(root).context("reading a tagged commit needs a git repository")?;
    let commit = repo
        .head_commit()
        .context("reading a tagged commit needs HEAD")?;
    tagged_commit_from_commit(&repo, commit, "HEAD", root, path, sha, read)
}

/// Like [`tagged_commit`], starting from commit `start` instead of HEAD.
///
/// # Errors
///
/// Returns an error when `root` is not a git repository, when `start` does not
/// resolve to a commit, or when the ancestry walk fails.
pub fn tagged_commit_from(
    root: &Path,
    start: &str,
    path: &Path,
    sha: &str,
    read: &dyn Fn(&str) -> Option<String>,
) -> Result<Option<VersionCommit>> {
    let repo = discover(root).context("reading a tagged commit needs a git repository")?;
    let id =
        gix::ObjectId::from_hex(start.as_bytes()).with_context(|| format!("commit {start}"))?;
    let commit = repo
        .find_commit(id)
        .with_context(|| format!("commit {start} is not in the repository"))?;
    tagged_commit_from_commit(&repo, commit, start, root, path, sha, read)
}

fn tagged_commit_from_commit<'a>(
    repo: &'a gix::Repository,
    mut commit: gix::Commit<'a>,
    start_label: &str,
    root: &Path,
    path: &Path,
    sha: &str,
    read: &dyn Fn(&str) -> Option<String>,
) -> Result<Option<VersionCommit>> {
    let rel = git_path(root, path, repo.workdir())
        .with_context(|| format!("{} is not in the repository", path.display()))?;
    let version_at =
        |commit: &gix::Commit<'_>| -> Result<PackageFile> { package_file_at(commit, &rel, read) };
    let wanted = match version_at(&commit)? {
        PackageFile::Present(Some(version)) => version,
        PackageFile::Missing | PackageFile::Present(None) => {
            bail!("{start_label} has no version in {}", rel.display())
        }
    };
    let boundary: Vec<gix::ObjectId> = repo
        .shallow_commits()?
        .map_or_default(|commits| commits.iter().copied().collect());
    let mut line = Vec::new();
    loop {
        if commit.id().to_string().eq_ignore_ascii_case(sha) {
            return Ok(version_at(&commit)?
                .is_release_of(&wanted)
                .then(|| VersionCommit {
                    sha: commit.id().to_string(),
                    depth: line.len(),
                }));
        }
        if boundary.contains(&commit.id().detach()) {
            return Err(lookup::unavailable(anyhow!(
                "cannot find tagged commit {sha}: the clone is shallow; fetch the full history{}",
                shallow_hint()
            )));
        }
        line.push(commit.id().detach());
        let Some(parent) = commit.parent_ids().next() else {
            break;
        };
        commit = repo.find_commit(parent.detach())?;
    }
    merged_release(repo, &line, sha, &wanted, &version_at)
}

/// `sha` as a release that HEAD has only through a merge: a commit off the
/// first-parent `line` (HEAD first) that carries `wanted`. Its depth is the
/// index of the oldest commit on `line` that contains it.
///
/// Every commit on `line` newer than the merge that brought `sha` in contains
/// it too. The search tests HEAD, then indices 1, 2, 4, 8, … until one does
/// not contain `sha` or `line` ends. It then bisects that last interval, so
/// finding a merge `d` commits below HEAD takes O(log d) merge-base walks.
///
/// `None` when `sha` names no commit, carries another version, or HEAD does
/// not contain it. A commit with no file at the package's path carries no
/// version and counts as `wanted`.
fn merged_release(
    repo: &gix::Repository,
    line: &[gix::ObjectId],
    sha: &str,
    wanted: &str,
    version_at: &dyn Fn(&gix::Commit<'_>) -> Result<PackageFile>,
) -> Result<Option<VersionCommit>> {
    let Ok(tagged) = gix::ObjectId::from_hex(sha.as_bytes()) else {
        return Ok(None);
    };
    let Ok(commit) = repo.find_commit(tagged) else {
        return Ok(None);
    };
    if !version_at(&commit)?.is_release_of(wanted) {
        return Ok(None);
    }
    let contains = |at: gix::ObjectId| -> Result<bool> {
        let base = repo.merge_base(at, tagged).with_context(|| {
            format!("cannot tell whether HEAD contains tagged commit {sha}; fetch the full history")
        })?;
        Ok(base.is_some_and(|base| base == tagged))
    };
    let Some(&head) = line.first() else {
        return Ok(None);
    };
    if !contains(head)? {
        return Ok(None);
    }
    let mut inside = 0;
    let mut outside = line.len();
    let mut probe = 1;
    while probe < line.len() {
        if !contains(line[probe])? {
            outside = probe;
            break;
        }
        inside = probe;
        probe *= 2;
    }
    while outside - inside > 1 {
        let mid = inside + (outside - inside) / 2;
        if contains(line[mid])? {
            inside = mid;
        } else {
            outside = mid;
        }
    }
    Ok(Some(VersionCommit {
        sha: tagged.to_string(),
        depth: inside,
    }))
}

fn has_path(commit: &gix::Commit<'_>, rel: &Path) -> Result<bool> {
    Ok(commit.tree()?.lookup_entry_by_path(rel)?.is_some())
}

fn named(commit: &gix::Commit<'_>) -> Result<AddedBy> {
    Ok(AddedBy {
        sha: commit.id().to_string(),
        subject: commit.message()?.summary().to_str_lossy().into_owned(),
    })
}

/// The pull request a squash-merge subject names: a trailing `(#N)`.
#[must_use]
pub fn pull_request_number(subject: &str) -> Option<u64> {
    let (_, digits) = subject.trim_end().strip_suffix(')')?.rsplit_once("(#")?;
    if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
        return None;
    }
    digits.parse().ok()
}