Skip to main content

verctl_git/
lib.rs

1//! Git repository access, commit history, tree reads, fetch, and push for
2//! `verctl`.
3
4#[cfg(test)]
5pub(crate) mod test_git;
6
7use std::collections::{BTreeMap, BTreeSet};
8use std::fs::{File, Metadata, Permissions};
9use std::io::{ErrorKind, Read};
10use std::num::NonZeroU32;
11use std::path::{Component, Path, PathBuf};
12use std::sync::atomic::AtomicBool;
13use std::time::Duration;
14use std::{env, fmt, fs, path};
15
16use anyhow::{Context, Result, anyhow, bail, ensure};
17use gix::actor::Signature;
18use gix::bstr::{BString, ByteSlice};
19use gix::credentials::helper::Action;
20use gix::credentials::protocol::Outcome;
21use gix::date::Time;
22use gix::dir::entry::Status;
23use gix::dir::walk::EmissionMode;
24use gix::filter::Pipeline;
25use gix::index::State;
26use gix::index::entry::Mode;
27use gix::objs::Commit;
28use gix::objs::tree::EntryKind;
29use gix::progress::Discard;
30use gix::refs::transaction::{PreviousValue, RefEdit};
31use gix::refs::{FullName, Target};
32use gix::remote::fetch::{Shallow, Tags};
33use gix::remote::{Direction, ref_map};
34use gix::sec::identity::Account;
35use gix::sec::trust::{DefaultForLevel, Mapping};
36use gix::sec::{Permission, Trust};
37use gix::status::tree_index::TrackRenames;
38use gix::status::{UntrackedFiles, index_worktree};
39use gix::worktree::stack::state::ignore::Source;
40use gix::{open, status};
41use semver::Version;
42use verctl_core::repo::Repo;
43use verctl_core::{env as github_env, lookup, process};
44
45/// The checked-out branch, or `None` for a detached HEAD or no repository.
46#[must_use]
47pub fn current_branch(root: &Path) -> Option<String> {
48    let repo = repo_covering(root)?;
49    repo.head_id().ok()?;
50    let name = repo.head_name().ok()??;
51    Some(name.shorten().to_string())
52}
53
54/// The commit HEAD names, as a full hex SHA.
55///
56/// # Errors
57///
58/// Returns an error when `root` is not inside a git repository, or when HEAD
59/// names no commit, as in a repository with no commits.
60pub fn head_sha(root: &Path) -> Result<String> {
61    let repo = discover(root).context("release needs a git repository to name the tag")?;
62    let commit = repo
63        .head_commit()
64        .context("release needs HEAD to name the tag")?;
65    Ok(commit.id().to_string())
66}
67
68/// Whether `HEAD` contains commit `sha` (either equal to `HEAD` or an ancestor
69/// of `HEAD`).
70///
71/// Returns `Ok(false)` when `sha` is absent from the local object store or is
72/// not an ancestor of `HEAD`.
73///
74/// # Errors
75///
76/// Returns an error when `root` is not inside a git repository, `HEAD` cannot
77/// be read, `sha` is not a valid commit hex id, or the ancestry walk fails.
78pub fn head_contains_commit(root: &Path, sha: &str) -> Result<bool> {
79    let repo = discover(root).context("checking commit ancestry needs a git repository")?;
80    let head = repo
81        .head_commit()
82        .context("checking commit ancestry needs HEAD")?
83        .id();
84    let target =
85        gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
86    if head == target {
87        return Ok(true);
88    }
89    if repo.find_commit(target).is_err() {
90        return Ok(false);
91    }
92    let base = repo.merge_base(head, target).with_context(|| {
93        format!("cannot tell whether HEAD contains commit {sha}; fetch the full history")
94    })?;
95    Ok(base.is_some_and(|base| base == target))
96}
97
98/// What a missing or unreachable merge-base means for a version comparison.
99const NEED_FULL_FETCH: &str =
100    "cannot compare versions against the default branch (need a full fetch, not a shallow clone)";
101
102/// File contents at the merge-base of HEAD and the default branch.
103///
104/// Paths are relative to `root` (the directory containing `.ctl/`) and are
105/// mapped onto the git workdir so `-c crates/foo/.ctl/ver.yaml` still hits the
106/// right blob. One repository open for the whole list.
107///
108/// Every entry is `None` when there is no repository, or when the repository
109/// has no `origin` remote and none of the candidate refs exists. A path
110/// missing from the merge-base tree is `None` for that entry only.
111///
112/// # Errors
113///
114/// Returns an error when:
115///
116/// - `origin` exists but resolving its default branch ref fails;
117/// - HEAD names no commit;
118/// - there is no merge-base (a shallow clone, for one);
119/// - the merge-base commit or its tree cannot be read.
120pub fn files_on_merge_base(
121    root: &Path,
122    rels: &[&Path],
123    candidates: &[String],
124) -> Result<Vec<Option<String>>> {
125    let Some(repo) = repo_covering(root) else {
126        return Ok(vec![None; rels.len()]);
127    };
128    let Some(upstream) = default_upstream_commit(&repo, candidates)? else {
129        return Ok(vec![None; rels.len()]);
130    };
131    let head = repo
132        .head_commit()
133        .context("cannot compare versions (need HEAD)")?;
134    let base = repo
135        .merge_base(head.id(), upstream)
136        .context(NEED_FULL_FETCH)?
137        .context(NEED_FULL_FETCH)?;
138    let tree = repo.find_commit(base)?.tree()?;
139    let workdir = repo.workdir().map(Path::to_path_buf);
140    Ok(rels
141        .iter()
142        .map(|rel| git_path(root, rel, workdir.as_deref()).and_then(|path| blob_at(&tree, &path)))
143        .collect())
144}
145
146/// `rel` as a path inside the repository. A relative path joins the
147/// canonical root without being canonicalized itself. A file deleted from the
148/// working tree still resolves to its committed copy this way. The version
149/// guard has to see a manifest that a pull request removed. An absolute path
150/// to a file that is gone resolves through its canonical directory, so a
151/// fragment a commit deleted still names its committed copy.
152fn git_path(root: &Path, rel: &Path, workdir: Option<&Path>) -> Option<PathBuf> {
153    let abs = if rel.is_absolute() {
154        rel.canonicalize().ok().or_else(|| {
155            rel.parent()?
156                .canonicalize()
157                .ok()
158                .map(|dir| dir.join(rel.file_name().unwrap_or_default()))
159        })?
160    } else {
161        let inside: PathBuf = rel
162            .components()
163            .filter(|part| !matches!(part, Component::CurDir))
164            .collect();
165        root.canonicalize().ok()?.join(inside)
166    };
167    let workdir = workdir?.canonicalize().ok()?;
168    abs.strip_prefix(workdir).ok().map(Path::to_path_buf)
169}
170
171/// The tree at the merge-base of HEAD and the pull request's base, and the
172/// paths the working tree changes against it. The content check for a Version
173/// PR replays the version step on this tree.
174#[derive(Debug)]
175pub struct MergeBase {
176    repo: gix::Repository,
177    workdir: PathBuf,
178    files: BTreeMap<String, (gix::ObjectId, EntryKind)>,
179    changed: BTreeSet<String>,
180}
181
182impl MergeBase {
183    /// Read the merge-base tree and list each tracked path that differs from
184    /// it: committed on the branch, modified, or deleted. A symlink or a
185    /// submodule differs when its entry on HEAD does. Untracked files are left
186    /// out.
187    ///
188    /// `None` when there is no repository, or no `origin` and none of the
189    /// candidate refs, as for [`files_on_merge_base`].
190    ///
191    /// # Errors
192    ///
193    /// Returns an error under the conditions of [`files_on_merge_base`], or
194    /// when a tree, a blob, a working tree file, or `git status` cannot be
195    /// read.
196    pub fn read(root: &Path, candidates: &[String]) -> Result<Option<Self>> {
197        let Some(repo) = repo_covering(root) else {
198            return Ok(None);
199        };
200        let Some(upstream) = default_upstream_commit(&repo, candidates)? else {
201            return Ok(None);
202        };
203        let (files, head_files) = {
204            let head = repo
205                .head_commit()
206                .context("cannot compare the Version PR (need HEAD)")?;
207            let base = repo
208                .merge_base(head.id(), upstream)
209                .context(NEED_FULL_FETCH)?
210                .context(NEED_FULL_FETCH)?;
211            (
212                files_of(&repo.find_commit(base)?.tree()?)?,
213                files_of(&head.tree()?)?,
214            )
215        };
216        let workdir = repo
217            .workdir()
218            .context("the Version PR check needs a working tree")?
219            .canonicalize()
220            .context("the working tree")?;
221        let mut candidates: BTreeSet<String> = files
222            .keys()
223            .chain(head_files.keys())
224            .filter(|path| files.get(*path) != head_files.get(*path))
225            .cloned()
226            .collect();
227        candidates.extend(
228            status_paths(&repo, Vec::new(), IgnoredFiles::Skip)
229                .context("git status")?
230                .into_iter()
231                .filter(|path| files.contains_key(path) || head_files.contains_key(path)),
232        );
233        let mut merge_base = Self {
234            repo,
235            workdir,
236            files,
237            changed: BTreeSet::new(),
238        };
239        for path in candidates {
240            if merge_base.differs(&path, head_files.get(&path))? {
241                merge_base.changed.insert(path);
242            }
243        }
244        Ok(Some(merge_base))
245    }
246
247    /// Whether `rel` differs from the merge-base. A regular file compares by
248    /// its bytes in the working tree, and a symlink by its target there, so an
249    /// uncommitted edit counts. A submodule compares by its commit on HEAD:
250    /// an uncommitted submodule move is out of scope, since CI checks out a
251    /// commit.
252    fn differs(&self, rel: &str, head: Option<&(gix::ObjectId, EntryKind)>) -> Result<bool> {
253        let base = self.files.get(rel);
254        let gitlink = |entry: Option<&(gix::ObjectId, EntryKind)>| {
255            entry.is_some_and(|(_, kind)| *kind == EntryKind::Commit)
256        };
257        if gitlink(base) || gitlink(head) {
258            return Ok(base != head);
259        }
260        let expected = match base {
261            None => Worktree::Missing,
262            Some((_, EntryKind::Link)) => Worktree::Link(self.base_bytes(rel)?.unwrap_or_default()),
263            Some(_) => Worktree::File(self.base_bytes(rel)?.unwrap_or_default()),
264        };
265        Ok(expected != Worktree::read(&self.workdir.join(rel))?)
266    }
267
268    /// The working tree's root, canonical.
269    #[must_use]
270    pub fn workdir(&self) -> &Path {
271        &self.workdir
272    }
273
274    /// Each path, relative to the working tree's root, that differs from the
275    /// merge-base. A file differs by its bytes, a symlink by its target, and a
276    /// submodule by its commit.
277    #[must_use]
278    pub fn changed(&self) -> &BTreeSet<String> {
279        &self.changed
280    }
281
282    /// A file's bytes at the merge-base, or `None` when it has no file there.
283    ///
284    /// # Errors
285    ///
286    /// Returns an error when the blob cannot be read.
287    pub fn base_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
288        let Some((oid, _)) = self.files.get(rel) else {
289            return Ok(None);
290        };
291        let blob = self
292            .repo
293            .find_blob(*oid)
294            .with_context(|| format!("{rel} at the merge-base"))?;
295        Ok(Some(blob.data.clone()))
296    }
297
298    /// A file's bytes in the working tree, or `None` when it is missing.
299    ///
300    /// # Errors
301    ///
302    /// Returns an error when the file exists but cannot be read.
303    pub fn worktree_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
304        read_optional(&self.workdir.join(rel))
305    }
306
307    /// Write every regular file of the merge-base tree under `dir`. Each file
308    /// keeps its executable bit.
309    ///
310    /// The whole tree is written because the replay's readers are not a fixed
311    /// list. `cargo metadata` expands member globs and needs each member's
312    /// target files. A pin or a served file can name any path. Symlinks
313    /// are not recreated, so no write through one leaves `dir`.
314    ///
315    /// # Errors
316    ///
317    /// Returns an error when a blob cannot be read or a file cannot be
318    /// written.
319    pub fn write_to(&self, dir: &Path) -> Result<()> {
320        use std::os::unix::fs::PermissionsExt as _;
321        for (rel, (_, kind)) in &self.files {
322            let mode = match kind {
323                EntryKind::Blob => 0o644,
324                EntryKind::BlobExecutable => 0o755,
325                EntryKind::Link | EntryKind::Tree | EntryKind::Commit => continue,
326            };
327            let path = dir.join(rel);
328            if let Some(parent) = path.parent() {
329                fs::create_dir_all(parent)
330                    .with_context(|| format!("create {}", parent.display()))?;
331            }
332            let bytes = self.base_bytes(rel)?.unwrap_or_default();
333            fs::write(&path, bytes).with_context(|| format!("write {}", path.display()))?;
334            fs::set_permissions(&path, Permissions::from_mode(mode))
335                .with_context(|| format!("chmod {}", path.display()))?;
336        }
337        Ok(())
338    }
339}
340
341/// What the working tree contains at a path, as the merge-base tree records it:
342/// a symlink's target, or a file's bytes.
343#[derive(Debug, PartialEq, Eq)]
344enum Worktree {
345    Missing,
346    Link(Vec<u8>),
347    File(Vec<u8>),
348}
349
350impl Worktree {
351    fn read(path: &Path) -> Result<Self> {
352        use std::os::unix::ffi::OsStrExt as _;
353        let metadata = match fs::symlink_metadata(path) {
354            Ok(metadata) => metadata,
355            Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Self::Missing),
356            Err(error) => return Err(error).with_context(|| path.display().to_string()),
357        };
358        if metadata.file_type().is_symlink() {
359            let target = fs::read_link(path).with_context(|| path.display().to_string())?;
360            return Ok(Self::Link(target.as_os_str().as_bytes().to_vec()));
361        }
362        let bytes = fs::read(path).with_context(|| path.display().to_string())?;
363        Ok(Self::File(bytes))
364    }
365}
366
367/// A file's bytes, or `None` when it does not exist.
368///
369/// # Errors
370///
371/// Returns an error when the file exists but cannot be read.
372pub fn read_optional(path: &Path) -> Result<Option<Vec<u8>>> {
373    match fs::read(path) {
374        Ok(bytes) => Ok(Some(bytes)),
375        Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
376        Err(error) => Err(error).with_context(|| path.display().to_string()),
377    }
378}
379
380/// Every entry in `tree` other than a directory, by path, with its object and
381/// kind. A symlink or a submodule contains no bytes the version step writes, so
382/// the content check never replays one. It still lists one that changed.
383fn files_of(tree: &gix::Tree<'_>) -> Result<BTreeMap<String, (gix::ObjectId, EntryKind)>> {
384    Ok(tree
385        .traverse()
386        .breadthfirst
387        .files()?
388        .into_iter()
389        .filter(|entry| !entry.mode.is_tree())
390        .map(|entry| {
391            (
392                entry.filepath.to_str_lossy().into_owned(),
393                (entry.oid, entry.mode.kind()),
394            )
395        })
396        .collect())
397}
398
399/// The text of `path` at commit `sha`, or `None` when that commit contains no
400/// such file.
401///
402/// # Errors
403///
404/// Returns an error when `root` is in no repository, when `path` is outside
405/// it, or when `sha` names no commit in it.
406pub fn file_at(root: &Path, sha: &str, path: &Path) -> Result<Option<String>> {
407    let repo = discover(root).context("reading a file at a commit needs a git repository")?;
408    let rel = git_path(root, path, repo.workdir())
409        .with_context(|| format!("{} is not in the repository", path.display()))?;
410    let id = gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
411    let commit = repo
412        .find_commit(id)
413        .with_context(|| format!("commit {sha} is not in the repository"))?;
414    Ok(blob_at(&commit.tree()?, &rel))
415}
416
417fn blob_at(tree: &gix::Tree<'_>, rel: &Path) -> Option<String> {
418    let entry = tree.lookup_entry_by_path(rel).ok()??;
419    let blob = entry.object().ok()?.try_into_blob().ok()?;
420    Some(String::from_utf8_lossy(&blob.data).into_owned())
421}
422
423/// Every blob named `file_name` under `dir` at commit `sha`, as
424/// `(path relative to dir, UTF-8 text)` pairs.
425///
426/// # Errors
427///
428/// Returns an error when `root` is in no repository, when `dir` is outside it,
429/// when `sha` names no commit in it, or when reading the tree or a blob fails.
430pub fn files_named_at(
431    root: &Path,
432    sha: &str,
433    dir: &Path,
434    file_name: &str,
435) -> Result<Vec<(String, String)>> {
436    let repo = discover(root).context("reading files at a commit needs a git repository")?;
437    let dir = dir
438        .canonicalize()
439        .with_context(|| format!("resolve {}", dir.display()))?;
440    let dir_rel = git_path(root, &dir, repo.workdir())
441        .with_context(|| format!("{} is not in the repository", dir.display()))?;
442    let id = gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
443    let commit = repo
444        .find_commit(id)
445        .with_context(|| format!("commit {sha} is not in the repository"))?;
446    let mut found = Vec::new();
447    for (rel, (oid, kind)) in files_of(&commit.tree()?)? {
448        if !matches!(kind, EntryKind::Blob | EntryKind::BlobExecutable) {
449            continue;
450        }
451        let path = Path::new(&rel);
452        if path.file_name().and_then(|name| name.to_str()) != Some(file_name) {
453            continue;
454        }
455        let under_dir = if dir_rel.as_os_str().is_empty() {
456            path
457        } else if let Ok(stripped) = path.strip_prefix(&dir_rel) {
458            stripped
459        } else {
460            continue;
461        };
462        let blob = repo
463            .find_object(oid)
464            .with_context(|| format!("read {rel} at commit {sha}"))?
465            .try_into_blob()
466            .with_context(|| format!("{rel} at commit {sha} is not a blob"))?;
467        found.push((
468            under_dir.to_string_lossy().into_owned(),
469            String::from_utf8_lossy(&blob.data).into_owned(),
470        ));
471    }
472    Ok(found)
473}
474
475/// The commit at the default branch's tip, as a full hex SHA. The branch
476/// resolves as for [`files_on_merge_base`]: `origin/HEAD`, or else the first
477/// of `candidates` that `origin` has.
478///
479/// # Errors
480///
481/// Returns an error when no repository covers `root`, when there is no
482/// `origin` remote, or when `origin` has none of those refs.
483pub fn default_tip(root: &Path, candidates: &[String]) -> Result<String> {
484    let repo = repo_covering(root).with_context(|| {
485        format!(
486            "cannot resolve the default branch: no git repository covers {}",
487            root.display()
488        )
489    })?;
490    let tip = default_upstream_commit(&repo, candidates)?.context(
491        "cannot resolve the default branch: there is no `origin` remote; add it and fetch the default branch",
492    )?;
493    Ok(tip.to_string())
494}
495
496/// The URL of the `origin` remote.
497///
498/// # Errors
499///
500/// Returns an error when `root` is not inside a git repository, when there is
501/// no `origin` remote, or when `origin` has no fetch URL.
502pub fn origin_url(root: &Path) -> Result<String> {
503    let repo = discover(root).context("open git repository")?;
504    let remote = repo.find_remote("origin").context("git remote origin")?;
505    let url = remote.url(Direction::Fetch).context("origin has no URL")?;
506    Ok(url.to_bstring().to_str_lossy().into_owned())
507}
508
509/// The commit that added a file, as the changelog names it.
510#[derive(Debug, Clone, PartialEq, Eq)]
511pub struct AddedBy {
512    /// Full hex SHA of the commit.
513    pub sha: String,
514    /// First line of the commit message.
515    pub subject: String,
516}
517
518/// The commit that added `path`. It is the newest commit on HEAD's
519/// first-parent history whose tree has the file and whose first parent's tree
520/// does not.
521///
522/// A squash merge is that commit, and its subject carries the pull request
523/// number.
524///
525/// When that commit is a merge and another parent already has the file, the
526/// file arrived with the merged branch. The walk then continues down that
527/// parent's first-parent history. A fragment merged from `next` links the pull
528/// request that added it there, instead of the merge.
529///
530/// A merge titled with its pull request, `Title (#N)`, may have branch commits
531/// that name none. That merge is then the commit named instead. A repository
532/// that merges with merge commits thus keeps its pull request links. The
533/// deepest such merge on the way down wins.
534///
535/// The result is `None` in these cases:
536///
537/// - There is no repository, or HEAD does not track the file. A fixture outside
538///   git, or a fragment not committed yet, has no commit to name.
539/// - A shallow clone ends before the adding commit. A commit listed in
540///   `.git/shallow` is the boundary and counts as parentless, and naming it
541///   would link the wrong commit.
542/// - A parent exists but cannot be loaded. It is treated like the shallow
543///   boundary.
544///
545/// # Errors
546///
547/// Returns an error when the shallow boundary cannot be read, or when a tree
548/// or commit message on the walk cannot be read.
549pub fn added_by(root: &Path, path: &Path) -> Result<Option<AddedBy>> {
550    let Ok(repo) = discover(root) else {
551        return Ok(None);
552    };
553    let Ok(head) = repo.head_commit() else {
554        return Ok(None);
555    };
556    added_from(&repo, root, path, head)
557}
558
559/// [`added_by`] from `start` instead of HEAD.
560///
561/// A fragment a candidate's Version PR deleted is gone from HEAD, so its
562/// origin is found from a commit that still contains it: the first parent of
563/// the commit that deleted it.
564///
565/// # Errors
566///
567/// Returns an error when `start` names no commit in the repository, and under
568/// the conditions of [`added_by`].
569pub fn added_by_from(root: &Path, path: &Path, start: &str) -> Result<Option<AddedBy>> {
570    let Ok(repo) = discover(root) else {
571        return Ok(None);
572    };
573    let id =
574        gix::ObjectId::from_hex(start.as_bytes()).with_context(|| format!("commit {start}"))?;
575    let commit = repo
576        .find_commit(id)
577        .with_context(|| format!("commit {start} is not in the repository"))?;
578    added_from(&repo, root, path, commit)
579}
580
581fn added_from(
582    repo: &gix::Repository,
583    root: &Path,
584    path: &Path,
585    head: gix::Commit<'_>,
586) -> Result<Option<AddedBy>> {
587    let Some(rel) = git_path(root, path, repo.workdir()) else {
588        return Ok(None);
589    };
590    if !has_path(&head, &rel)? {
591        return Ok(None);
592    }
593    let boundary: Vec<gix::ObjectId> = repo
594        .shallow_commits()?
595        .map_or_default(|commits| commits.iter().copied().collect());
596    let mut commit = head;
597    let mut named_merge = None;
598    loop {
599        let parents: Vec<gix::ObjectId> = if boundary.contains(&commit.id().detach()) {
600            Vec::new()
601        } else {
602            commit.parent_ids().map(gix::Id::detach).collect()
603        };
604        if parents.is_empty() && !boundary.is_empty() {
605            return Ok(None);
606        }
607        let mut holder = None;
608        for (index, id) in parents.into_iter().enumerate() {
609            let Ok(parent) = repo.find_commit(id) else {
610                return Ok(None);
611            };
612            if has_path(&parent, &rel)? {
613                holder = Some((index, parent));
614                break;
615            }
616        }
617        let added = named(&commit)?;
618        let Some((index, parent)) = holder else {
619            return Ok(Some(match named_merge {
620                Some(merge) if pull_request_number(&added.subject).is_none() => merge,
621                Some(_) | None => added,
622            }));
623        };
624        if index > 0 && pull_request_number(&added.subject).is_some() {
625            named_merge = Some(added);
626        }
627        commit = parent;
628    }
629}
630
631/// A file a commit deleted, as its first parent had it.
632#[derive(Debug, Clone, PartialEq, Eq)]
633#[non_exhaustive]
634pub struct Deleted {
635    /// The file: `dir` as the caller gave it, joined with the file name.
636    pub path: PathBuf,
637    /// Its text in the first parent.
638    pub text: String,
639    /// Full hex SHA of the first parent: the newest commit that contains the
640    /// file.
641    pub parent: String,
642}
643
644/// The files under `dir` that each candidate's Version PR deleted since the
645/// version in `manifest` was last stable, newest first.
646///
647/// The walk follows HEAD's first parents. A commit whose first parent contains
648/// another version in `manifest` set a version. The first such commit that set
649/// a version with no prerelease ends the walk, and its own deletions are left
650/// out: they belong to that stable release. Every other commit that set a
651/// version is a candidate's Version PR, and each file under `dir` its first
652/// parent contains and it does not is listed. The merge queue lands a Version
653/// PR as a merge commit, so the fragments it consumed show in that diff. A
654/// commit that set no version deleted no fragment a release consumed, so its
655/// deletions are skipped. With no stable version on the history, the walk
656/// reads to the root commit.
657///
658/// `read` returns `None` when a revision of the file contains no version, which
659/// counts as a different version.
660///
661/// # Errors
662///
663/// Returns an error when `root` is in no repository, when `manifest` or `dir`
664/// is outside it, or when a commit or tree cannot be read. It returns a
665/// [`lookup::Unavailable`] error naming the commit when the walk reaches a
666/// shallow clone's boundary first, because a stable section built without
667/// the rest would leave changes out.
668pub fn candidate_deletions(
669    root: &Path,
670    manifest: &Path,
671    read: &dyn Fn(&str) -> Option<String>,
672    dir: &Path,
673) -> Result<Vec<Deleted>> {
674    let repo = discover(root).context("reading earlier candidates needs a git repository")?;
675    let workdir = repo.workdir().map(Path::to_path_buf);
676    let manifest_rel = git_path(root, manifest, workdir.as_deref())
677        .with_context(|| format!("{} is not in the repository", manifest.display()))?;
678    let dir_rel = git_path(root, dir, workdir.as_deref())
679        .with_context(|| format!("{} is not in the repository", dir.display()))?;
680    let version_at = |commit: &gix::Commit<'_>| -> Result<Option<String>> {
681        Ok(blob_at(&commit.tree()?, &manifest_rel).and_then(|raw| read(&raw)))
682    };
683    let boundary: Vec<gix::ObjectId> = repo
684        .shallow_commits()?
685        .map_or_default(|commits| commits.iter().copied().collect());
686    let mut commit = repo
687        .head_commit()
688        .context("reading earlier candidates needs HEAD")?;
689    let mut deleted = Vec::new();
690    loop {
691        let version = version_at(&commit)?;
692        if boundary.contains(&commit.id().detach()) {
693            return Err(lookup::unavailable(anyhow!(
694                "cannot read the candidates before commit {}: the clone is shallow; fetch the full history{}",
695                commit.id(),
696                shallow_hint()
697            )));
698        }
699        let Some(parent) = commit.parent_ids().next() else {
700            break;
701        };
702        let parent = repo.find_commit(parent.detach())?;
703        if version_at(&parent)? != version {
704            if version.as_deref().is_some_and(stable) {
705                break;
706            }
707            let files = files_under(&parent, &dir_rel)?;
708            let kept = files_under(&commit, &dir_rel)?;
709            for (name, text) in files {
710                if !kept.contains_key(&name) {
711                    deleted.push(Deleted {
712                        path: dir.join(&name),
713                        text,
714                        parent: parent.id().to_string(),
715                    });
716                }
717            }
718        }
719        commit = parent;
720    }
721    Ok(deleted)
722}
723
724/// Whether `version` is semver with no prerelease.
725fn stable(version: &str) -> bool {
726    Version::parse(version).is_ok_and(|version| version.pre.is_empty())
727}
728
729/// Each file directly under `dir` in `commit`, by its file name, with its
730/// text. `dir` is the directory's path in the repository.
731fn files_under(commit: &gix::Commit<'_>, dir: &Path) -> Result<BTreeMap<PathBuf, String>> {
732    let tree = commit.tree()?;
733    let Some(entry) = tree.lookup_entry_by_path(dir)? else {
734        return Ok(BTreeMap::new());
735    };
736    let Ok(subtree) = entry.object()?.try_into_tree() else {
737        return Ok(BTreeMap::new());
738    };
739    let mut files = BTreeMap::new();
740    for entry in subtree.iter() {
741        let entry = entry?;
742        if !entry.mode().is_blob() {
743            continue;
744        }
745        let blob = entry.object()?.try_into_blob()?;
746        files.insert(
747            PathBuf::from(entry.filename().to_str_lossy().as_ref()),
748            String::from_utf8_lossy(&blob.data).into_owned(),
749        );
750    }
751    Ok(files)
752}
753
754/// A commit that carries a package's release, and how far it sits below HEAD.
755#[derive(Debug, Clone, PartialEq, Eq)]
756#[non_exhaustive]
757pub struct VersionCommit {
758    /// Full hex SHA of the commit.
759    pub sha: String,
760    /// First-parent steps from HEAD: 0 is HEAD itself.
761    pub depth: usize,
762}
763
764impl VersionCommit {
765    /// Build a version commit at `sha` and `depth` first-parent steps below
766    /// HEAD.
767    #[must_use]
768    pub const fn new(sha: String, depth: usize) -> Self {
769        Self { sha, depth }
770    }
771}
772
773/// What a commit contains at a package's path.
774#[derive(Debug)]
775enum PackageFile {
776    /// The commit contains no file at the path.
777    Missing,
778    /// The commit contains a file there, and `read` finds this version in it,
779    /// or none.
780    Present(Option<String>),
781}
782
783/// What `commit` contains at `rel`. Only a path with no tree entry is
784/// [`PackageFile::Missing`]. A directory, submodule or symlink there contains
785/// no version, and a lookup or read failure is an error, so neither passes
786/// as a commit made before the file existed.
787fn package_file_at(
788    commit: &gix::Commit<'_>,
789    rel: &Path,
790    read: &dyn Fn(&str) -> Option<String>,
791) -> Result<PackageFile> {
792    let tree = commit.tree()?;
793    let Some(entry) = tree
794        .lookup_entry_by_path(rel)
795        .with_context(|| format!("reading {} at commit {}", rel.display(), commit.id()))?
796    else {
797        return Ok(PackageFile::Missing);
798    };
799    match entry.mode().kind() {
800        EntryKind::Blob | EntryKind::BlobExecutable => {
801            let blob = entry
802                .object()
803                .with_context(|| format!("reading {} at commit {}", rel.display(), commit.id()))?
804                .detach();
805            Ok(PackageFile::Present(read(&String::from_utf8_lossy(
806                &blob.data,
807            ))))
808        }
809        EntryKind::Tree | EntryKind::Link | EntryKind::Commit => Ok(PackageFile::Present(None)),
810    }
811}
812
813impl PackageFile {
814    /// Whether a release tag on a commit containing this names `wanted`. A
815    /// commit made before the file existed does, because the tag's name renders
816    /// the version. A file that contains another version, or none, does not.
817    fn is_release_of(&self, wanted: &str) -> bool {
818        match self {
819            Self::Missing => true,
820            Self::Present(version) => version.as_deref() == Some(wanted),
821        }
822    }
823}
824
825/// `sha` as the release commit of the version `read` finds in `path` at HEAD,
826/// when HEAD contains `sha` and `sha` carries that version.
827///
828/// A release tag can name a commit other than HEAD and still be that
829/// version's release. Four cases qualify:
830///
831/// - A publish rerun after later commits tagged a newer HEAD at the same
832///   version.
833/// - A version set again after a revert, which keeps the tag from its first
834///   release.
835/// - A tagged commit that left the first-parent history while HEAD keeps it. A
836///   forkctl append publish rewrites a branch and merges it back with its old
837///   tip as the second parent. Only that parent then contains the tagged
838///   commit. The new first-parent commit at the same version may change other
839///   files.
840/// - A tag on a commit made before the package's file existed, such as one
841///   before the version moved to a `VERSION` file. The tag's name renders the
842///   version, so that commit is the release.
843///
844/// In every case the registry already has the version, so the tag's commit is
845/// the release. Only the version is compared, never the tree, and a commit
846/// with no file at `path` has no version to compare.
847///
848/// On the first-parent history the depth is the tagged commit's own. Off it,
849/// the depth is that of the oldest first-parent commit that contains the
850/// tagged commit, the merge that brought it in. `None` means the tag is on a
851/// commit with another version, or on a commit HEAD does not contain.
852///
853/// # Errors
854///
855/// Returns an error when:
856///
857/// - `root` is in no repository;
858/// - `path` is outside it;
859/// - HEAD has no version in `path`;
860/// - a commit or tree cannot be read.
861///
862/// It also returns a [`lookup::Unavailable`] error when the walk reaches a
863/// shallow clone's boundary before finding `sha`. It returns an error too when
864/// no merge-base can be computed between a first-parent commit and `sha`.
865pub fn tagged_commit(
866    root: &Path,
867    path: &Path,
868    sha: &str,
869    read: &dyn Fn(&str) -> Option<String>,
870) -> Result<Option<VersionCommit>> {
871    let repo = discover(root).context("reading a tagged commit needs a git repository")?;
872    let commit = repo
873        .head_commit()
874        .context("reading a tagged commit needs HEAD")?;
875    tagged_commit_from_commit(&repo, commit, "HEAD", root, path, sha, read)
876}
877
878/// Like [`tagged_commit`], starting from commit `start` instead of HEAD.
879///
880/// # Errors
881///
882/// Returns an error when `root` is not a git repository, when `start` does not
883/// resolve to a commit, or when the ancestry walk fails.
884pub fn tagged_commit_from(
885    root: &Path,
886    start: &str,
887    path: &Path,
888    sha: &str,
889    read: &dyn Fn(&str) -> Option<String>,
890) -> Result<Option<VersionCommit>> {
891    let repo = discover(root).context("reading a tagged commit needs a git repository")?;
892    let id =
893        gix::ObjectId::from_hex(start.as_bytes()).with_context(|| format!("commit {start}"))?;
894    let commit = repo
895        .find_commit(id)
896        .with_context(|| format!("commit {start} is not in the repository"))?;
897    tagged_commit_from_commit(&repo, commit, start, root, path, sha, read)
898}
899
900fn tagged_commit_from_commit<'a>(
901    repo: &'a gix::Repository,
902    mut commit: gix::Commit<'a>,
903    start_label: &str,
904    root: &Path,
905    path: &Path,
906    sha: &str,
907    read: &dyn Fn(&str) -> Option<String>,
908) -> Result<Option<VersionCommit>> {
909    let rel = git_path(root, path, repo.workdir())
910        .with_context(|| format!("{} is not in the repository", path.display()))?;
911    let version_at =
912        |commit: &gix::Commit<'_>| -> Result<PackageFile> { package_file_at(commit, &rel, read) };
913    let wanted = match version_at(&commit)? {
914        PackageFile::Present(Some(version)) => version,
915        PackageFile::Missing | PackageFile::Present(None) => {
916            bail!("{start_label} has no version in {}", rel.display())
917        }
918    };
919    let boundary: Vec<gix::ObjectId> = repo
920        .shallow_commits()?
921        .map_or_default(|commits| commits.iter().copied().collect());
922    let mut line = Vec::new();
923    loop {
924        if commit.id().to_string().eq_ignore_ascii_case(sha) {
925            return Ok(version_at(&commit)?
926                .is_release_of(&wanted)
927                .then(|| VersionCommit {
928                    sha: commit.id().to_string(),
929                    depth: line.len(),
930                }));
931        }
932        if boundary.contains(&commit.id().detach()) {
933            return Err(lookup::unavailable(anyhow!(
934                "cannot find tagged commit {sha}: the clone is shallow; fetch the full history{}",
935                shallow_hint()
936            )));
937        }
938        line.push(commit.id().detach());
939        let Some(parent) = commit.parent_ids().next() else {
940            break;
941        };
942        commit = repo.find_commit(parent.detach())?;
943    }
944    merged_release(repo, &line, sha, &wanted, &version_at)
945}
946
947/// `sha` as a release that HEAD has only through a merge: a commit off the
948/// first-parent `line` (HEAD first) that carries `wanted`. Its depth is the
949/// index of the oldest commit on `line` that contains it.
950///
951/// Every commit on `line` newer than the merge that brought `sha` in contains
952/// it too. The search tests HEAD, then indices 1, 2, 4, 8, … until one does
953/// not contain `sha` or `line` ends. It then bisects that last interval, so
954/// finding a merge `d` commits below HEAD takes O(log d) merge-base walks.
955///
956/// `None` when `sha` names no commit, carries another version, or HEAD does
957/// not contain it. A commit with no file at the package's path carries no
958/// version and counts as `wanted`.
959fn merged_release(
960    repo: &gix::Repository,
961    line: &[gix::ObjectId],
962    sha: &str,
963    wanted: &str,
964    version_at: &dyn Fn(&gix::Commit<'_>) -> Result<PackageFile>,
965) -> Result<Option<VersionCommit>> {
966    let Ok(tagged) = gix::ObjectId::from_hex(sha.as_bytes()) else {
967        return Ok(None);
968    };
969    let Ok(commit) = repo.find_commit(tagged) else {
970        return Ok(None);
971    };
972    if !version_at(&commit)?.is_release_of(wanted) {
973        return Ok(None);
974    }
975    let contains = |at: gix::ObjectId| -> Result<bool> {
976        let base = repo.merge_base(at, tagged).with_context(|| {
977            format!("cannot tell whether HEAD contains tagged commit {sha}; fetch the full history")
978        })?;
979        Ok(base.is_some_and(|base| base == tagged))
980    };
981    let Some(&head) = line.first() else {
982        return Ok(None);
983    };
984    if !contains(head)? {
985        return Ok(None);
986    }
987    let mut inside = 0;
988    let mut outside = line.len();
989    let mut probe = 1;
990    while probe < line.len() {
991        if !contains(line[probe])? {
992            outside = probe;
993            break;
994        }
995        inside = probe;
996        probe *= 2;
997    }
998    while outside - inside > 1 {
999        let mid = inside + (outside - inside) / 2;
1000        if contains(line[mid])? {
1001            inside = mid;
1002        } else {
1003            outside = mid;
1004        }
1005    }
1006    Ok(Some(VersionCommit {
1007        sha: tagged.to_string(),
1008        depth: inside,
1009    }))
1010}
1011
1012fn has_path(commit: &gix::Commit<'_>, rel: &Path) -> Result<bool> {
1013    Ok(commit.tree()?.lookup_entry_by_path(rel)?.is_some())
1014}
1015
1016fn named(commit: &gix::Commit<'_>) -> Result<AddedBy> {
1017    Ok(AddedBy {
1018        sha: commit.id().to_string(),
1019        subject: commit.message()?.summary().to_str_lossy().into_owned(),
1020    })
1021}
1022
1023/// The pull request a squash-merge subject names: a trailing `(#N)`.
1024#[must_use]
1025pub fn pull_request_number(subject: &str) -> Option<u64> {
1026    let (_, digits) = subject.trim_end().strip_suffix(')')?.rsplit_once("(#")?;
1027    if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
1028        return None;
1029    }
1030    digits.parse().ok()
1031}
1032
1033/// The branch `origin/HEAD` points at, or `None` when that ref is unset.
1034#[must_use]
1035pub fn upstream_default_branch(root: &Path) -> Option<String> {
1036    origin_head_branch(&discover(root).ok()?)
1037}
1038
1039/// Whether HEAD is off the default-branch history: `None` when the default
1040/// branch contains HEAD, or why it does not, naming both commits.
1041///
1042/// Being off the branch is a finding the caller may allow. A missing fact is
1043/// not a finding: a proof that cannot run fails and names the missing fact.
1044/// A check that passed by skipping itself would let a release run from any
1045/// commit, in exactly the CI shapes where the proof matters.
1046///
1047/// Each of these fails:
1048///
1049/// - no repository;
1050/// - no HEAD commit;
1051/// - no `origin` remote;
1052/// - an `origin` with no peelable default-tracking ref;
1053/// - a shallow clone that cannot walk the graph.
1054///
1055/// # Errors
1056///
1057/// Returns an error when:
1058///
1059/// - no repository covers `root`;
1060/// - HEAD has no commit;
1061/// - there is no `origin` remote;
1062/// - resolving the default branch ref fails;
1063/// - the merge-base cannot be computed, as in a shallow clone.
1064pub fn off_default_history(root: &Path) -> Result<Option<String>> {
1065    prove_default_history(root, &candidate_names(env_base_ref().as_deref()))
1066}
1067
1068/// Whether `.github/workflows/` at the commit the run executes differs from
1069/// the default branch's tip.
1070/// It is `None` when the two trees are the same object, and otherwise names
1071/// both commits.
1072///
1073/// Actions runs the workflows of `GITHUB_SHA`.
1074/// In a reusable workflow's publish job HEAD is the version commit instead.
1075/// So the tree compared is the one at `GITHUB_SHA` when that variable names a
1076/// commit in the repository, and HEAD's otherwise.
1077///
1078/// A retry of an old release commit runs its workflows as they were at that
1079/// commit. Steps or permissions changed since can publish to the registry and
1080/// then fail to tag, and the registry cannot take a version back.
1081///
1082/// Equal tree ids prove equal content, so no file is read. A tree that is
1083/// missing on both sides counts as equal.
1084///
1085/// # Errors
1086///
1087/// Returns an error when no repository covers `root`, HEAD has no commit, or
1088/// the default branch ref is missing or cannot be resolved.
1089pub fn workflows_differ(root: &Path) -> Result<Option<String>> {
1090    workflows_differ_at(root, env_run_sha().as_deref())
1091}
1092
1093/// [`workflows_differ`] with the run's commit given in place of `GITHUB_SHA`.
1094fn workflows_differ_at(root: &Path, run_sha: Option<&str>) -> Result<Option<String>> {
1095    let repo = repo_covering(root).with_context(|| {
1096        format!(
1097            "release cannot compare workflows: no git repository covers {}",
1098            root.display()
1099        )
1100    })?;
1101    let head = repo
1102        .head_commit()
1103        .context("release cannot compare workflows: HEAD has no commit")?;
1104    let (run, label) = run_sha
1105        .and_then(|sha| find_commit_by_hex(&repo, sha))
1106        .map_or((head, "HEAD"), |commit| (commit, "GITHUB_SHA"));
1107    let upstream = default_upstream_commit(&repo, &candidate_names(env_base_ref().as_deref()))?
1108        .context("release cannot compare workflows: there is no `origin` remote")?;
1109    let upstream = repo.find_commit(upstream)?;
1110    let workflows = |commit: &gix::Commit<'_>| -> Result<Option<gix::ObjectId>> {
1111        Ok(commit
1112            .tree()?
1113            .lookup_entry_by_path(WORKFLOWS)?
1114            .map(|entry| entry.object_id()))
1115    };
1116    if workflows(&run)? == workflows(&upstream)? {
1117        return Ok(None);
1118    }
1119    Ok(Some(format!(
1120        "{WORKFLOWS}/ at {label} {run} differs from the default branch at {upstream}",
1121        run = run.id(),
1122        upstream = upstream.id(),
1123    )))
1124}
1125
1126/// The commit a full hex SHA names, or `None` when it is not valid hex or
1127/// names no commit in the repository.
1128fn find_commit_by_hex<'repo>(
1129    repo: &'repo gix::Repository,
1130    sha: &str,
1131) -> Option<gix::Commit<'repo>> {
1132    let id = gix::ObjectId::from_hex(sha.as_bytes()).ok()?;
1133    repo.find_commit(id).ok()
1134}
1135
1136fn env_run_sha() -> Option<String> {
1137    env::var("GITHUB_SHA")
1138        .ok()
1139        .map(|value| value.trim().to_owned())
1140        .filter(|value| !value.is_empty())
1141}
1142
1143/// Where a repository keeps its GitHub Actions workflows.
1144const WORKFLOWS: &str = ".github/workflows";
1145
1146/// How to fetch `origin/<branch>` when that ref is missing.
1147#[non_exhaustive]
1148pub enum FetchDefault {
1149    /// `git fetch origin`.
1150    Origin,
1151    /// GitHub HTTPS. Credentials are the callback, never the URL.
1152    GitHub {
1153        /// Access token for the fetch.
1154        token: String,
1155        /// The `owner/name` slug.
1156        repository: String,
1157    },
1158}
1159
1160/// Prints the repository but never the token, so a logged value leaks no
1161/// credential.
1162impl fmt::Debug for FetchDefault {
1163    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1164        match self {
1165            Self::Origin => f.write_str("Origin"),
1166            Self::GitHub {
1167                repository,
1168                token: _,
1169            } => f
1170                .debug_struct("GitHub")
1171                .field("token", &"<redacted>")
1172                .field("repository", repository)
1173                .finish(),
1174        }
1175    }
1176}
1177
1178impl FetchDefault {
1179    /// `GitHub` when `GITHUB_TOKEN` and `GITHUB_REPOSITORY` are both set and
1180    /// non-empty, else `Origin`.
1181    #[must_use]
1182    pub fn from_env() -> Self {
1183        match (env::var("GITHUB_TOKEN"), env::var("GITHUB_REPOSITORY")) {
1184            (Ok(token), Ok(repository)) if !token.is_empty() && !repository.is_empty() => {
1185                Self::GitHub { token, repository }
1186            }
1187            _ => Self::Origin,
1188        }
1189    }
1190}
1191
1192/// HTTPS URL for an `owner/name` slug. No credentials in the URL.
1193#[must_use]
1194pub fn github_https_url(repository: &str) -> String {
1195    format!("https://github.com/{repository}.git")
1196}
1197
1198/// Username GitHub git-over-HTTPS expects. Not an HTTP Bearer scheme.
1199#[must_use]
1200pub fn github_git_user() -> &'static str {
1201    "x-access-token"
1202}
1203
1204/// `VERCTL_DEFAULT_BRANCH` only.
1205///
1206/// `GITHUB_BASE_REF` is a candidate for `off_default_history` only. It never
1207/// names a branch to rewrite `origin/HEAD` with.
1208#[must_use]
1209pub fn configured_default_branch() -> Option<String> {
1210    env::var("VERCTL_DEFAULT_BRANCH")
1211        .ok()
1212        .map(|value| value.trim().to_owned())
1213        .filter(|value| !value.is_empty())
1214}
1215
1216/// Point `origin/HEAD` at `origin/<branch>`. Fetch that one ref only
1217/// when it is missing. The fetch gets the branch's history instead of a
1218/// depth-1 tip, because `off_default_history` walks parents.
1219///
1220/// An empty `branch`, no repository, and no `origin` remote are each a no-op.
1221///
1222/// # Errors
1223///
1224/// Returns an error when:
1225///
1226/// - the fetch fails (remote unreachable, credentials rejected, or the branch
1227///   absent on the remote);
1228/// - `origin/<branch>` is still missing afterwards;
1229/// - `origin/HEAD` cannot be updated.
1230pub fn ensure_origin_head(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
1231    if branch.is_empty() {
1232        return Ok(());
1233    }
1234    let Some(repo) = repo_covering(root) else {
1235        return Ok(());
1236    };
1237    if !has_origin(&repo) {
1238        return Ok(());
1239    }
1240    let remote_ref = format!("refs/remotes/origin/{branch}");
1241    if peel_remote(&repo, &remote_ref).is_none() {
1242        fetch_one_branch(&repo, branch, fetch, Shallow::NoChange)?;
1243    }
1244    ensure!(
1245        peel_remote(&repo, &remote_ref).is_some(),
1246        "cannot resolve the default branch ({remote_ref} is missing; fetch the default branch)"
1247    );
1248    let target = FullName::try_from(remote_ref.as_str())
1249        .context("point origin/HEAD at the default branch")?;
1250    let name = FullName::try_from("refs/remotes/origin/HEAD")
1251        .context("point origin/HEAD at the default branch")?;
1252    repo.edit_reference(RefEdit::update(
1253        name,
1254        Target::Symbolic(target),
1255        PreviousValue::Any,
1256        "verctl default branch",
1257    ))
1258    .context("point origin/HEAD at the default branch")?;
1259    Ok(())
1260}
1261
1262/// Points at `VERCTL_DEFAULT_BRANCH` only while it is unset: once set,
1263/// [`ensure_full_history`] has run, and a commit still past the boundary is
1264/// not on the default branch.
1265fn shallow_hint() -> &'static str {
1266    if configured_default_branch().is_some() {
1267        ""
1268    } else {
1269        ", or set VERCTL_DEFAULT_BRANCH so verctl fetches it"
1270    }
1271}
1272
1273/// Fetch the whole history of `origin/<branch>` when the clone is shallow.
1274///
1275/// A depth-1 checkout, which is the default of `actions/checkout`, ends at a
1276/// commit that has no parents. All of these then stop at the boundary:
1277///
1278/// - finding the commit that set a version;
1279/// - finding a tag's commit;
1280/// - proving HEAD is on the default branch.
1281///
1282/// Fetching the default branch without a depth limit removes that boundary for
1283/// every commit on it, the version commit included.
1284///
1285/// A clone that is not shallow, an empty `branch`, no repository, and no
1286/// `origin` remote are each a no-op. The walks then report the boundary.
1287///
1288/// # Errors
1289///
1290/// Returns an error when:
1291///
1292/// - the shallow boundary cannot be read;
1293/// - the fetch fails (remote unreachable, credentials rejected, or the branch
1294///   absent on the remote).
1295pub fn ensure_full_history(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
1296    if branch.is_empty() {
1297        return Ok(());
1298    }
1299    let Some(repo) = repo_covering(root) else {
1300        return Ok(());
1301    };
1302    if !has_origin(&repo) || !repo.is_shallow().context("read the shallow boundary")? {
1303        return Ok(());
1304    }
1305    fetch_one_branch(&repo, branch, fetch, Shallow::undo())
1306}
1307
1308/// Fetch `origin/<branch>` so a merge-base with HEAD can be computed: when the
1309/// ref is missing, or when the clone is shallow.
1310///
1311/// A pull request checkout from `actions/checkout` contains only the depth-1
1312/// merge ref, with no `origin/<base>` and a parentless HEAD. Undoing the
1313/// boundary sends the parents of every commit the clone marks shallow, HEAD
1314/// included, so the walk from HEAD reaches the base branch.
1315///
1316/// A full clone that has the ref, an empty `branch`, no repository, and no
1317/// `origin` remote are each a no-op.
1318///
1319/// # Errors
1320///
1321/// Returns an error when:
1322///
1323/// - the shallow boundary cannot be read;
1324/// - the fetch fails (remote unreachable, credentials rejected, or the branch
1325///   absent on the remote).
1326pub fn ensure_comparable(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
1327    if branch.is_empty() {
1328        return Ok(());
1329    }
1330    let Some(repo) = repo_covering(root) else {
1331        return Ok(());
1332    };
1333    if !has_origin(&repo) {
1334        return Ok(());
1335    }
1336    let shallow = repo.is_shallow().context("read the shallow boundary")?;
1337    let missing = peel_remote(&repo, &format!("refs/remotes/origin/{branch}")).is_none();
1338    match (shallow, missing) {
1339        (true, _) => fetch_one_branch(&repo, branch, fetch, Shallow::undo()),
1340        (false, true) => fetch_one_branch(&repo, branch, fetch, Shallow::NoChange),
1341        (false, false) => Ok(()),
1342    }
1343}
1344
1345/// Materialize the repository tree at release tag `tag` into `dir`, returning
1346/// the path inside `dir` that corresponds to `root`.
1347///
1348/// Looks up `refs/tags/<tag>` locally first. When absent and the repository
1349/// has an `origin` remote, fetches `refs/tags/<tag>` alone through `fetch`
1350/// (depth 1 on a shallow clone, `NoChange` on a full clone so full history is
1351/// preserved). Regular files keep their executable bit and symlinks are
1352/// skipped, matching [`MergeBase::write_to`].
1353///
1354/// # Errors
1355///
1356/// Returns an error when `root` is outside a git repository, when `tag` is
1357/// empty or exists neither locally nor on `origin`, or when the tree cannot be
1358/// read or written.
1359pub fn extract_tag_tree(
1360    root: &Path,
1361    tag: &str,
1362    dir: &Path,
1363    fetch: &FetchDefault,
1364) -> Result<PathBuf> {
1365    use std::os::unix::fs::PermissionsExt as _;
1366
1367    ensure!(!tag.is_empty(), "baseline tag name must not be empty");
1368    let repo =
1369        discover(root).context("extracting a baseline release tag needs a git repository")?;
1370    let mut commit_id = peel_tag_commit(&repo, tag)?;
1371    if commit_id.is_none() && has_origin(&repo) {
1372        let shallow = if repo.is_shallow().context("read the shallow boundary")? {
1373            Shallow::DepthAtRemote(NonZeroU32::MIN)
1374        } else {
1375            Shallow::NoChange
1376        };
1377        let spec = format!("+refs/tags/{tag}:refs/tags/{tag}");
1378        fetch_one_ref(&repo, &spec, fetch, shallow, "fetch the baseline tag")?;
1379        commit_id = peel_tag_commit(&repo, tag)?;
1380    }
1381    let Some(commit_id) = commit_id else {
1382        bail!(
1383            "baseline tag {tag} was not found locally or on origin; verctl semver needs the release tag to build locked rustdoc JSON"
1384        );
1385    };
1386    let tree = repo
1387        .find_commit(commit_id)
1388        .with_context(|| format!("read commit {commit_id} for tag {tag}"))?
1389        .tree()
1390        .with_context(|| format!("read tree for tag {tag}"))?;
1391    let files = files_of(&tree)?;
1392    for (rel, (oid, kind)) in files {
1393        let mode = match kind {
1394            EntryKind::Blob => 0o644,
1395            EntryKind::BlobExecutable => 0o755,
1396            EntryKind::Link | EntryKind::Tree | EntryKind::Commit => continue,
1397        };
1398        let path = dir.join(&rel);
1399        if let Some(parent) = path.parent() {
1400            fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
1401        }
1402        let blob = repo
1403            .find_blob(oid)
1404            .with_context(|| format!("read blob {rel} at tag {tag}"))?;
1405        fs::write(&path, &blob.data).with_context(|| format!("write {}", path.display()))?;
1406        fs::set_permissions(&path, Permissions::from_mode(mode))
1407            .with_context(|| format!("chmod {}", path.display()))?;
1408    }
1409    let prefix = project_prefix(&repo, root);
1410    Ok(if prefix.as_os_str().is_empty() {
1411        dir.to_path_buf()
1412    } else {
1413        dir.join(prefix)
1414    })
1415}
1416
1417fn peel_tag_commit(repo: &gix::Repository, tag: &str) -> Result<Option<gix::ObjectId>> {
1418    let full = format!("refs/tags/{tag}");
1419    let Some(mut reference) = repo
1420        .try_find_reference(&full)
1421        .with_context(|| format!("look up {full}"))?
1422    else {
1423        return Ok(None);
1424    };
1425    let commit = reference
1426        .peel_to_commit()
1427        .with_context(|| format!("tag {tag} does not point to a commit"))?;
1428    Ok(Some(commit.id().detach()))
1429}
1430
1431/// Fetches `branch` alone into `origin/<branch>`, through a remote that carries
1432/// only that refspec and no tags, so the configured `origin` refspecs cannot
1433/// widen the fetch. `shallow` controls what happens to a shallow clone's
1434/// boundary.
1435fn fetch_one_branch(
1436    repo: &gix::Repository,
1437    branch: &str,
1438    fetch: &FetchDefault,
1439    shallow: Shallow,
1440) -> Result<()> {
1441    let spec = format!("+refs/heads/{branch}:refs/remotes/origin/{branch}");
1442    fetch_one_ref(repo, &spec, fetch, shallow, "fetch the default branch")
1443}
1444
1445fn fetch_one_ref(
1446    repo: &gix::Repository,
1447    spec: &str,
1448    fetch: &FetchDefault,
1449    shallow: Shallow,
1450    context: &str,
1451) -> Result<()> {
1452    let url = match fetch {
1453        FetchDefault::Origin => origin_url_of(repo)?,
1454        FetchDefault::GitHub {
1455            repository,
1456            token: _,
1457        } => github_https_url(repository),
1458    };
1459    let remote = repo
1460        .remote_at(url.as_str())
1461        .with_context(|| context.to_owned())?
1462        .with_fetch_tags(Tags::None)
1463        .with_refspecs([spec], Direction::Fetch)
1464        .with_context(|| context.to_owned())?;
1465    let connection = remote
1466        .connect(Direction::Fetch)
1467        .with_context(|| format!("git fetch {spec}"))?;
1468    let interrupt = AtomicBool::new(false);
1469    match fetch {
1470        FetchDefault::Origin => connection
1471            .prepare_fetch(Discard, ref_map::Options::default())
1472            .with_context(|| format!("git fetch {spec}"))?
1473            .with_shallow(shallow)
1474            .receive(Discard, &interrupt),
1475        FetchDefault::GitHub {
1476            token,
1477            repository: _,
1478        } => connection
1479            .with_credentials(github_credentials(token))
1480            .prepare_fetch(Discard, ref_map::Options::default())
1481            .with_context(|| format!("git fetch {spec}"))?
1482            .with_shallow(shallow)
1483            .receive(Discard, &interrupt),
1484    }
1485    .with_context(|| format!("git fetch {spec}"))?;
1486    Ok(())
1487}
1488
1489/// Answers every credential request with `x-access-token` and `token`, kept in
1490/// memory: the token never reaches a URL, a config file, or a helper program.
1491fn github_credentials(token: &str) -> impl FnMut(Action) -> gix::Result<Option<Outcome>> + '_ {
1492    move |action| match action {
1493        Action::Get(context) => Ok(Some(Outcome {
1494            identity: Account {
1495                username: github_git_user().to_owned(),
1496                password: token.to_owned(),
1497                oauth_refresh_token: None,
1498            },
1499            next: context.into(),
1500        })),
1501        Action::Store(_) | Action::Erase(_) => Ok(None),
1502    }
1503}
1504
1505fn prove_default_history(root: &Path, candidates: &[String]) -> Result<Option<String>> {
1506    let repo = repo_covering(root).with_context(|| {
1507        format!(
1508            "release cannot prove HEAD is on the default branch: no git repository covers {}",
1509            root.display()
1510        )
1511    })?;
1512    let head = repo
1513        .head_commit()
1514        .context("release cannot prove HEAD is on the default branch: HEAD has no commit")?
1515        .id()
1516        .detach();
1517    let upstream = default_upstream_commit(&repo, candidates)?.context(
1518        "release cannot prove HEAD is on the default branch: there is no `origin` remote; add it and fetch the default branch",
1519    )?;
1520    if head == upstream {
1521        return Ok(None);
1522    }
1523    match repo.merge_base(head, upstream) {
1524        Ok(Some(base)) if base == head => Ok(None),
1525        Ok(Some(_) | None) => Ok(Some(format!(
1526            "HEAD {head} is not an ancestor of the default branch at {upstream}"
1527        ))),
1528        Err(error) => Err(error).context(
1529            "release cannot prove HEAD is on the default branch (need a full fetch, not a shallow clone)",
1530        ),
1531    }
1532}
1533
1534/// The working tree that contains `dir`, canonicalized.
1535///
1536/// The ceiling for an upward file search: nothing above a repository
1537/// root belongs to the project inside it.
1538#[must_use]
1539pub fn workdir_covering(dir: &Path) -> Option<PathBuf> {
1540    repo_covering(dir)?
1541        .workdir()
1542        .and_then(|workdir| workdir.canonicalize().ok())
1543}
1544
1545/// Every path git tracks under `root`, relative to `root` itself.
1546///
1547/// The list comes from the index instead of a directory walk. Build output,
1548/// vendored trees, and anything else gitignored is not part of what this repo
1549/// publishes.
1550///
1551/// The index contains paths from the working tree. `root` is a project inside
1552/// it (one repository may contain several), so anything outside `root` is not
1553/// this project's. What is left is rebased onto `root`.
1554///
1555/// A tree with no repository tracks nothing (it cannot serve a file by tag). A
1556/// repository whose index cannot be read is an error, never an empty answer.
1557///
1558/// # Errors
1559///
1560/// Returns an error when the repository's index cannot be read.
1561pub fn tracked(root: &Path) -> Result<Vec<PathBuf>> {
1562    let Some(repo) = repo_covering(root) else {
1563        return Ok(Vec::new());
1564    };
1565    let index = repo.index_or_empty().context("git index")?;
1566    let project = project_prefix(&repo, root);
1567    Ok(index
1568        .entries()
1569        .iter()
1570        .filter_map(|entry| entry.path(&index).to_str().ok().map(PathBuf::from))
1571        .filter_map(|path| path.strip_prefix(&project).ok().map(Path::to_path_buf))
1572        .collect())
1573}
1574
1575/// Whether the repository is told to ignore `rel`, a path relative to `root`.
1576///
1577/// Ignoring a file marks it as not part of what the repo publishes. That is
1578/// the same fact `tracked` already reads the index for. So an ignored file is
1579/// not a forgotten one, and nothing should ask its author to commit it.
1580///
1581/// A file under an ignored directory is ignored too, as git has it. gix
1582/// matches the one path it is given, so each parent directory is checked
1583/// first.
1584#[must_use]
1585pub fn is_ignored(root: &Path, rel: &Path) -> bool {
1586    let Some(repo) = repo_covering(root) else {
1587        return false;
1588    };
1589    let path = project_prefix(&repo, root).join(rel);
1590    let Ok(index) = repo.index_or_empty() else {
1591        return false;
1592    };
1593    let Ok(mut excludes) = repo.excludes(&index, None, Source::WorktreeThenIdMappingIfNotSkipped)
1594    else {
1595        return false;
1596    };
1597    let mut ignored_at = |path: &Path, mode| {
1598        excludes
1599            .at_path(path, mode)
1600            .is_ok_and(|platform| platform.is_excluded())
1601    };
1602    path.ancestors()
1603        .skip(1)
1604        .filter(|dir| !dir.as_os_str().is_empty())
1605        .any(|dir| ignored_at(dir, Some(Mode::DIR)))
1606        || ignored_at(&path, None)
1607}
1608
1609/// Whether a repository covers `root` at all.
1610///
1611/// `tracked` answers "nothing" both for an empty index and for a tree with no
1612/// repository. Those are different states: a file the index does not carry is
1613/// untracked only where an index exists to not carry it.
1614#[must_use]
1615pub fn is_repository(root: &Path) -> bool {
1616    repo_covering(root).is_some()
1617}
1618
1619/// Where `root` sits inside the working tree: empty when it is the root.
1620fn project_prefix(repo: &gix::Repository, root: &Path) -> PathBuf {
1621    let Some(workdir) = repo.workdir().and_then(|dir| dir.canonicalize().ok()) else {
1622        return PathBuf::new();
1623    };
1624    root.canonicalize()
1625        .ok()
1626        .and_then(|root| root.strip_prefix(&workdir).ok().map(Path::to_path_buf))
1627        .unwrap_or_default()
1628}
1629
1630/// The repository that covers `dir`, searching upward, as it is on disk.
1631///
1632/// A git hook exports repository-local variables for its own git process.
1633/// pre-commit sets `GIT_INDEX_FILE` to a temporary index, given as a path
1634/// relative to git's working directory, and may set `GIT_DIR` and
1635/// `GIT_WORK_TREE`. verctl ignores them, as libgit2 did, so a command behaves
1636/// the same inside a hook and outside one.
1637///
1638/// gix's catch-all permission for `GIT_*` variables is denied, which drops
1639/// those overrides. Identity and HTTP variables keep their own permissions.
1640/// `GIT_DIR` is never read, because discovery starts from `dir` instead of the
1641/// environment. Nothing in this module writes the index.
1642///
1643/// Fetches and branch updates write reflog entries, which gix refuses without
1644/// a committer. A CI runner often has no git identity configured, so
1645/// [`fallback_identity`] fills that gap. A configured identity still wins.
1646fn discover(dir: &Path) -> Result<gix::Repository> {
1647    let mapping = Mapping {
1648        full: open_options(Trust::Full),
1649        reduced: open_options(Trust::Reduced),
1650    };
1651    let repo = gix::ThreadSafeRepository::discover_opts(
1652        dir,
1653        gix::discover::upwards::Options::default(),
1654        mapping,
1655    )
1656    .with_context(|| format!("no git repository covers {}", dir.display()))?;
1657    let mut repo = repo.to_thread_local();
1658    let (name, email) = fallback_identity();
1659    repo.committer_or_set_fallback(name.as_str(), email.as_str())
1660        .context("set the reflog identity")?;
1661    Ok(repo)
1662}
1663
1664/// gix's defaults for `trust`, without the repository-local `GIT_*` overrides.
1665fn open_options(trust: Trust) -> open::Options {
1666    let mut options = open::Options::default_for_level(trust);
1667    options.permissions.env.git_prefix = Permission::Deny;
1668    options
1669}
1670
1671fn repo_covering(root: &Path) -> Option<gix::Repository> {
1672    let repo = discover(root).ok()?;
1673    let workdir = repo.workdir()?.canonicalize().ok()?;
1674    let root = root.canonicalize().ok()?;
1675    root.starts_with(workdir).then_some(repo)
1676}
1677
1678fn has_origin(repo: &gix::Repository) -> bool {
1679    repo.remote_names()
1680        .iter()
1681        .any(|name| name.to_str() == Ok("origin"))
1682}
1683
1684fn origin_url_of(repo: &gix::Repository) -> Result<String> {
1685    let remote = repo
1686        .find_remote("origin")
1687        .context("fetch the default branch")?;
1688    let url = remote.url(Direction::Fetch).context("origin has no URL")?;
1689    Ok(url.to_bstring().to_str_lossy().into_owned())
1690}
1691
1692fn peel_remote(repo: &gix::Repository, name: &str) -> Option<gix::ObjectId> {
1693    let mut reference = repo.try_find_reference(name).ok()??;
1694    let commit = reference.peel_to_commit().ok()?;
1695    Some(commit.id().detach())
1696}
1697
1698fn origin_head_branch(repo: &gix::Repository) -> Option<String> {
1699    let reference = repo.try_find_reference("refs/remotes/origin/HEAD").ok()??;
1700    let target = reference.target();
1701    let target = target.try_name()?.as_bstr().to_str().ok()?;
1702    let name = target.trim_start_matches("refs/remotes/origin/");
1703    (!name.is_empty()).then(|| name.to_owned())
1704}
1705
1706fn env_base_ref() -> Option<String> {
1707    env::var("GITHUB_BASE_REF")
1708        .ok()
1709        .map(|value| value.trim().to_owned())
1710        .filter(|value| !value.is_empty())
1711}
1712
1713/// `GITHUB_BASE_REF` (PR base) then `main` / `master`.
1714///
1715/// `GITHUB_REF_NAME` is not a candidate: on push it is the branch
1716/// being pushed, so `origin/<that branch>` would always match HEAD.
1717/// A non-main default on Actions is `origin/HEAD`, which
1718/// `ensure_origin_head` fetches and points at
1719/// `VERCTL_DEFAULT_BRANCH`.
1720#[must_use]
1721pub fn default_branch_candidates() -> Vec<String> {
1722    candidate_names(env_base_ref().as_deref())
1723}
1724
1725/// The branch releases come from, whatever branch a pull request targets. The
1726/// candidates, in order:
1727///
1728/// 1. `VERCTL_DEFAULT_BRANCH`;
1729/// 2. the event's repository default branch
1730///    ([`verctl_core::env::event_default_branch`]);
1731/// 3. `main` / `master`;
1732/// 4. `GITHUB_BASE_REF`.
1733///
1734/// The event's default covers a default branch with another name, which
1735/// Actions leaves without `origin/HEAD`. The pull request's base comes last,
1736/// for a run with neither.
1737#[must_use]
1738pub fn release_branch_candidates() -> Vec<String> {
1739    release_candidate_names(
1740        configured_default_branch().as_deref(),
1741        github_env::event_default_branch().as_deref(),
1742        env_base_ref().as_deref(),
1743    )
1744}
1745
1746fn release_candidate_names(
1747    configured: Option<&str>,
1748    event_default: Option<&str>,
1749    base: Option<&str>,
1750) -> Vec<String> {
1751    let mut names = Vec::new();
1752    for name in [configured, event_default].into_iter().flatten() {
1753        if !name.is_empty() && !names.iter().any(|known| known == name) {
1754            names.push(name.to_owned());
1755        }
1756    }
1757    for name in candidate_names(None)
1758        .into_iter()
1759        .chain(base.map(str::to_owned))
1760    {
1761        if !name.is_empty() && !names.contains(&name) {
1762            names.push(name);
1763        }
1764    }
1765    names
1766}
1767
1768/// The branches a version comparison fetches when they are missing:
1769/// `VERCTL_DEFAULT_BRANCH`, then the event's repository default branch, then
1770/// `GITHUB_BASE_REF`. The default branch is fetched
1771/// even when the pull request targets another branch, so the released
1772/// baseline reads the same branch a full clone would. None is set outside
1773/// Actions, so a local run fetches nothing.
1774#[must_use]
1775pub fn comparison_branches() -> Vec<String> {
1776    let mut names = Vec::new();
1777    let sources = [
1778        configured_default_branch(),
1779        github_env::event_default_branch(),
1780        env_base_ref(),
1781    ];
1782    for name in sources.into_iter().flatten() {
1783        if !name.is_empty() && !names.contains(&name) {
1784            names.push(name);
1785        }
1786    }
1787    names
1788}
1789
1790/// Like `default_branch_candidates`, but the caller supplies the base ref and
1791/// the environment is not read.
1792#[must_use]
1793pub fn default_branch_candidates_from(base_ref: Option<&str>) -> Vec<String> {
1794    candidate_names(base_ref)
1795}
1796
1797fn candidate_names(base_ref: Option<&str>) -> Vec<String> {
1798    let mut names = Vec::new();
1799    if let Some(value) = base_ref.map(str::trim).filter(|value| !value.is_empty()) {
1800        names.push(value.to_owned());
1801    }
1802    for stock in ["main", "master"] {
1803        if !names.iter().any(|name| name == stock) {
1804            names.push(stock.to_owned());
1805        }
1806    }
1807    names
1808}
1809
1810fn default_upstream_commit(
1811    repo: &gix::Repository,
1812    candidates: &[String],
1813) -> Result<Option<gix::ObjectId>> {
1814    if let Some(branch) = origin_head_branch(repo) {
1815        let name = format!("refs/remotes/origin/{branch}");
1816        return match peel_remote(repo, &name) {
1817            Some(commit) => Ok(Some(commit)),
1818            None => bail!(
1819                "cannot resolve the default branch ({name} is missing; fetch the default branch)"
1820            ),
1821        };
1822    }
1823    for name in candidates {
1824        let reference = format!("refs/remotes/origin/{name}");
1825        if let Some(commit) = peel_remote(repo, &reference) {
1826            return Ok(Some(commit));
1827        }
1828    }
1829    if has_origin(repo) {
1830        bail!(
1831            "cannot resolve the default branch (origin exists but origin/HEAD, origin/main, and origin/master are missing; fetch the default branch)"
1832        );
1833    }
1834    Ok(None)
1835}
1836
1837/// Whether `rel` matches a `prepare.stage` glob `pattern` (either directly or
1838/// with a leading `./`).
1839#[must_use]
1840pub fn matches_stage(pattern: &str, rel: &str) -> bool {
1841    glob::Pattern::new(pattern)
1842        .is_ok_and(|compiled| compiled.matches(rel) || compiled.matches(&format!("./{rel}")))
1843}
1844
1845/// Whether `assert_only_allowed` and status lookups inspect gitignored files.
1846#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1847pub enum IgnoredFiles {
1848    /// Inspect only tracked and untracked files (skip gitignored paths).
1849    #[default]
1850    Skip,
1851    /// Include gitignored files matched by declared `prepare.stage` globs.
1852    Include,
1853}
1854
1855/// Fail if the worktree has dirty paths outside `allowed` and `globs`.
1856///
1857/// Returns dirty paths that match `globs` (modified, untracked, or
1858/// deleted files). Directories are skipped. Same `git status` walk as
1859/// the unexpected-dirty check; not a filesystem glob. Renames are not
1860/// tracked, so a moved file shows as its old and its new path, each of
1861/// which must be allowed.
1862///
1863/// # Errors
1864///
1865/// Returns an error when `git status` cannot be computed, or when a dirty
1866/// path is neither in `allowed` nor matched by `globs`. The latter error lists
1867/// those paths. A root outside a repository is not an error and returns an
1868/// empty list.
1869pub fn assert_only_allowed(
1870    root: &Path,
1871    allowed: &[PathBuf],
1872    globs: &[String],
1873    ignored: IgnoredFiles,
1874) -> Result<Vec<PathBuf>> {
1875    let Ok(repo) = discover(root) else {
1876        return Ok(Vec::new());
1877    };
1878    let dirty = status_paths(&repo, Vec::new(), IgnoredFiles::Skip).context("git status")?;
1879    let workdir = repo.workdir().unwrap_or(root);
1880    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1881    let workdir = workdir
1882        .canonicalize()
1883        .unwrap_or_else(|_| workdir.to_path_buf());
1884    let mut extra = Vec::new();
1885    let mut staged = Vec::new();
1886    for rel in &dirty {
1887        let abs = workdir.join(rel);
1888        if !abs.starts_with(&root) {
1889            continue;
1890        }
1891        if abs.is_dir() {
1892            continue;
1893        }
1894        if allowed
1895            .iter()
1896            .any(|path| path == &abs || path.ends_with(rel))
1897        {
1898            continue;
1899        }
1900        if globs.iter().any(|pattern| matches_stage(pattern, rel)) {
1901            staged.push(abs);
1902            continue;
1903        }
1904        extra.push(rel.clone());
1905    }
1906    if matches!(ignored, IgnoredFiles::Include) && !globs.is_empty() {
1907        let patterns = globs
1908            .iter()
1909            .map(|pattern| pattern.as_str().into())
1910            .collect();
1911        let ignored =
1912            status_paths(&repo, patterns, IgnoredFiles::Include).context("git status (ignored)")?;
1913        for rel in &ignored {
1914            let abs = workdir.join(rel);
1915            if !abs.starts_with(&root) || abs.is_dir() {
1916                continue;
1917            }
1918            if globs.iter().any(|pattern| matches_stage(pattern, rel))
1919                && !staged.iter().any(|path| path == &abs)
1920            {
1921                staged.push(abs);
1922            }
1923        }
1924    }
1925    if extra.is_empty() {
1926        return Ok(staged);
1927    }
1928    bail!(
1929        "version produced unexpected paths (declare them in prepare.stage): {}",
1930        extra.join(", ")
1931    );
1932}
1933
1934/// The paths `git status` reports, one entry per path, sorted.
1935///
1936/// With [`IgnoredFiles::Skip`]: staged, modified, deleted, and untracked files,
1937/// every untracked file listed on its own. With [`IgnoredFiles::Include`]: only
1938/// the ignored files `patterns` select, each listed on its own.
1939fn status_paths(
1940    repo: &gix::Repository,
1941    patterns: Vec<BString>,
1942    ignored: IgnoredFiles,
1943) -> Result<BTreeSet<String>> {
1944    let include_ignored = matches!(ignored, IgnoredFiles::Include);
1945    let status = repo
1946        .status(Discard)?
1947        .untracked_files(UntrackedFiles::Files)
1948        .index_worktree_rewrites(None)
1949        .tree_index_track_renames(TrackRenames::Disabled);
1950    let status = if include_ignored {
1951        status.dirwalk_options(|options| options.emit_ignored(Some(EmissionMode::Matching)))
1952    } else {
1953        status
1954    };
1955    let mut paths = BTreeSet::new();
1956    for item in status.into_iter(patterns)? {
1957        let item = item?;
1958        let is_ignored = matches!(
1959            &item,
1960            status::Item::IndexWorktree(index_worktree::Item::DirectoryContents {
1961                entry,
1962                collapsed_directory_status: _
1963            }) if matches!(entry.status, Status::Ignored(_))
1964        );
1965        if is_ignored == include_ignored {
1966            paths.insert(item.location().to_str_lossy().into_owned());
1967        }
1968    }
1969    Ok(paths)
1970}
1971
1972/// What [`commit_branch_and_push`] did: `Empty` when the tree was unchanged.
1973///
1974/// Not `#[non_exhaustive]`: `verctl-release` matches both outcomes
1975/// exhaustively.
1976#[derive(Debug, Clone, Copy, Eq, PartialEq)]
1977pub enum PushOutcome {
1978    /// No version files changed.
1979    Empty,
1980    /// Branch was updated and pushed.
1981    Pushed,
1982}
1983
1984/// Commits `paths` onto `branch` without moving HEAD, then force-pushes
1985/// `branch` to `github` over HTTPS with `token`.
1986///
1987/// When `paths` leave the tree unchanged, nothing is pushed and the result is
1988/// [`PushOutcome::Empty`].
1989///
1990/// # Errors
1991///
1992/// Returns an error when:
1993///
1994/// - `root` is not inside a git repository;
1995/// - the repository has no workdir, or HEAD names no commit;
1996/// - a path lies outside the workdir, is not UTF-8, or cannot be read or
1997///   filtered;
1998/// - the commit or branch ref cannot be written;
1999/// - `git push` fails or runs past five minutes.
2000pub fn commit_branch_and_push(
2001    root: &Path,
2002    branch: &str,
2003    message: &str,
2004    token: &str,
2005    github: &Repo,
2006    paths: &[PathBuf],
2007) -> Result<PushOutcome> {
2008    let repo = discover(root).context("open git repository")?;
2009    let workdir = absolute_workdir(&repo)?;
2010    let parent = repo.head_commit().context("HEAD commit")?;
2011    let Some(_) = write_commit_on_branch(&repo, &workdir, &parent, branch, message, paths)? else {
2012        return Ok(PushOutcome::Empty);
2013    };
2014    let url = format!("https://github.com/{}/{}.git", github.owner, github.name);
2015    push(repo.git_dir(), &url, branch, token)?;
2016    Ok(PushOutcome::Pushed)
2017}
2018
2019/// The working tree as an absolute path. gix reports it as it was discovered,
2020/// so a repository found from `.` has `.` for a workdir, and no path would
2021/// strip that prefix.
2022fn absolute_workdir(repo: &gix::Repository) -> Result<PathBuf> {
2023    let workdir = repo.workdir().context("repository has no workdir")?;
2024    path::absolute(workdir).with_context(|| format!("resolve the workdir {}", workdir.display()))
2025}
2026
2027/// The token reaches `git push` through this variable, which only the push's
2028/// own process sees.
2029const PUSH_TOKEN: &str = "VERCTL_GIT_TOKEN";
2030
2031/// The credential helper `git push` runs. For `get` it supplies
2032/// `x-access-token` and the token from [`PUSH_TOKEN`]. It ignores `store` and
2033/// `erase`, so the token is never in argv, a URL, or a credential store.
2034const PUSH_CREDENTIAL_HELPER: &str = r#"!f() { test "$1" = get || return 0; echo username=x-access-token; echo "password=$VERCTL_GIT_TOKEN"; }; f"#;
2035
2036/// How long a push may run before it is killed.
2037const PUSH_TIMEOUT: Duration = Duration::from_mins(5);
2038
2039/// Force-pushes `branch` to `url` with the `git` binary, because gix cannot
2040/// push yet.
2041///
2042/// `credential.helper=` first clears every helper the user configured, so no
2043/// keychain supplies a credential or stores one in its place.
2044/// `GIT_TERMINAL_PROMPT=0` makes a rejected token fail instead of waiting for
2045/// input.
2046///
2047/// The repository's own hooks do not run (`--no-verify`): the branch is
2048/// generated, and libgit2, which pushed it before, never ran hooks either.
2049///
2050/// `--git-dir` names the repository outright, so a `GIT_DIR` a hook exported
2051/// cannot redirect the push. The error, which carries git's stderr, can contain
2052/// the URL but not the token, since git only ever saw the variable's name.
2053fn push(git_dir: &Path, url: &str, branch: &str, token: &str) -> Result<()> {
2054    let git_dir = git_dir
2055        .canonicalize()
2056        .with_context(|| format!("git directory {}", git_dir.display()))?;
2057    let git_dir = format!(
2058        "--git-dir={}",
2059        git_dir.to_str().context("git directory is not UTF-8")?
2060    );
2061    let helper = format!("credential.helper={PUSH_CREDENTIAL_HELPER}");
2062    let refspec = format!("+refs/heads/{branch}:refs/heads/{branch}");
2063    let argv = process::argv(&[
2064        "git",
2065        &git_dir,
2066        "-c",
2067        "credential.helper=",
2068        "-c",
2069        &helper,
2070        "push",
2071        "--no-verify",
2072        "--quiet",
2073        url,
2074        &refspec,
2075    ]);
2076    process::run_limited(
2077        &argv,
2078        &[(PUSH_TOKEN, token), ("GIT_TERMINAL_PROMPT", "0")],
2079        PUSH_TIMEOUT,
2080    )
2081    .context("git push")?;
2082    Ok(())
2083}
2084
2085/// Writes a commit that starts from `parent`'s tree and takes `paths` from the
2086/// working tree, then points `branch` at it. HEAD, the index, and the working
2087/// tree are left alone, because the tree is edited in memory. `None` when the
2088/// tree is unchanged.
2089///
2090/// A path missing from the working tree is removed from the tree. Each file
2091/// passes through the `.gitattributes` clean filters first, as `git add` runs
2092/// them. So `text` normalization and Large File Storage (LFS) pointers match
2093/// what git would store.
2094fn write_commit_on_branch(
2095    repo: &gix::Repository,
2096    workdir: &Path,
2097    parent: &gix::Commit<'_>,
2098    branch: &str,
2099    message: &str,
2100    paths: &[PathBuf],
2101) -> Result<Option<gix::ObjectId>> {
2102    let parent_tree = parent.tree_id().context("HEAD tree")?.detach();
2103    let mut editor = repo.edit_tree(parent_tree).context("edit HEAD tree")?;
2104    let (mut filters, index) = repo
2105        .filter_pipeline(None)
2106        .context("load the .gitattributes filters")?;
2107    for path in paths {
2108        let rel = workdir_rel(workdir, path)?;
2109        let name = rel
2110            .to_str()
2111            .with_context(|| format!("path is not UTF-8: {}", rel.display()))?
2112            .to_owned();
2113        let abs = workdir.join(&rel);
2114        if abs.exists() {
2115            let (kind, data) = worktree_entry(&mut filters, &index, &abs, &rel)?;
2116            let blob = repo
2117                .write_blob(data)
2118                .with_context(|| format!("git add {name}"))?;
2119            editor
2120                .upsert(&name, kind, blob)
2121                .with_context(|| format!("git add {name}"))?;
2122        } else {
2123            editor
2124                .remove(&name)
2125                .with_context(|| format!("git rm {name}"))?;
2126        }
2127    }
2128    let tree = editor.write().context("write tree")?.detach();
2129    if tree == parent_tree {
2130        return Ok(None);
2131    }
2132    let signature = signature(repo);
2133    let commit = Commit {
2134        tree,
2135        parents: [parent.id().detach()].into_iter().collect(),
2136        author: signature.clone(),
2137        committer: signature,
2138        encoding: None,
2139        message: message.into(),
2140        extra_headers: Vec::new(),
2141    };
2142    let id = repo.write_object(&commit).context("git commit")?.detach();
2143    repo.reference(
2144        format!("refs/heads/{branch}"),
2145        id,
2146        PreviousValue::Any,
2147        "verctl: version packages",
2148    )
2149    .context("git commit")?;
2150    Ok(Some(id))
2151}
2152
2153/// The tree entry kind and content for the file at `abs`, which sits at `rel`
2154/// in the working tree. A symbolic link stores its target. A file stores what
2155/// the clean `filters` make of it and keeps its executable bit.
2156fn worktree_entry(
2157    filters: &mut Pipeline<'_>,
2158    index: &State,
2159    abs: &Path,
2160    rel: &Path,
2161) -> Result<(EntryKind, Vec<u8>)> {
2162    let meta = fs::symlink_metadata(abs).with_context(|| abs.display().to_string())?;
2163    if meta.file_type().is_symlink() {
2164        let target = fs::read_link(abs).with_context(|| abs.display().to_string())?;
2165        let target = target
2166            .to_str()
2167            .with_context(|| format!("link target is not UTF-8: {}", abs.display()))?;
2168        return Ok((EntryKind::Link, target.as_bytes().to_vec()));
2169    }
2170    let file = File::open(abs).with_context(|| abs.display().to_string())?;
2171    let mut clean = filters
2172        .convert_to_git(file, rel, index)
2173        .with_context(|| format!("filter {}", rel.display()))?;
2174    let mut data = Vec::new();
2175    Read::read_to_end(&mut clean, &mut data)
2176        .with_context(|| format!("filter {}", rel.display()))?;
2177    Ok((file_kind(&meta), data))
2178}
2179
2180#[cfg(unix)]
2181fn file_kind(meta: &Metadata) -> EntryKind {
2182    use std::os::unix::fs::PermissionsExt;
2183    if meta.permissions().mode() & 0o111 == 0 {
2184        EntryKind::Blob
2185    } else {
2186        EntryKind::BlobExecutable
2187    }
2188}
2189
2190#[cfg(not(unix))]
2191fn file_kind(_meta: &std::fs::Metadata) -> EntryKind {
2192    EntryKind::Blob
2193}
2194
2195/// `path` relative to the working tree. A relative `path` is taken from the
2196/// workdir. An absolute one may spell the workdir as given or canonical. The
2197/// dirty-path check returns canonical paths. The plan keeps the spelling
2198/// verctl was started with, and a checkout behind a symlink spells them
2199/// differently.
2200///
2201/// Both spellings of the workdir are tried against `path` as given and against
2202/// `path` with its parent canonicalized. The second try still works for a file
2203/// that was deleted.
2204fn workdir_rel(workdir: &Path, path: &Path) -> Result<PathBuf> {
2205    let absolute = if path.is_absolute() {
2206        path.to_path_buf()
2207    } else {
2208        workdir.join(path)
2209    };
2210    let normalized: PathBuf = absolute
2211        .components()
2212        .filter(|component| !matches!(component, Component::CurDir))
2213        .collect();
2214    let workdirs = [Some(workdir.to_path_buf()), workdir.canonicalize().ok()];
2215    let through_parent = normalized
2216        .parent()
2217        .and_then(|parent| parent.canonicalize().ok())
2218        .zip(normalized.file_name())
2219        .map(|(parent, name)| parent.join(name));
2220    let paths = [Some(normalized.clone()), through_parent];
2221    paths
2222        .iter()
2223        .flatten()
2224        .find_map(|path| {
2225            workdirs
2226                .iter()
2227                .flatten()
2228                .find_map(|workdir| path.strip_prefix(workdir).ok())
2229        })
2230        .map(Path::to_path_buf)
2231        .with_context(|| format!("path outside workdir: {}", normalized.display()))
2232}
2233
2234/// Who the Version PR commit is by: `user.name` and `user.email` when the
2235/// repository's git config sets both, else the [`fallback_identity`].
2236fn signature(repo: &gix::Repository) -> Signature {
2237    let time = Time::now_local_or_utc();
2238    let config = repo.config_snapshot();
2239    if let (Some(name), Some(email)) = (config.string("user.name"), config.string("user.email")) {
2240        return Signature { name, email, time };
2241    }
2242    let (name, email) = fallback_identity();
2243    Signature {
2244        name: name.into(),
2245        email: email.into(),
2246        time,
2247    }
2248}
2249
2250/// The identity verctl writes under when git config names none:
2251/// `GIT_AUTHOR_NAME` or `GITHUB_ACTOR`, else `verctl`, with
2252/// `GIT_AUTHOR_EMAIL` or that name's GitHub noreply address.
2253fn fallback_identity() -> (String, String) {
2254    let name = env::var("GIT_AUTHOR_NAME")
2255        .or_else(|_| env::var("GITHUB_ACTOR"))
2256        .unwrap_or_else(|_| "verctl".into());
2257    let email =
2258        env::var("GIT_AUTHOR_EMAIL").unwrap_or_else(|_| format!("{name}@users.noreply.github.com"));
2259    (name, email)
2260}
2261
2262#[cfg(test)]
2263mod tests {
2264    use std::fs;
2265    use std::os::unix::fs::symlink;
2266    use std::path::{Path, PathBuf};
2267
2268    use indoc::indoc;
2269    use tokio::task;
2270    use verctl_core::repo::Repo;
2271    use wiremock::matchers;
2272
2273    use super::{
2274        AddedBy, VersionCommit, added_by, added_by_from, candidate_deletions, file_at, origin_url,
2275        tagged_commit,
2276    };
2277    use crate::test_git::{commit_all, git, init};
2278
2279    /// The version a `VERSION` fixture contains, or `None` for an empty file.
2280    fn version_file(raw: &str) -> Option<String> {
2281        let version = raw.trim();
2282        (!version.is_empty()).then(|| version.to_owned())
2283    }
2284
2285    /// A fragment that bumps `demo` by `bump`, with `summary` as its body.
2286    fn fragment(bump: &str, summary: &str) -> String {
2287        indoc::formatdoc! {"
2288            ---
2289            demo: {bump}
2290            ---
2291
2292            {summary}
2293        "}
2294    }
2295
2296    /// A stable release, then two candidates that each consume one fragment,
2297    /// with a stray fragment added and deleted between them by commits that
2298    /// set no version. Returns the commit that added `one.md` and the first
2299    /// candidate's parent.
2300    fn two_candidates(dir: &Path) -> (String, String) {
2301        init(dir);
2302        fs::create_dir(dir.join(".changeset")).unwrap();
2303        fs::write(dir.join("VERSION"), "0.8.0\n").unwrap();
2304        fs::write(dir.join(".changeset/old.md"), fragment("patch", "Old.")).unwrap();
2305        commit_all(dir, "chore: start");
2306        fs::write(dir.join("VERSION"), "0.8.1\n").unwrap();
2307        fs::remove_file(dir.join(".changeset/old.md")).unwrap();
2308        commit_all(dir, "chore: release demo 0.8.1 (#1)");
2309        fs::write(dir.join(".changeset/one.md"), fragment("patch", "One.")).unwrap();
2310        let added = commit_all(dir, "fix: one (#2)");
2311        fs::write(dir.join("VERSION"), "0.8.2-rc.1\n").unwrap();
2312        fs::remove_file(dir.join(".changeset/one.md")).unwrap();
2313        commit_all(dir, "chore: release demo 0.8.2-rc.1 (#3)");
2314        let first_parent = git(dir, &["rev-parse", "HEAD~1"]);
2315        fs::write(dir.join(".changeset/stray.md"), fragment("patch", "Stray.")).unwrap();
2316        commit_all(dir, "docs: stray (#4)");
2317        fs::remove_file(dir.join(".changeset/stray.md")).unwrap();
2318        commit_all(dir, "docs: drop stray (#5)");
2319        fs::write(dir.join(".changeset/two.md"), fragment("minor", "Two.")).unwrap();
2320        commit_all(dir, "feat: two (#6)");
2321        fs::write(dir.join("VERSION"), "0.8.2-rc.2\n").unwrap();
2322        fs::remove_file(dir.join(".changeset/two.md")).unwrap();
2323        commit_all(dir, "chore: release demo 0.8.2-rc.2 (#7)");
2324        (added, first_parent)
2325    }
2326
2327    #[test]
2328    fn candidate_deletions_lists_what_each_candidate_consumed_since_stable() {
2329        let dir = tempfile::TempDir::new().unwrap();
2330        let (_, first_parent) = two_candidates(dir.path());
2331        let deleted = candidate_deletions(
2332            dir.path(),
2333            &dir.path().join("VERSION"),
2334            &version_file,
2335            &dir.path().join(".changeset"),
2336        )
2337        .unwrap();
2338        let names: Vec<(String, String)> = deleted
2339            .iter()
2340            .map(|file| {
2341                (
2342                    file.path
2343                        .file_name()
2344                        .unwrap()
2345                        .to_string_lossy()
2346                        .into_owned(),
2347                    file.text.clone(),
2348                )
2349            })
2350            .collect();
2351        assert_eq!(
2352            names,
2353            [
2354                ("two.md".to_owned(), fragment("minor", "Two.")),
2355                ("one.md".to_owned(), fragment("patch", "One.")),
2356            ]
2357        );
2358        assert_eq!(deleted[1].parent, first_parent);
2359        assert_eq!(deleted[1].path, dir.path().join(".changeset/one.md"));
2360    }
2361
2362    #[test]
2363    fn candidate_deletions_is_empty_on_a_stable_head() {
2364        let dir = tempfile::TempDir::new().unwrap();
2365        two_candidates(dir.path());
2366        fs::write(dir.path().join("VERSION"), "0.8.2\n").unwrap();
2367        commit_all(dir.path(), "chore: release demo 0.8.2 (#8)");
2368        assert_eq!(
2369            candidate_deletions(
2370                dir.path(),
2371                &dir.path().join("VERSION"),
2372                &version_file,
2373                &dir.path().join(".changeset"),
2374            )
2375            .unwrap(),
2376            []
2377        );
2378    }
2379
2380    #[test]
2381    fn added_by_from_resolves_a_fragment_deleted_at_head() {
2382        let dir = tempfile::TempDir::new().unwrap();
2383        let (added, first_parent) = two_candidates(dir.path());
2384        let path = dir.path().join(".changeset/one.md");
2385        assert_eq!(added_by(dir.path(), &path).unwrap(), None);
2386        assert_eq!(
2387            added_by_from(dir.path(), &path, &first_parent).unwrap(),
2388            Some(AddedBy {
2389                sha: added,
2390                subject: "fix: one (#2)".to_owned(),
2391            })
2392        );
2393    }
2394
2395    /// A stable section built from a shallow clone would leave out the
2396    /// candidates below its boundary, so the walk fails and names the commit.
2397    #[test]
2398    fn candidate_deletions_fails_at_a_shallow_boundary() {
2399        let dir = tempfile::TempDir::new().unwrap();
2400        two_candidates(dir.path());
2401        let boundary = git(dir.path(), &["rev-parse", "HEAD~2"]);
2402        fs::write(dir.path().join(".git/shallow"), format!("{boundary}\n")).unwrap();
2403        let error = candidate_deletions(
2404            dir.path(),
2405            &dir.path().join("VERSION"),
2406            &version_file,
2407            &dir.path().join(".changeset"),
2408        )
2409        .unwrap_err()
2410        .to_string();
2411        assert!(error.contains(&boundary), "{error}");
2412        assert!(error.contains("shallow"), "{error}");
2413    }
2414
2415    /// The paths of every blob in the commit `sha`.
2416    fn tree_names(dir: &Path, sha: &str) -> Vec<String> {
2417        git(dir, &["ls-tree", "-r", "--name-only", sha])
2418            .lines()
2419            .map(str::to_owned)
2420            .collect()
2421    }
2422
2423    fn version_line(raw: &str) -> Option<String> {
2424        raw.lines()
2425            .find_map(|line| line.strip_prefix("version = "))
2426            .map(|version| version.trim_matches('"').to_owned())
2427    }
2428
2429    fn write_version(dir: &Path, version: &str) {
2430        fs::write(
2431            dir.join("Cargo.toml"),
2432            indoc::formatdoc! {r#"
2433                [package]
2434                name = "demo"
2435                version = "{version}"
2436            "#},
2437        )
2438        .unwrap();
2439    }
2440
2441    #[test]
2442    fn a_tag_on_a_later_commit_at_the_same_version_is_the_release() {
2443        let dir = tempfile::TempDir::new().unwrap();
2444        init(dir.path());
2445        write_version(dir.path(), "0.4.6");
2446        let set = commit_all(dir.path(), "chore(release): version packages (#9)");
2447        fs::write(dir.path().join("README"), "later\n").unwrap();
2448        let later = commit_all(dir.path(), "docs: later");
2449        fs::write(dir.path().join("README"), "head\n").unwrap();
2450        commit_all(dir.path(), "docs: head");
2451        let manifest = dir.path().join("Cargo.toml");
2452        let found = tagged_commit(dir.path(), &manifest, &later, &version_line).unwrap();
2453        assert_eq!(
2454            found,
2455            Some(VersionCommit {
2456                sha: later,
2457                depth: 1,
2458            })
2459        );
2460        assert!(
2461            tagged_commit(dir.path(), &manifest, &set, &version_line)
2462                .unwrap()
2463                .is_some()
2464        );
2465    }
2466
2467    #[test]
2468    fn a_tag_on_a_commit_at_another_version_is_not_the_release() {
2469        let dir = tempfile::TempDir::new().unwrap();
2470        init(dir.path());
2471        write_version(dir.path(), "0.4.5");
2472        let older = commit_all(dir.path(), "chore: start");
2473        write_version(dir.path(), "0.4.6");
2474        commit_all(dir.path(), "chore(release): version packages (#9)");
2475        let manifest = dir.path().join("Cargo.toml");
2476        assert_eq!(
2477            tagged_commit(dir.path(), &manifest, &older, &version_line).unwrap(),
2478            None
2479        );
2480        assert_eq!(
2481            tagged_commit(dir.path(), &manifest, &"0".repeat(40), &version_line).unwrap(),
2482            None
2483        );
2484    }
2485
2486    /// An app's `project.yml`, whose `MARKETING_VERSION` line carried its
2487    /// version before the version moved to a `VERSION` file.
2488    fn write_project(dir: &Path, version: &str) {
2489        fs::write(
2490            dir.join("project.yml"),
2491            indoc::formatdoc! {r#"
2492                name: Demo
2493                targets:
2494                  Demo:
2495                    settings:
2496                      base:
2497                        MARKETING_VERSION: "{version}"
2498            "#},
2499        )
2500        .unwrap();
2501    }
2502
2503    /// An app released at `0.0.16` from `project.yml`, then versioned through
2504    /// a new `VERSION` file at the same version. Returns the release commit,
2505    /// which contains no `VERSION`.
2506    fn released_before_the_version_file(dir: &Path) -> String {
2507        init(dir);
2508        write_project(dir, "0.0.16");
2509        let released = commit_all(dir, "chore(release): version packages");
2510        fs::write(dir.join("VERSION"), "0.0.16\n").unwrap();
2511        commit_all(dir, "chore: version the app through a VERSION file");
2512        released
2513    }
2514
2515    /// A release commit beside `main`, made before `main` gained its
2516    /// `VERSION` file at `0.0.16`. HEAD is `main`, which contains the release
2517    /// commit only once [`keep_merged`] merges it. Returns the release commit.
2518    fn released_beside_the_version_file(dir: &Path) -> String {
2519        init(dir);
2520        write_project(dir, "0.0.16");
2521        let start = commit_all(dir, "chore: start");
2522        git(dir, &["checkout", "-q", "--detach", &start]);
2523        fs::write(dir.join("publish.yml"), "published\n").unwrap();
2524        let released = commit_all(dir, "ci: publish");
2525        git(dir, &["checkout", "-q", "main"]);
2526        fs::write(dir.join("VERSION"), "0.0.16\n").unwrap();
2527        commit_all(dir, "chore: version the app through a VERSION file");
2528        released
2529    }
2530
2531    /// Merge `sha` into HEAD as its second parent, keeping HEAD's tree, as a
2532    /// forkctl append publish does.
2533    fn keep_merged(dir: &Path, sha: &str) {
2534        git(
2535            dir,
2536            &[
2537                "merge",
2538                "-q",
2539                "-s",
2540                "ours",
2541                "-m",
2542                "forkctl: keep published history",
2543                sha,
2544            ],
2545        );
2546    }
2547
2548    #[test]
2549    fn a_tag_on_a_commit_before_the_version_file_existed_is_the_release() {
2550        let dir = tempfile::TempDir::new().unwrap();
2551        let released = released_before_the_version_file(dir.path());
2552        let found = tagged_commit(
2553            dir.path(),
2554            &dir.path().join("VERSION"),
2555            &released,
2556            &version_file,
2557        )
2558        .unwrap();
2559        assert_eq!(
2560            found,
2561            Some(VersionCommit {
2562                sha: released,
2563                depth: 1,
2564            })
2565        );
2566    }
2567
2568    #[test]
2569    fn a_merged_tag_on_a_commit_before_the_version_file_existed_is_the_release() {
2570        let dir = tempfile::TempDir::new().unwrap();
2571        let released = released_beside_the_version_file(dir.path());
2572        keep_merged(dir.path(), &released);
2573        let found = tagged_commit(
2574            dir.path(),
2575            &dir.path().join("VERSION"),
2576            &released,
2577            &version_file,
2578        )
2579        .unwrap();
2580        assert_eq!(
2581            found,
2582            Some(VersionCommit {
2583                sha: released,
2584                depth: 0,
2585            })
2586        );
2587    }
2588
2589    #[test]
2590    fn an_unreached_tag_before_the_version_file_existed_is_not_the_release() {
2591        let dir = tempfile::TempDir::new().unwrap();
2592        let released = released_beside_the_version_file(dir.path());
2593        let found = tagged_commit(
2594            dir.path(),
2595            &dir.path().join("VERSION"),
2596            &released,
2597            &version_file,
2598        )
2599        .unwrap();
2600        assert_eq!(found, None);
2601    }
2602
2603    #[test]
2604    fn a_tag_on_a_commit_with_a_directory_at_the_version_path_is_not_the_release() {
2605        let dir = tempfile::TempDir::new().unwrap();
2606        init(dir.path());
2607        fs::create_dir(dir.path().join("VERSION")).unwrap();
2608        fs::write(dir.path().join("VERSION").join("README"), "a directory\n").unwrap();
2609        let tagged = commit_all(dir.path(), "chore: a directory at the path");
2610        fs::remove_dir_all(dir.path().join("VERSION")).unwrap();
2611        fs::write(dir.path().join("VERSION"), "0.0.16\n").unwrap();
2612        commit_all(dir.path(), "chore: version the app through a VERSION file");
2613        let found = tagged_commit(
2614            dir.path(),
2615            &dir.path().join("VERSION"),
2616            &tagged,
2617            &version_file,
2618        )
2619        .unwrap();
2620        assert_eq!(found, None);
2621    }
2622
2623    /// A history in the shape a forkctl append publish leaves. `set` starts at
2624    /// `0.0.1`, and `published` follows it with a workflow change. Then the
2625    /// branch is rewritten from `set` and merged back with `published` as the
2626    /// second parent, keeping the rewritten tree. `published_version` is the
2627    /// version
2628    /// `published` carries. Returns `published`.
2629    fn rewritten_and_merged_back(dir: &Path, published_version: &str) -> String {
2630        init(dir);
2631        write_version(dir, "0.0.1");
2632        fs::write(dir.join("publish.yml"), "one\n").unwrap();
2633        let set = commit_all(dir, "chore: start");
2634        write_version(dir, published_version);
2635        fs::write(dir.join("publish.yml"), "two\n").unwrap();
2636        let published = commit_all(dir, "ci: publish");
2637        git(dir, &["checkout", "-q", "--detach", &set]);
2638        fs::write(dir.join("publish.yml"), "three\n").unwrap();
2639        commit_all(dir, "ci: rewritten publish");
2640        keep_merged(dir, &published);
2641        published
2642    }
2643
2644    #[test]
2645    fn a_tag_on_a_merged_commit_at_the_same_version_is_the_release() {
2646        let dir = tempfile::TempDir::new().unwrap();
2647        let published = rewritten_and_merged_back(dir.path(), "0.0.1");
2648        assert_ne!(
2649            git(dir.path(), &["rev-parse", "HEAD^1:publish.yml"]),
2650            git(
2651                dir.path(),
2652                &["rev-parse", &format!("{published}:publish.yml")]
2653            ),
2654            "the first-parent commit at the same version changes another file"
2655        );
2656        let found = tagged_commit(
2657            dir.path(),
2658            &dir.path().join("Cargo.toml"),
2659            &published,
2660            &version_line,
2661        )
2662        .unwrap();
2663        assert_eq!(
2664            found,
2665            Some(VersionCommit {
2666                sha: published,
2667                depth: 0,
2668            })
2669        );
2670    }
2671
2672    #[test]
2673    fn a_tag_merged_several_commits_below_head_takes_the_depth_of_the_merge() {
2674        let dir = tempfile::TempDir::new().unwrap();
2675        let published = rewritten_and_merged_back(dir.path(), "0.0.1");
2676        for later in 1..=5 {
2677            fs::write(dir.path().join("README"), format!("later {later}\n")).unwrap();
2678            commit_all(dir.path(), &format!("docs: later {later}"));
2679        }
2680        let found = tagged_commit(
2681            dir.path(),
2682            &dir.path().join("Cargo.toml"),
2683            &published,
2684            &version_line,
2685        )
2686        .unwrap();
2687        assert_eq!(
2688            found,
2689            Some(VersionCommit {
2690                sha: published,
2691                depth: 5,
2692            })
2693        );
2694    }
2695
2696    #[test]
2697    fn a_tag_on_a_merged_commit_at_another_version_is_not_the_release() {
2698        let dir = tempfile::TempDir::new().unwrap();
2699        let published = rewritten_and_merged_back(dir.path(), "0.0.2");
2700        assert_eq!(
2701            tagged_commit(
2702                dir.path(),
2703                &dir.path().join("Cargo.toml"),
2704                &published,
2705                &version_line,
2706            )
2707            .unwrap(),
2708            None
2709        );
2710    }
2711
2712    #[test]
2713    fn a_tag_on_a_commit_head_does_not_contain_is_not_the_release() {
2714        let dir = tempfile::TempDir::new().unwrap();
2715        init(dir.path());
2716        write_version(dir.path(), "0.0.1");
2717        let set = commit_all(dir.path(), "chore: start");
2718        fs::write(dir.path().join("publish.yml"), "two\n").unwrap();
2719        let abandoned = commit_all(dir.path(), "ci: publish");
2720        git(dir.path(), &["checkout", "-q", "--detach", &set]);
2721        fs::write(dir.path().join("publish.yml"), "three\n").unwrap();
2722        commit_all(dir.path(), "ci: rewritten publish");
2723        assert_eq!(
2724            tagged_commit(
2725                dir.path(),
2726                &dir.path().join("Cargo.toml"),
2727                &abandoned,
2728                &version_line,
2729            )
2730            .unwrap(),
2731            None
2732        );
2733    }
2734
2735    #[test]
2736    fn file_at_reads_a_file_at_a_commit_and_nothing_before_it() {
2737        let dir = tempfile::TempDir::new().unwrap();
2738        init(dir.path());
2739        fs::write(dir.path().join("README"), "start\n").unwrap();
2740        let before = commit_all(dir.path(), "chore: start");
2741        fs::create_dir_all(dir.path().join(".ctl")).unwrap();
2742        fs::write(dir.path().join(".ctl/ver.yaml"), "packages: []\n").unwrap();
2743        let added = commit_all(dir.path(), "chore: add the config");
2744        fs::write(dir.path().join(".ctl/ver.yaml"), "packages: [later]\n").unwrap();
2745        commit_all(dir.path(), "chore: change the config");
2746        let path = Path::new(".ctl/ver.yaml");
2747        assert_eq!(
2748            file_at(dir.path(), &added, path).unwrap().as_deref(),
2749            Some("packages: []\n")
2750        );
2751        assert_eq!(file_at(dir.path(), &before, path).unwrap(), None);
2752    }
2753
2754    #[test]
2755    fn added_by_names_the_commit_that_added_the_file() {
2756        let dir = tempfile::TempDir::new().unwrap();
2757        init(dir.path());
2758        fs::write(dir.path().join("README"), "start\n").unwrap();
2759        commit_all(dir.path(), "chore: start");
2760        fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2761        let added = commit_all(dir.path(), "fix: the parser (#12)");
2762        fs::write(dir.path().join("README"), "later\n").unwrap();
2763        commit_all(dir.path(), "docs: later");
2764        assert_eq!(
2765            added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
2766            Some(AddedBy {
2767                sha: added,
2768                subject: "fix: the parser (#12)".into(),
2769            })
2770        );
2771    }
2772
2773    /// A fragment that reached HEAD through a merge commit names the commit
2774    /// that added it on the merged branch, instead of the merge.
2775    #[test]
2776    fn added_by_follows_a_merge_to_the_commit_that_added_the_file() {
2777        let dir = tempfile::TempDir::new().unwrap();
2778        init(dir.path());
2779        fs::write(dir.path().join("README"), "start\n").unwrap();
2780        let base = commit_all(dir.path(), "chore: start");
2781        fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2782        let side = commit_all(dir.path(), "fix: the parser (#12)");
2783        git(dir.path(), &["reset", "-q", "--hard", &base]);
2784        fs::write(dir.path().join("README"), "later\n").unwrap();
2785        let main = commit_all(dir.path(), "docs: later (#13)");
2786        fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2787        git(dir.path(), &["add", "-A"]);
2788        let tree = git(dir.path(), &["write-tree"]);
2789        let merge = git(
2790            dir.path(),
2791            &[
2792                "commit-tree",
2793                &tree,
2794                "-p",
2795                &main,
2796                "-p",
2797                &side,
2798                "-m",
2799                "feat: release next (#14)",
2800            ],
2801        );
2802        git(dir.path(), &["reset", "-q", "--hard", &merge]);
2803        assert_eq!(
2804            added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
2805            Some(AddedBy {
2806                sha: side,
2807                subject: "fix: the parser (#12)".into(),
2808            })
2809        );
2810    }
2811
2812    /// A merge titled with its pull request is named when the branch commit
2813    /// that added the file names none. Merge-commit repositories thus keep
2814    /// their pull request links.
2815    #[test]
2816    fn added_by_names_a_titled_merge_over_an_unnamed_branch_commit() {
2817        let dir = tempfile::TempDir::new().unwrap();
2818        init(dir.path());
2819        fs::write(dir.path().join("README"), "start\n").unwrap();
2820        let base = commit_all(dir.path(), "chore: start");
2821        fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2822        let side = commit_all(dir.path(), "wip");
2823        git(dir.path(), &["reset", "-q", "--hard", &base]);
2824        fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2825        git(dir.path(), &["add", "-A"]);
2826        let tree = git(dir.path(), &["write-tree"]);
2827        let merge = git(
2828            dir.path(),
2829            &[
2830                "commit-tree",
2831                &tree,
2832                "-p",
2833                &base,
2834                "-p",
2835                &side,
2836                "-m",
2837                "fix: the parser (#12)",
2838            ],
2839        );
2840        git(dir.path(), &["reset", "-q", "--hard", &merge]);
2841        assert_eq!(
2842            added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
2843            Some(AddedBy {
2844                sha: merge,
2845                subject: "fix: the parser (#12)".into(),
2846            })
2847        );
2848    }
2849
2850    /// A later pull request that only edits a fragment keeps the link to the
2851    /// one that added it. The walk follows the file, not its content, so an
2852    /// edit through a titled merge or a squash leaves the adding merge named.
2853    #[test]
2854    fn added_by_keeps_the_adding_pull_request_after_an_edit() {
2855        let dir = tempfile::TempDir::new().unwrap();
2856        init(dir.path());
2857        fs::write(dir.path().join("README"), "start\n").unwrap();
2858        let base = commit_all(dir.path(), "chore: start");
2859        fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2860        let side = commit_all(dir.path(), "wip");
2861        git(dir.path(), &["reset", "-q", "--hard", &base]);
2862        fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2863        git(dir.path(), &["add", "-A"]);
2864        let tree = git(dir.path(), &["write-tree"]);
2865        let added = git(
2866            dir.path(),
2867            &[
2868                "commit-tree",
2869                &tree,
2870                "-p",
2871                &base,
2872                "-p",
2873                &side,
2874                "-m",
2875                "fix: the parser (#12)",
2876            ],
2877        );
2878        git(dir.path(), &["reset", "-q", "--hard", &added]);
2879        fs::write(dir.path().join("fix.md"), "Fix, reworded.\n").unwrap();
2880        let edit = commit_all(dir.path(), "docs: reword the fix");
2881        git(dir.path(), &["reset", "-q", "--hard", &added]);
2882        fs::write(dir.path().join("fix.md"), "Fix, reworded.\n").unwrap();
2883        git(dir.path(), &["add", "-A"]);
2884        let tree = git(dir.path(), &["write-tree"]);
2885        let edited = git(
2886            dir.path(),
2887            &[
2888                "commit-tree",
2889                &tree,
2890                "-p",
2891                &added,
2892                "-p",
2893                &edit,
2894                "-m",
2895                "docs: reword the fix (#13)",
2896            ],
2897        );
2898        git(dir.path(), &["reset", "-q", "--hard", &edited]);
2899        fs::write(dir.path().join("fix.md"), "Fix, reworded again.\n").unwrap();
2900        commit_all(dir.path(), "docs: reword the fix again (#14)");
2901        assert_eq!(
2902            added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
2903            Some(AddedBy {
2904                sha: added,
2905                subject: "fix: the parser (#12)".into(),
2906            })
2907        );
2908    }
2909
2910    /// A shallow clone ends at a commit git reports as parentless. When the
2911    /// adding commit lies beyond it, naming the boundary would be wrong.
2912    #[test]
2913    fn added_by_names_nothing_past_a_shallow_boundary() {
2914        let dir = tempfile::TempDir::new().unwrap();
2915        init(dir.path());
2916        fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2917        commit_all(dir.path(), "fix: the parser (#12)");
2918        fs::write(dir.path().join("README"), "later\n").unwrap();
2919        let boundary = commit_all(dir.path(), "docs: later (#13)");
2920        fs::write(dir.path().join(".git/shallow"), format!("{boundary}\n")).unwrap();
2921        assert_eq!(
2922            git(dir.path(), &["rev-parse", "--is-shallow-repository"]),
2923            "true"
2924        );
2925        assert_eq!(
2926            added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
2927            None
2928        );
2929    }
2930
2931    #[test]
2932    fn origin_url_from_discovered_repo() {
2933        let dir = tempfile::TempDir::new().unwrap();
2934        init(dir.path());
2935        git(
2936            dir.path(),
2937            &[
2938                "remote",
2939                "add",
2940                "origin",
2941                "https://github.com/victor-software-house/verctl.git",
2942            ],
2943        );
2944        commit_all(dir.path(), "init");
2945        assert_eq!(
2946            origin_url(dir.path()).unwrap(),
2947            "https://github.com/victor-software-house/verctl.git"
2948        );
2949    }
2950
2951    #[test]
2952    fn empty_paths_do_not_switch_head() {
2953        let dir = tempfile::TempDir::new().unwrap();
2954        init(dir.path());
2955        commit_all(dir.path(), "init");
2956        let before = git(dir.path(), &["symbolic-ref", "HEAD"]);
2957        let repo_id = Repo {
2958            owner: "victor-software-house".into(),
2959            name: "verctl".into(),
2960        };
2961        let out = super::commit_branch_and_push(
2962            dir.path(),
2963            "verctl/release/main",
2964            "chore",
2965            "unused",
2966            &repo_id,
2967            &[],
2968        )
2969        .unwrap();
2970        assert_eq!(out, super::PushOutcome::Empty);
2971        assert_eq!(git(dir.path(), &["symbolic-ref", "HEAD"]), before);
2972    }
2973
2974    #[test]
2975    fn unexpected_dirty_fails_unless_globbed() {
2976        let dir = tempfile::TempDir::new().unwrap();
2977        init(dir.path());
2978        fs::write(
2979            dir.path().join("Cargo.toml"),
2980            indoc! {r#"
2981                [package]
2982                version = "1.0.0"
2983            "#},
2984        )
2985        .unwrap();
2986        commit_all(dir.path(), "init");
2987        fs::write(dir.path().join("secret.env"), "TOKEN=leak\n").unwrap();
2988        let allowed = [dir.path().join("Cargo.toml")];
2989        let err = super::assert_only_allowed(dir.path(), &allowed, &[], super::IgnoredFiles::Skip)
2990            .unwrap_err();
2991        assert!(format!("{err:#}").contains("secret.env"), "{err:#}");
2992        let staged = super::assert_only_allowed(
2993            dir.path(),
2994            &allowed,
2995            &["*.env".into()],
2996            super::IgnoredFiles::Skip,
2997        )
2998        .unwrap();
2999        assert_eq!(staged.len(), 1);
3000        assert!(staged[0].ends_with("secret.env"), "{staged:?}");
3001    }
3002
3003    #[test]
3004    fn stage_glob_collects_a_deleted_file() {
3005        let dir = tempfile::TempDir::new().unwrap();
3006        init(dir.path());
3007        fs::write(dir.path().join("Cargo.lock"), "old\n").unwrap();
3008        fs::write(
3009            dir.path().join("Cargo.toml"),
3010            indoc! {r#"
3011                [package]
3012                version = "1.0.0"
3013            "#},
3014        )
3015        .unwrap();
3016        commit_all(dir.path(), "init");
3017        fs::remove_file(dir.path().join("Cargo.lock")).unwrap();
3018        let staged = super::assert_only_allowed(
3019            dir.path(),
3020            &[dir.path().join("Cargo.toml")],
3021            &["Cargo.lock".into()],
3022            super::IgnoredFiles::Skip,
3023        )
3024        .unwrap();
3025        assert_eq!(staged.len(), 1);
3026        assert!(staged[0].ends_with("Cargo.lock"), "{staged:?}");
3027        assert!(!dir.path().join("Cargo.lock").exists());
3028    }
3029
3030    #[test]
3031    fn stage_glob_collects_files_under_a_tree_not_the_directory() {
3032        let dir = tempfile::TempDir::new().unwrap();
3033        init(dir.path());
3034        fs::write(
3035            dir.path().join("Cargo.toml"),
3036            indoc! {r#"
3037                [package]
3038                version = "1.0.0"
3039            "#},
3040        )
3041        .unwrap();
3042        commit_all(dir.path(), "init");
3043        fs::create_dir_all(dir.path().join("src")).unwrap();
3044        fs::write(dir.path().join("src/lib.rs"), "fn x() {}\n").unwrap();
3045        let staged = super::assert_only_allowed(
3046            dir.path(),
3047            &[dir.path().join("Cargo.toml")],
3048            &["src/**".into()],
3049            super::IgnoredFiles::Skip,
3050        )
3051        .unwrap();
3052        assert_eq!(staged.len(), 1);
3053        assert!(staged[0].ends_with("src/lib.rs"), "{staged:?}");
3054        assert!(!staged.iter().any(|path| path.ends_with("src")));
3055    }
3056
3057    #[test]
3058    fn ignored_workdir_paths_are_not_unexpected() {
3059        let dir = tempfile::TempDir::new().unwrap();
3060        init(dir.path());
3061        fs::write(dir.path().join(".gitignore"), "/target\n").unwrap();
3062        fs::write(
3063            dir.path().join("Cargo.toml"),
3064            indoc! {r#"
3065                [package]
3066                version = "1.0.0"
3067            "#},
3068        )
3069        .unwrap();
3070        commit_all(dir.path(), "init");
3071        fs::create_dir_all(dir.path().join("target/debug")).unwrap();
3072        fs::write(dir.path().join("target/debug/verctl"), "bin\n").unwrap();
3073        super::assert_only_allowed(
3074            dir.path(),
3075            &[dir.path().join("Cargo.toml")],
3076            &[],
3077            super::IgnoredFiles::Skip,
3078        )
3079        .unwrap();
3080    }
3081
3082    #[test]
3083    fn stage_ignored_opt_in_collects_gitignored_files() {
3084        let dir = tempfile::TempDir::new().unwrap();
3085        init(dir.path());
3086        fs::write(dir.path().join(".gitignore"), "/generated.rs\n").unwrap();
3087        fs::write(
3088            dir.path().join("Cargo.toml"),
3089            indoc! {r#"
3090                [package]
3091                version = "1.0.0"
3092            "#},
3093        )
3094        .unwrap();
3095        commit_all(dir.path(), "init");
3096        fs::write(dir.path().join("generated.rs"), "gen\n").unwrap();
3097        let allowed = [dir.path().join("Cargo.toml")];
3098        let off = super::assert_only_allowed(
3099            dir.path(),
3100            &allowed,
3101            &["generated.rs".into()],
3102            super::IgnoredFiles::Skip,
3103        )
3104        .unwrap();
3105        assert!(off.is_empty(), "{off:?}");
3106        let on = super::assert_only_allowed(
3107            dir.path(),
3108            &allowed,
3109            &["generated.rs".into()],
3110            super::IgnoredFiles::Include,
3111        )
3112        .unwrap();
3113        assert_eq!(on.len(), 1);
3114        assert!(on[0].ends_with("generated.rs"), "{on:?}");
3115    }
3116
3117    #[test]
3118    fn stage_ignored_recurses_a_gitignored_directory() {
3119        let dir = tempfile::TempDir::new().unwrap();
3120        init(dir.path());
3121        fs::write(dir.path().join(".gitignore"), "/dist\n").unwrap();
3122        fs::write(
3123            dir.path().join("Cargo.toml"),
3124            indoc! {r#"
3125                [package]
3126                version = "1.0.0"
3127            "#},
3128        )
3129        .unwrap();
3130        commit_all(dir.path(), "init");
3131        fs::create_dir_all(dir.path().join("dist")).unwrap();
3132        fs::write(dir.path().join("dist/out.js"), "ok\n").unwrap();
3133        let allowed = [dir.path().join("Cargo.toml")];
3134        let staged = super::assert_only_allowed(
3135            dir.path(),
3136            &allowed,
3137            &["dist/**".into()],
3138            super::IgnoredFiles::Include,
3139        )
3140        .unwrap();
3141        assert_eq!(staged.len(), 1);
3142        assert!(staged[0].ends_with("dist/out.js"), "{staged:?}");
3143    }
3144
3145    #[test]
3146    fn stage_ignored_pathspec_does_not_collect_other_ignored_trees() {
3147        let dir = tempfile::TempDir::new().unwrap();
3148        init(dir.path());
3149        fs::write(dir.path().join(".gitignore"), "/dist\n/target\n").unwrap();
3150        fs::write(
3151            dir.path().join("Cargo.toml"),
3152            indoc! {r#"
3153                [package]
3154                version = "1.0.0"
3155            "#},
3156        )
3157        .unwrap();
3158        commit_all(dir.path(), "init");
3159        fs::create_dir_all(dir.path().join("dist")).unwrap();
3160        fs::write(dir.path().join("dist/out.js"), "ok\n").unwrap();
3161        fs::create_dir_all(dir.path().join("target/debug")).unwrap();
3162        fs::write(dir.path().join("target/debug/verctl"), "bin\n").unwrap();
3163        fs::write(dir.path().join("target/CACHEDIR.TAG"), "tag\n").unwrap();
3164        let staged = super::assert_only_allowed(
3165            dir.path(),
3166            &[dir.path().join("Cargo.toml")],
3167            &["dist/**".into()],
3168            super::IgnoredFiles::Include,
3169        )
3170        .unwrap();
3171        assert_eq!(staged.len(), 1, "{staged:?}");
3172        assert!(staged[0].ends_with("dist/out.js"), "{staged:?}");
3173        assert!(
3174            !staged
3175                .iter()
3176                .any(|path| path.to_string_lossy().contains("target")),
3177            "{staged:?}"
3178        );
3179    }
3180
3181    #[test]
3182    fn write_commit_on_branch_removes_a_deleted_staged_path() {
3183        let dir = tempfile::TempDir::new().unwrap();
3184        init(dir.path());
3185        fs::write(dir.path().join("Cargo.lock"), "old\n").unwrap();
3186        fs::write(
3187            dir.path().join("Cargo.toml"),
3188            indoc! {r#"
3189                [package]
3190                version = "1.0.0"
3191            "#},
3192        )
3193        .unwrap();
3194        commit_all(dir.path(), "init");
3195        fs::remove_file(dir.path().join("Cargo.lock")).unwrap();
3196        let staged = super::assert_only_allowed(
3197            dir.path(),
3198            &[dir.path().join("Cargo.toml")],
3199            &["Cargo.lock".into()],
3200            super::IgnoredFiles::Skip,
3201        )
3202        .unwrap();
3203        let oid = write_commit(dir.path(), &staged).expect("deletion should commit");
3204        let names = tree_names(dir.path(), &oid);
3205        assert!(!names.iter().any(|name| name == "Cargo.lock"), "{names:?}");
3206        assert!(names.iter().any(|name| name == "Cargo.toml"), "{names:?}");
3207    }
3208
3209    #[test]
3210    fn commit_only_lists_given_paths() {
3211        let dir = tempfile::TempDir::new().unwrap();
3212        init(dir.path());
3213        fs::write(
3214            dir.path().join("Cargo.toml"),
3215            indoc! {r#"
3216                [package]
3217                version = "1.0.0"
3218            "#},
3219        )
3220        .unwrap();
3221        let parent = commit_all(dir.path(), "init");
3222        fs::write(
3223            dir.path().join("Cargo.toml"),
3224            indoc! {r#"
3225                [package]
3226                version = "1.0.1"
3227            "#},
3228        )
3229        .unwrap();
3230        fs::write(
3231            dir.path().join("secret.env"),
3232            indoc! {"
3233                TOKEN=leak
3234            "},
3235        )
3236        .unwrap();
3237        let oid = write_commit(dir.path(), &[dir.path().join("Cargo.toml")]).expect("commit");
3238        let names = tree_names(dir.path(), &oid);
3239        assert!(names.iter().any(|name| name == "Cargo.toml"), "{names:?}");
3240        assert!(!names.iter().any(|name| name == "secret.env"), "{names:?}");
3241        assert_eq!(git(dir.path(), &["rev-parse", "HEAD"]), parent);
3242    }
3243
3244    #[test]
3245    fn dotted_relative_paths_stage() {
3246        let dir = tempfile::TempDir::new().unwrap();
3247        init(dir.path());
3248        fs::write(
3249            dir.path().join("Cargo.toml"),
3250            indoc! {r#"
3251                [package]
3252                version = "1.0.0"
3253            "#},
3254        )
3255        .unwrap();
3256        commit_all(dir.path(), "init");
3257        fs::write(
3258            dir.path().join("Cargo.toml"),
3259            indoc! {r#"
3260                [package]
3261                version = "1.0.1"
3262            "#},
3263        )
3264        .unwrap();
3265        let oid =
3266            write_commit(dir.path(), &[Path::new("./Cargo.toml").to_path_buf()]).expect("commit");
3267        let names = tree_names(dir.path(), &oid);
3268        assert!(names.iter().any(|name| name == "Cargo.toml"), "{names:?}");
3269    }
3270
3271    /// The push's credential helper hands the server `x-access-token` and the
3272    /// token, and a rejected push reports an error without the token.
3273    #[tokio::test]
3274    async fn push_keeps_the_token_out_of_the_error() {
3275        let server = wiremock::MockServer::start().await;
3276        wiremock::Mock::given(matchers::any())
3277            .respond_with(
3278                wiremock::ResponseTemplate::new(401)
3279                    .insert_header("WWW-Authenticate", r#"Basic realm="git""#),
3280            )
3281            .mount(&server)
3282            .await;
3283        let (dir, _) = fixture();
3284        git(dir.path(), &["branch", "verctl/release/main"]);
3285        let url = format!("{}/owner/repo.git", server.uri());
3286        let token = "verctl-push-token-5f3a9c";
3287        let error = task::spawn_blocking(move || {
3288            super::push(&dir.path().join(".git"), &url, "verctl/release/main", token)
3289        })
3290        .await
3291        .unwrap()
3292        .unwrap_err();
3293        let message = format!("{error:#}");
3294        assert!(!message.contains(token), "{message}");
3295        let expected = format!("Basic {}", base64(&format!("x-access-token:{token}")));
3296        let requests = server.received_requests().await.unwrap();
3297        assert!(
3298            requests.iter().any(|request| {
3299                request
3300                    .headers
3301                    .get("authorization")
3302                    .is_some_and(|value| value.as_bytes() == expected.as_bytes())
3303            }),
3304            "no request carried the token as Basic credentials"
3305        );
3306    }
3307
3308    /// Standard base64 with padding, enough to spell an HTTP Basic header.
3309    fn base64(text: &str) -> String {
3310        const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3311        let mut out = String::new();
3312        for chunk in text.as_bytes().chunks(3) {
3313            let bytes = [
3314                chunk[0],
3315                chunk.get(1).copied().unwrap_or(0),
3316                chunk.get(2).copied().unwrap_or(0),
3317            ];
3318            let joined = u32::from(bytes[0]) << 16 | u32::from(bytes[1]) << 8 | u32::from(bytes[2]);
3319            for index in 0..4 {
3320                if index <= chunk.len() {
3321                    let sextet = (joined >> (18 - 6 * index)) & 0x3f;
3322                    out.push(char::from(ALPHABET[usize::try_from(sextet).unwrap()]));
3323                } else {
3324                    out.push('=');
3325                }
3326            }
3327        }
3328        out
3329    }
3330
3331    /// A file under a `text` attribute is stored with line feed (LF) endings,
3332    /// as `git add` stores it, whatever the working tree contains.
3333    #[test]
3334    fn the_commit_applies_clean_filters() {
3335        let dir = tempfile::TempDir::new().unwrap();
3336        init(dir.path());
3337        fs::write(dir.path().join(".gitattributes"), "*.md text\n").unwrap();
3338        fs::write(dir.path().join("CHANGELOG.md"), "old\n").unwrap();
3339        commit_all(dir.path(), "init");
3340        fs::write(dir.path().join("CHANGELOG.md"), "a\r\nb\r\n").unwrap();
3341        let oid = write_commit(dir.path(), &[dir.path().join("CHANGELOG.md")]).expect("commit");
3342        let blob = format!("{oid}:CHANGELOG.md");
3343        assert_eq!(git(dir.path(), &["cat-file", "-p", &blob]), "a\nb");
3344    }
3345
3346    /// A configured `user.name` and `user.email` sign the Version PR commit
3347    /// and its reflog entry; the fallback identity fills in only when git
3348    /// config names none.
3349    #[test]
3350    fn a_configured_identity_wins_over_the_fallback() {
3351        let dir = tempfile::TempDir::new().unwrap();
3352        init(dir.path());
3353        git(dir.path(), &["config", "user.name", "Configured Name"]);
3354        git(
3355            dir.path(),
3356            &["config", "user.email", "configured@example.com"],
3357        );
3358        fs::write(dir.path().join("Cargo.toml"), "version = 1\n").unwrap();
3359        commit_all(dir.path(), "init");
3360        fs::write(dir.path().join("Cargo.toml"), "version = 2\n").unwrap();
3361        let oid = write_commit(dir.path(), &[dir.path().join("Cargo.toml")]).expect("commit");
3362        let configured = "Configured Name <configured@example.com>";
3363        assert_eq!(
3364            git(
3365                dir.path(),
3366                &["log", "-1", "--format=%an <%ae>|%cn <%ce>", &oid]
3367            ),
3368            format!("{configured}|{configured}")
3369        );
3370        assert_eq!(
3371            git(
3372                dir.path(),
3373                &[
3374                    "log",
3375                    "-g",
3376                    "-1",
3377                    "--format=%gn <%ge>",
3378                    "refs/heads/verctl/release/main",
3379                ],
3380            ),
3381            configured
3382        );
3383    }
3384
3385    /// `version --pr` runs from the repository root and finds it as `.`, and
3386    /// gix then reports `.` as the workdir, which no path strips. The commit
3387    /// resolves the workdir absolute first. The test binary runs in this
3388    /// crate's checkout, which is that root.
3389    #[test]
3390    fn a_workdir_found_from_dot_resolves_paths() {
3391        let repo = super::discover(Path::new(".")).unwrap();
3392        let workdir = super::absolute_workdir(&repo).unwrap();
3393        assert!(workdir.is_absolute(), "{}", workdir.display());
3394        assert_eq!(
3395            super::workdir_rel(&workdir, Path::new("./Cargo.toml")).unwrap(),
3396            Path::new("Cargo.toml")
3397        );
3398    }
3399
3400    /// A checkout reached through a symlink has a workdir spelled through the
3401    /// link, while the dirty-path check returns canonical paths; both resolve.
3402    #[cfg(unix)]
3403    #[test]
3404    fn a_symlinked_workdir_takes_canonical_paths() {
3405        let dir = tempfile::TempDir::new().unwrap();
3406        init(dir.path());
3407        fs::write(dir.path().join("Cargo.toml"), "version = 1\n").unwrap();
3408        commit_all(dir.path(), "init");
3409        fs::write(dir.path().join("Cargo.toml"), "version = 2\n").unwrap();
3410        let links = tempfile::TempDir::new().unwrap();
3411        let link = links.path().join("checkout");
3412        symlink(dir.path(), &link).unwrap();
3413        let canonical = dir.path().canonicalize().unwrap().join("Cargo.toml");
3414        let workdir = super::absolute_workdir(&super::discover(&link).unwrap()).unwrap();
3415        assert_eq!(
3416            super::workdir_rel(&workdir, &canonical).unwrap(),
3417            Path::new("Cargo.toml")
3418        );
3419        assert_eq!(
3420            super::workdir_rel(&workdir, &link.join("Cargo.toml")).unwrap(),
3421            Path::new("Cargo.toml")
3422        );
3423    }
3424
3425    /// Writes the Version PR commit of `paths` the way `commit_branch_and_push`
3426    /// does, and returns its SHA.
3427    fn write_commit(dir: &Path, paths: &[PathBuf]) -> Option<String> {
3428        let repo = super::discover(dir).unwrap();
3429        let workdir = super::absolute_workdir(&repo).unwrap();
3430        let parent = repo.head_commit().unwrap();
3431        super::write_commit_on_branch(
3432            &repo,
3433            &workdir,
3434            &parent,
3435            "verctl/release/main",
3436            "chore",
3437            paths,
3438        )
3439        .unwrap()
3440        .map(|id| id.to_string())
3441    }
3442
3443    fn stock() -> Vec<String> {
3444        super::candidate_names(None)
3445    }
3446
3447    fn fixture() -> (tempfile::TempDir, String) {
3448        let dir = tempfile::TempDir::new().unwrap();
3449        init(dir.path());
3450        let sha = commit_all(dir.path(), "init");
3451        (dir, sha)
3452    }
3453
3454    fn add_origin(dir: &Path) {
3455        git(
3456            dir,
3457            &[
3458                "remote",
3459                "add",
3460                "origin",
3461                "https://github.com/victor-software-house/verctl.git",
3462            ],
3463        );
3464    }
3465
3466    fn track(dir: &Path, name: &str, sha: &str) {
3467        git(
3468            dir,
3469            &["update-ref", &format!("refs/remotes/origin/{name}"), sha],
3470        );
3471    }
3472
3473    fn set_origin_head(dir: &Path, name: &str) {
3474        git(
3475            dir,
3476            &[
3477                "symbolic-ref",
3478                "refs/remotes/origin/HEAD",
3479                &format!("refs/remotes/origin/{name}"),
3480            ],
3481        );
3482    }
3483
3484    /// The proof as a pass or a failure: being off the branch fails too.
3485    fn prove(root: &Path, candidates: &[String]) -> anyhow::Result<()> {
3486        match super::prove_default_history(root, candidates)? {
3487            None => Ok(()),
3488            Some(off) => anyhow::bail!(off),
3489        }
3490    }
3491
3492    #[test]
3493    fn candidate_names_are_base_ref_then_main_master() {
3494        assert_eq!(super::candidate_names(None), ["main", "master"]);
3495        assert_eq!(super::candidate_names(Some("")), ["main", "master"]);
3496        assert_eq!(super::candidate_names(Some("   ")), ["main", "master"]);
3497        assert_eq!(
3498            super::candidate_names(Some("trunk")),
3499            ["trunk", "main", "master"]
3500        );
3501        assert_eq!(super::candidate_names(Some("main")), ["main", "master"]);
3502        assert_eq!(
3503            super::candidate_names(Some("release/1.0")),
3504            ["release/1.0", "main", "master"]
3505        );
3506    }
3507
3508    #[test]
3509    fn no_repository_refuses() {
3510        let dir = tempfile::TempDir::new().unwrap();
3511        let err = prove(dir.path(), &stock()).unwrap_err();
3512        assert!(
3513            format!("{err:#}").contains("release cannot prove HEAD"),
3514            "{err:#}"
3515        );
3516        assert!(format!("{err:#}").contains("no git repository"), "{err:#}");
3517    }
3518
3519    #[test]
3520    fn no_head_commit_refuses() {
3521        let dir = tempfile::TempDir::new().unwrap();
3522        init(dir.path());
3523        let err = prove(dir.path(), &stock()).unwrap_err();
3524        assert!(format!("{err:#}").contains("HEAD has no commit"), "{err:#}");
3525    }
3526
3527    #[test]
3528    fn a_missing_origin_refuses() {
3529        let (dir, _) = fixture();
3530        let err = prove(dir.path(), &stock()).unwrap_err();
3531        assert!(format!("{err:#}").contains("no `origin` remote"), "{err:#}");
3532    }
3533
3534    #[test]
3535    fn head_on_origin_main_is_ok() {
3536        let (dir, sha) = fixture();
3537        add_origin(dir.path());
3538        track(dir.path(), "main", &sha);
3539        prove(dir.path(), &stock()).unwrap();
3540    }
3541
3542    #[test]
3543    fn head_sha_is_the_peeled_head_commit() {
3544        let (dir, sha) = fixture();
3545        assert_eq!(super::head_sha(dir.path()).unwrap(), sha);
3546    }
3547
3548    #[test]
3549    fn origin_master_without_head_is_ok() {
3550        let (dir, sha) = fixture();
3551        add_origin(dir.path());
3552        track(dir.path(), "master", &sha);
3553        prove(dir.path(), &stock()).unwrap();
3554    }
3555
3556    #[test]
3557    fn origin_head_to_non_main_is_ok() {
3558        let (dir, sha) = fixture();
3559        add_origin(dir.path());
3560        track(dir.path(), "trunk", &sha);
3561        set_origin_head(dir.path(), "trunk");
3562        prove(dir.path(), &stock()).unwrap();
3563    }
3564
3565    #[test]
3566    fn base_ref_trunk_without_origin_head_is_ok() {
3567        let (dir, sha) = fixture();
3568        add_origin(dir.path());
3569        track(dir.path(), "trunk", &sha);
3570        prove(dir.path(), &super::candidate_names(Some("trunk"))).unwrap();
3571    }
3572
3573    #[test]
3574    fn origin_without_default_tracking_ref_fails() {
3575        let (dir, _) = fixture();
3576        add_origin(dir.path());
3577        let err = prove(dir.path(), &stock()).unwrap_err();
3578        assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
3579    }
3580
3581    #[test]
3582    fn origin_trunk_alone_needs_head_or_base_ref() {
3583        let (dir, sha) = fixture();
3584        add_origin(dir.path());
3585        track(dir.path(), "trunk", &sha);
3586        let err = prove(dir.path(), &stock()).unwrap_err();
3587        assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
3588        prove(dir.path(), &super::candidate_names(Some("trunk"))).unwrap();
3589        set_origin_head(dir.path(), "trunk");
3590        prove(dir.path(), &stock()).unwrap();
3591    }
3592
3593    #[test]
3594    fn origin_hotfix_alone_is_not_the_default() {
3595        let (dir, sha) = fixture();
3596        add_origin(dir.path());
3597        track(dir.path(), "hotfix", &sha);
3598        let err = prove(dir.path(), &stock()).unwrap_err();
3599        assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
3600    }
3601
3602    #[test]
3603    fn unpeelable_origin_head_does_not_fall_through_to_main() {
3604        let (dir, sha) = fixture();
3605        add_origin(dir.path());
3606        track(dir.path(), "main", &sha);
3607        set_origin_head(dir.path(), "trunk");
3608        let err = prove(dir.path(), &stock()).unwrap_err();
3609        assert!(format!("{err:#}").contains("origin/trunk"), "{err:#}");
3610    }
3611
3612    #[test]
3613    fn github_https_url_has_no_credentials() {
3614        let url = super::github_https_url("victor-software-house/qctl");
3615        assert_eq!(url, "https://github.com/victor-software-house/qctl.git");
3616        let lower = url.to_ascii_lowercase();
3617        assert!(!lower.contains("bearer"), "{url}");
3618        assert!(!lower.contains("token"), "{url}");
3619        assert!(!lower.contains("x-access-token"), "{url}");
3620    }
3621
3622    #[test]
3623    fn github_git_user_is_x_access_token() {
3624        assert_eq!(super::github_git_user(), "x-access-token");
3625    }
3626
3627    #[test]
3628    fn ensure_origin_head_skips_fetch_when_the_ref_exists() {
3629        let (dir, sha) = fixture();
3630        git(
3631            dir.path(),
3632            &["remote", "add", "origin", "https://127.0.0.1:1/nope.git"],
3633        );
3634        track(dir.path(), "main", &sha);
3635        super::ensure_origin_head(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3636        assert_eq!(
3637            git(dir.path(), &["symbolic-ref", "refs/remotes/origin/HEAD"]),
3638            "refs/remotes/origin/main"
3639        );
3640    }
3641
3642    #[test]
3643    fn ensure_origin_head_fetches_a_missing_ref_from_origin() {
3644        let upstream_dir = tempfile::TempDir::new().unwrap();
3645        init(upstream_dir.path());
3646        commit_all(upstream_dir.path(), "init");
3647
3648        let work_dir = tempfile::TempDir::new().unwrap();
3649        init(work_dir.path());
3650        commit_all(work_dir.path(), "local");
3651        let url = format!("file://{}", upstream_dir.path().display());
3652        git(work_dir.path(), &["remote", "add", "origin", &url]);
3653
3654        super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3655        git(
3656            work_dir.path(),
3657            &["rev-parse", "--verify", "refs/remotes/origin/main^{commit}"],
3658        );
3659        assert_eq!(
3660            git(
3661                work_dir.path(),
3662                &["symbolic-ref", "refs/remotes/origin/HEAD"]
3663            ),
3664            "refs/remotes/origin/main"
3665        );
3666    }
3667
3668    #[test]
3669    fn a_shallow_clone_gets_the_history_that_holds_the_tagged_commit() {
3670        let upstream = tempfile::TempDir::new().unwrap();
3671        init(upstream.path());
3672        write_version(upstream.path(), "0.0.1");
3673        commit_all(upstream.path(), "chore: start");
3674        write_version(upstream.path(), "0.0.2");
3675        let set = commit_all(upstream.path(), "chore(release): version packages");
3676        fs::write(upstream.path().join("README"), "later\n").unwrap();
3677        commit_all(upstream.path(), "docs: later");
3678
3679        let parent = tempfile::TempDir::new().unwrap();
3680        let url = format!("file://{}", upstream.path().display());
3681        git(
3682            parent.path(),
3683            &["clone", "-q", "--depth", "1", &url, "work"],
3684        );
3685        let work = parent.path().join("work");
3686        let manifest = work.join("Cargo.toml");
3687        let error = tagged_commit(&work, &manifest, &set, &version_line).unwrap_err();
3688        assert!(format!("{error:#}").contains("shallow"), "{error:#}");
3689
3690        super::ensure_full_history(&work, "main", &super::FetchDefault::Origin).unwrap();
3691        let found = tagged_commit(&work, &manifest, &set, &version_line).unwrap();
3692        assert_eq!(found, Some(VersionCommit { sha: set, depth: 1 }));
3693    }
3694
3695    #[test]
3696    fn a_full_clone_is_not_fetched_again() {
3697        let dir = tempfile::TempDir::new().unwrap();
3698        init(dir.path());
3699        commit_all(dir.path(), "init");
3700        // An origin that does not exist: a fetch would fail.
3701        git(
3702            dir.path(),
3703            &["remote", "add", "origin", "file:///nonexistent/verctl"],
3704        );
3705        super::ensure_full_history(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3706    }
3707
3708    /// The `actions/checkout` pull request case: a depth-1 fetch of
3709    /// `refs/pull/1/merge`, no `origin/main`, and `main` moved on since the
3710    /// merge ref was made. The merge-base is therefore HEAD's first parent,
3711    /// instead of the tip.
3712    #[test]
3713    fn a_pull_request_merge_checkout_compares_against_its_merge_base() {
3714        let upstream = tempfile::TempDir::new().unwrap();
3715        let up = upstream.path();
3716        init(up);
3717        write_version(up, "0.0.1");
3718        commit_all(up, "chore: start");
3719        write_version(up, "0.0.2");
3720        commit_all(up, "chore(release): version packages");
3721        git(up, &["checkout", "-q", "-b", "pr"]);
3722        fs::write(up.join("README"), "change\n").unwrap();
3723        commit_all(up, "docs: change");
3724        git(up, &["checkout", "-q", "--detach", "main"]);
3725        git(
3726            up,
3727            &["merge", "-q", "--no-ff", "pr", "-m", "Merge pr into main"],
3728        );
3729        git(up, &["update-ref", "refs/pull/1/merge", "HEAD"]);
3730        git(up, &["checkout", "-q", "main"]);
3731        write_version(up, "0.0.3");
3732        commit_all(up, "chore(release): version packages");
3733
3734        let work = tempfile::TempDir::new().unwrap();
3735        let dir = work.path();
3736        init(dir);
3737        let url = format!("file://{}", up.display());
3738        git(dir, &["remote", "add", "origin", &url]);
3739        git(
3740            dir,
3741            &[
3742                "fetch",
3743                "-q",
3744                "--depth=1",
3745                "origin",
3746                "+refs/pull/1/merge:refs/remotes/pull/1/merge",
3747            ],
3748        );
3749        git(
3750            dir,
3751            &["checkout", "-q", "--detach", "refs/remotes/pull/1/merge"],
3752        );
3753        assert_eq!(git(dir, &["rev-parse", "--is-shallow-repository"]), "true");
3754
3755        let manifest = [Path::new("Cargo.toml")];
3756        let candidates = ["main".to_owned()];
3757        let error = super::files_on_merge_base(dir, &manifest, &candidates).unwrap_err();
3758        assert!(
3759            format!("{error:#}").contains("fetch the default branch"),
3760            "{error:#}"
3761        );
3762
3763        super::ensure_comparable(dir, "main", &super::FetchDefault::Origin).unwrap();
3764        let files = super::files_on_merge_base(dir, &manifest, &candidates).unwrap();
3765        let base = files[0].as_deref().expect("Cargo.toml at the merge-base");
3766        assert_eq!(version_line(base).as_deref(), Some("0.0.2"));
3767    }
3768
3769    #[test]
3770    fn release_candidates_put_the_event_default_after_the_configured_branch() {
3771        assert_eq!(
3772            super::release_candidate_names(None, Some("trunk"), Some("develop")),
3773            ["trunk", "main", "master", "develop"]
3774        );
3775        assert_eq!(
3776            super::release_candidate_names(Some("stable"), Some("trunk"), None),
3777            ["stable", "trunk", "main", "master"]
3778        );
3779        assert_eq!(
3780            super::release_candidate_names(None, Some("main"), Some("main")),
3781            ["main", "master"]
3782        );
3783        assert_eq!(
3784            super::release_candidate_names(None, None, Some("develop")),
3785            ["main", "master", "develop"]
3786        );
3787    }
3788
3789    #[test]
3790    fn a_full_clone_with_the_branch_is_not_fetched_for_a_comparison() {
3791        let (dir, sha) = fixture();
3792        // An origin that does not exist: a fetch would fail.
3793        git(
3794            dir.path(),
3795            &["remote", "add", "origin", "file:///nonexistent/verctl"],
3796        );
3797        track(dir.path(), "main", &sha);
3798        super::ensure_comparable(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3799    }
3800
3801    #[test]
3802    fn a_full_clone_without_the_branch_fetches_it_for_a_comparison() {
3803        let upstream = tempfile::TempDir::new().unwrap();
3804        init(upstream.path());
3805        let tip = commit_all(upstream.path(), "init");
3806
3807        let work = tempfile::TempDir::new().unwrap();
3808        init(work.path());
3809        commit_all(work.path(), "local");
3810        let url = format!("file://{}", upstream.path().display());
3811        git(work.path(), &["remote", "add", "origin", &url]);
3812
3813        super::ensure_comparable(work.path(), "main", &super::FetchDefault::Origin).unwrap();
3814        assert_eq!(
3815            git(work.path(), &["rev-parse", "refs/remotes/origin/main"]),
3816            tip
3817        );
3818    }
3819
3820    #[test]
3821    fn fetch_one_branch_does_not_set_depth() {
3822        let src = include_str!("lib.rs");
3823        let prod = src.split("#[cfg(test)]").next().expect("production");
3824        assert!(
3825            !prod.contains("opts.depth"),
3826            "a depth-limited fetch leaves the tip parentless so graph_descendant_of cannot prove ancestry"
3827        );
3828    }
3829
3830    #[test]
3831    fn configured_default_branch_is_only_verctl_default_branch() {
3832        let src = include_str!("lib.rs");
3833        let start = src
3834            .find("pub fn configured_default_branch")
3835            .expect("configured_default_branch");
3836        let rest = &src[start..];
3837        let end = rest
3838            .find("pub fn ensure_origin_head")
3839            .expect("ensure_origin_head");
3840        let body = &rest[..end];
3841        assert!(!body.contains("GITHUB_BASE_REF"), "{body}");
3842        assert!(!body.contains("env_base_ref"), "{body}");
3843    }
3844
3845    #[test]
3846    fn fetched_default_branch_keeps_parents_for_ancestry() {
3847        let upstream_dir = tempfile::TempDir::new().unwrap();
3848        init(upstream_dir.path());
3849        commit_all(upstream_dir.path(), "A");
3850
3851        let work_dir = tempfile::TempDir::new().unwrap();
3852        init(work_dir.path());
3853        let url = format!("file://{}", upstream_dir.path().display());
3854        git(work_dir.path(), &["remote", "add", "origin", &url]);
3855        super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3856        let first = git(work_dir.path(), &["rev-parse", "refs/remotes/origin/main"]);
3857        git(
3858            work_dir.path(),
3859            &["update-ref", "--no-deref", "HEAD", &first],
3860        );
3861
3862        fs::write(upstream_dir.path().join("b.txt"), "b\n").unwrap();
3863        commit_all(upstream_dir.path(), "B");
3864        fs::write(upstream_dir.path().join("c.txt"), "c\n").unwrap();
3865        commit_all(upstream_dir.path(), "C");
3866
3867        git(
3868            work_dir.path(),
3869            &["update-ref", "-d", "refs/remotes/origin/main"],
3870        );
3871        git(
3872            work_dir.path(),
3873            &["symbolic-ref", "--delete", "refs/remotes/origin/HEAD"],
3874        );
3875        super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3876        prove(work_dir.path(), &stock()).unwrap();
3877    }
3878
3879    #[test]
3880    fn origin_head_wins_over_main_when_they_differ() {
3881        let (dir, first) = fixture();
3882        add_origin(dir.path());
3883        fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
3884        let second = commit_all(dir.path(), "ahead");
3885        track(dir.path(), "main", &first);
3886        track(dir.path(), "trunk", &second);
3887        set_origin_head(dir.path(), "trunk");
3888        prove(dir.path(), &stock()).unwrap();
3889    }
3890
3891    /// Being off the branch is a finding instead of an error, and it names
3892    /// both commits.
3893    #[test]
3894    fn head_off_default_history_fails() {
3895        let (dir, first) = fixture();
3896        add_origin(dir.path());
3897        track(dir.path(), "main", &first);
3898        git(dir.path(), &["update-ref", "refs/heads/other", &first]);
3899        git(dir.path(), &["symbolic-ref", "HEAD", "refs/heads/other"]);
3900        fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
3901        let head = commit_all(dir.path(), "ahead");
3902        let off = super::prove_default_history(dir.path(), &stock())
3903            .unwrap()
3904            .unwrap();
3905        assert!(off.contains("not an ancestor"), "{off}");
3906        assert!(off.contains(&head), "{off}");
3907        assert!(off.contains(&first), "{off}");
3908    }
3909
3910    #[test]
3911    fn workflows_at_the_default_tip_match() {
3912        let (dir, _) = fixture();
3913        fs::create_dir_all(dir.path().join(".github/workflows")).unwrap();
3914        fs::write(dir.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
3915        let release = commit_all(dir.path(), "chore(release): version packages");
3916        fs::write(dir.path().join("README"), "later\n").unwrap();
3917        let tip = commit_all(dir.path(), "docs: later");
3918        add_origin(dir.path());
3919        track(dir.path(), "main", &tip);
3920        git(dir.path(), &["update-ref", "--no-deref", "HEAD", &release]);
3921        assert_eq!(super::workflows_differ(dir.path()).unwrap(), None);
3922    }
3923
3924    /// A workflow changed on the default branch after the release commit, and
3925    /// a repository with workflows on one side only, both differ.
3926    #[test]
3927    fn a_workflow_changed_since_the_release_commit_differs() {
3928        let (dir, _) = fixture();
3929        fs::create_dir_all(dir.path().join(".github/workflows")).unwrap();
3930        fs::write(dir.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
3931        let release = commit_all(dir.path(), "chore(release): version packages");
3932        fs::write(
3933            dir.path().join(".github/workflows/ci.yml"),
3934            "on: [push, pull_request]\n",
3935        )
3936        .unwrap();
3937        let tip = commit_all(dir.path(), "ci: run on pull requests");
3938        add_origin(dir.path());
3939        track(dir.path(), "main", &tip);
3940        git(dir.path(), &["update-ref", "--no-deref", "HEAD", &release]);
3941        let differs = super::workflows_differ(dir.path()).unwrap().unwrap();
3942        assert!(differs.contains(".github/workflows/"), "{differs}");
3943        assert!(differs.contains(&release), "{differs}");
3944        assert!(differs.contains(&tip), "{differs}");
3945
3946        let (bare, first) = fixture();
3947        add_origin(bare.path());
3948        fs::create_dir_all(bare.path().join(".github/workflows")).unwrap();
3949        fs::write(bare.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
3950        let added = commit_all(bare.path(), "ci: add");
3951        track(bare.path(), "main", &added);
3952        git(bare.path(), &["update-ref", "--no-deref", "HEAD", &first]);
3953        assert!(super::workflows_differ(bare.path()).unwrap().is_some());
3954    }
3955
3956    /// The publish job of a reusable workflow checks out the version commit,
3957    /// while Actions runs the workflows of `GITHUB_SHA`.
3958    /// So that commit's tree is the one compared when it names a commit, and
3959    /// HEAD's when it does not.
3960    #[test]
3961    fn the_workflows_compared_are_those_of_the_run_commit() {
3962        let (dir, _) = fixture();
3963        fs::create_dir_all(dir.path().join(".github/workflows")).unwrap();
3964        fs::write(dir.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
3965        let release = commit_all(dir.path(), "chore(release): version packages");
3966        fs::write(
3967            dir.path().join(".github/workflows/ci.yml"),
3968            "on: [push, pull_request]\n",
3969        )
3970        .unwrap();
3971        let tip = commit_all(dir.path(), "ci: run on pull requests");
3972        add_origin(dir.path());
3973        track(dir.path(), "main", &tip);
3974        git(dir.path(), &["update-ref", "--no-deref", "HEAD", &release]);
3975
3976        assert_eq!(
3977            super::workflows_differ_at(dir.path(), Some(&tip)).unwrap(),
3978            None
3979        );
3980
3981        let at_head = super::workflows_differ_at(dir.path(), Some(&"0".repeat(40)))
3982            .unwrap()
3983            .unwrap();
3984        assert!(at_head.contains(&format!("at HEAD {release}")), "{at_head}");
3985        let unset = super::workflows_differ_at(dir.path(), None)
3986            .unwrap()
3987            .unwrap();
3988        assert!(unset.contains(&format!("at HEAD {release}")), "{unset}");
3989
3990        let at_run = super::workflows_differ_at(dir.path(), Some(&release))
3991            .unwrap()
3992            .unwrap();
3993        assert!(
3994            at_run.contains(&format!("at GITHUB_SHA {release}")),
3995            "{at_run}"
3996        );
3997    }
3998
3999    #[test]
4000    fn head_behind_origin_main_is_ok() {
4001        let (dir, first) = fixture();
4002        add_origin(dir.path());
4003        fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
4004        let second = commit_all(dir.path(), "ahead");
4005        track(dir.path(), "main", &second);
4006        git(dir.path(), &["update-ref", "--no-deref", "HEAD", &first]);
4007        prove(dir.path(), &stock()).unwrap();
4008    }
4009
4010    #[test]
4011    fn extract_tag_tree_reads_local_annotated_tag_and_preserves_files() {
4012        let (dir, _) = fixture();
4013        fs::write(dir.path().join("Cargo.toml"), "version = \"0.1.0\"\n").unwrap();
4014        commit_all(dir.path(), "release 0.1.0");
4015        git(dir.path(), &["tag", "-a", "v0.1.0", "-m", "v0.1.0"]);
4016        fs::write(dir.path().join("Cargo.toml"), "version = \"0.1.1\"\n").unwrap();
4017        commit_all(dir.path(), "next");
4018
4019        let dest = tempfile::TempDir::new().unwrap();
4020        let extracted = super::extract_tag_tree(
4021            dir.path(),
4022            "v0.1.0",
4023            dest.path(),
4024            &super::FetchDefault::Origin,
4025        )
4026        .unwrap();
4027        assert_eq!(extracted, dest.path());
4028        assert_eq!(
4029            fs::read_to_string(extracted.join("Cargo.toml")).unwrap(),
4030            "version = \"0.1.0\"\n"
4031        );
4032    }
4033
4034    #[test]
4035    fn extract_tag_tree_fetches_missing_tag_in_shallow_clone() {
4036        let upstream = tempfile::TempDir::new().unwrap();
4037        init(upstream.path());
4038        fs::write(upstream.path().join("Cargo.toml"), "version = \"0.1.0\"\n").unwrap();
4039        commit_all(upstream.path(), "v0.1.0");
4040        git(upstream.path(), &["tag", "v0.1.0"]);
4041        fs::write(upstream.path().join("Cargo.toml"), "version = \"0.1.1\"\n").unwrap();
4042        commit_all(upstream.path(), "ahead");
4043
4044        let parent = tempfile::TempDir::new().unwrap();
4045        let url = format!("file://{}", upstream.path().display());
4046        git(
4047            parent.path(),
4048            &["clone", "-q", "--depth", "1", "--no-tags", &url, "work"],
4049        );
4050        let work = parent.path().join("work");
4051        let dest = tempfile::TempDir::new().unwrap();
4052        let extracted =
4053            super::extract_tag_tree(&work, "v0.1.0", dest.path(), &super::FetchDefault::Origin)
4054                .unwrap();
4055        assert_eq!(
4056            fs::read_to_string(extracted.join("Cargo.toml")).unwrap(),
4057            "version = \"0.1.0\"\n"
4058        );
4059    }
4060
4061    #[test]
4062    fn extract_tag_tree_fails_naming_missing_tag() {
4063        let (dir, _) = fixture();
4064        let dest = tempfile::TempDir::new().unwrap();
4065        let error = super::extract_tag_tree(
4066            dir.path(),
4067            "v9.9.9",
4068            dest.path(),
4069            &super::FetchDefault::Origin,
4070        )
4071        .unwrap_err();
4072        let message = format!("{error:#}");
4073        assert!(message.contains("v9.9.9"), "{message}");
4074    }
4075}