#[cfg(test)]
pub(crate) mod test_git;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::{File, Metadata, Permissions};
use std::io::{ErrorKind, Read};
use std::path::{Component, Path, PathBuf};
use std::sync::atomic::AtomicBool;
use std::time::Duration;
use std::{env, fmt, fs, path};
use anyhow::{Context, Result, anyhow, bail, ensure};
use gix::actor::Signature;
use gix::bstr::{BString, ByteSlice};
use gix::credentials::helper::Action;
use gix::credentials::protocol::Outcome;
use gix::date::Time;
use gix::dir::entry::Status;
use gix::dir::walk::EmissionMode;
use gix::filter::Pipeline;
use gix::index::State;
use gix::index::entry::Mode;
use gix::objs::Commit;
use gix::objs::tree::EntryKind;
use gix::progress::Discard;
use gix::refs::transaction::{PreviousValue, RefEdit};
use gix::refs::{FullName, Target};
use gix::remote::fetch::{Shallow, Tags};
use gix::remote::{Direction, ref_map};
use gix::sec::identity::Account;
use gix::sec::trust::{DefaultForLevel, Mapping};
use gix::sec::{Permission, Trust};
use gix::status::tree_index::TrackRenames;
use gix::status::{UntrackedFiles, index_worktree};
use gix::worktree::stack::state::ignore::Source;
use gix::{open, status};
use semver::Version;
use verctl_core::repo::Repo;
use verctl_core::{env as github_env, lookup, process};
#[must_use]
pub fn current_branch(root: &Path) -> Option<String> {
let repo = repo_covering(root)?;
repo.head_id().ok()?;
let name = repo.head_name().ok()??;
Some(name.shorten().to_string())
}
pub fn head_sha(root: &Path) -> Result<String> {
let repo = discover(root).context("release needs a git repository to name the tag")?;
let commit = repo
.head_commit()
.context("release needs HEAD to name the tag")?;
Ok(commit.id().to_string())
}
pub fn head_contains_commit(root: &Path, sha: &str) -> Result<bool> {
let repo = discover(root).context("checking commit ancestry needs a git repository")?;
let head = repo
.head_commit()
.context("checking commit ancestry needs HEAD")?
.id();
let target =
gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
if head == target {
return Ok(true);
}
if repo.find_commit(target).is_err() {
return Ok(false);
}
let base = repo.merge_base(head, target).with_context(|| {
format!("cannot tell whether HEAD contains commit {sha}; fetch the full history")
})?;
Ok(base.is_some_and(|base| base == target))
}
const NEED_FULL_FETCH: &str =
"cannot compare versions against the default branch (need a full fetch, not a shallow clone)";
pub fn files_on_merge_base(
root: &Path,
rels: &[&Path],
candidates: &[String],
) -> Result<Vec<Option<String>>> {
let Some(repo) = repo_covering(root) else {
return Ok(vec![None; rels.len()]);
};
let Some(upstream) = default_upstream_commit(&repo, candidates)? else {
return Ok(vec![None; rels.len()]);
};
let head = repo
.head_commit()
.context("cannot compare versions (need HEAD)")?;
let base = repo
.merge_base(head.id(), upstream)
.context(NEED_FULL_FETCH)?
.context(NEED_FULL_FETCH)?;
let tree = repo.find_commit(base)?.tree()?;
let workdir = repo.workdir().map(Path::to_path_buf);
Ok(rels
.iter()
.map(|rel| git_path(root, rel, workdir.as_deref()).and_then(|path| blob_at(&tree, &path)))
.collect())
}
fn git_path(root: &Path, rel: &Path, workdir: Option<&Path>) -> Option<PathBuf> {
let abs = if rel.is_absolute() {
rel.canonicalize().ok().or_else(|| {
rel.parent()?
.canonicalize()
.ok()
.map(|dir| dir.join(rel.file_name().unwrap_or_default()))
})?
} else {
let inside: PathBuf = rel
.components()
.filter(|part| !matches!(part, Component::CurDir))
.collect();
root.canonicalize().ok()?.join(inside)
};
let workdir = workdir?.canonicalize().ok()?;
abs.strip_prefix(workdir).ok().map(Path::to_path_buf)
}
#[derive(Debug)]
pub struct MergeBase {
repo: gix::Repository,
workdir: PathBuf,
files: BTreeMap<String, (gix::ObjectId, EntryKind)>,
changed: BTreeSet<String>,
}
impl MergeBase {
pub fn read(root: &Path, candidates: &[String]) -> Result<Option<Self>> {
let Some(repo) = repo_covering(root) else {
return Ok(None);
};
let Some(upstream) = default_upstream_commit(&repo, candidates)? else {
return Ok(None);
};
let (files, head_files) = {
let head = repo
.head_commit()
.context("cannot compare the Version PR (need HEAD)")?;
let base = repo
.merge_base(head.id(), upstream)
.context(NEED_FULL_FETCH)?
.context(NEED_FULL_FETCH)?;
(
files_of(&repo.find_commit(base)?.tree()?)?,
files_of(&head.tree()?)?,
)
};
let workdir = repo
.workdir()
.context("the Version PR check needs a working tree")?
.canonicalize()
.context("the working tree")?;
let mut candidates: BTreeSet<String> = files
.keys()
.chain(head_files.keys())
.filter(|path| files.get(*path) != head_files.get(*path))
.cloned()
.collect();
candidates.extend(
status_paths(&repo, Vec::new(), IgnoredFiles::Skip)
.context("git status")?
.into_iter()
.filter(|path| files.contains_key(path) || head_files.contains_key(path)),
);
let mut merge_base = Self {
repo,
workdir,
files,
changed: BTreeSet::new(),
};
for path in candidates {
if merge_base.differs(&path, head_files.get(&path))? {
merge_base.changed.insert(path);
}
}
Ok(Some(merge_base))
}
fn differs(&self, rel: &str, head: Option<&(gix::ObjectId, EntryKind)>) -> Result<bool> {
let base = self.files.get(rel);
let gitlink = |entry: Option<&(gix::ObjectId, EntryKind)>| {
entry.is_some_and(|(_, kind)| *kind == EntryKind::Commit)
};
if gitlink(base) || gitlink(head) {
return Ok(base != head);
}
let expected = match base {
None => Worktree::Missing,
Some((_, EntryKind::Link)) => Worktree::Link(self.base_bytes(rel)?.unwrap_or_default()),
Some(_) => Worktree::File(self.base_bytes(rel)?.unwrap_or_default()),
};
Ok(expected != Worktree::read(&self.workdir.join(rel))?)
}
#[must_use]
pub fn workdir(&self) -> &Path {
&self.workdir
}
#[must_use]
pub fn changed(&self) -> &BTreeSet<String> {
&self.changed
}
pub fn base_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
let Some((oid, _)) = self.files.get(rel) else {
return Ok(None);
};
let blob = self
.repo
.find_blob(*oid)
.with_context(|| format!("{rel} at the merge-base"))?;
Ok(Some(blob.data.clone()))
}
pub fn worktree_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
read_optional(&self.workdir.join(rel))
}
pub fn write_to(&self, dir: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt as _;
for (rel, (_, kind)) in &self.files {
let mode = match kind {
EntryKind::Blob => 0o644,
EntryKind::BlobExecutable => 0o755,
EntryKind::Link | EntryKind::Tree | EntryKind::Commit => continue,
};
let path = dir.join(rel);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("create {}", parent.display()))?;
}
let bytes = self.base_bytes(rel)?.unwrap_or_default();
fs::write(&path, bytes).with_context(|| format!("write {}", path.display()))?;
fs::set_permissions(&path, Permissions::from_mode(mode))
.with_context(|| format!("chmod {}", path.display()))?;
}
Ok(())
}
}
#[derive(Debug, PartialEq, Eq)]
enum Worktree {
Missing,
Link(Vec<u8>),
File(Vec<u8>),
}
impl Worktree {
fn read(path: &Path) -> Result<Self> {
use std::os::unix::ffi::OsStrExt as _;
let metadata = match fs::symlink_metadata(path) {
Ok(metadata) => metadata,
Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Self::Missing),
Err(error) => return Err(error).with_context(|| path.display().to_string()),
};
if metadata.file_type().is_symlink() {
let target = fs::read_link(path).with_context(|| path.display().to_string())?;
return Ok(Self::Link(target.as_os_str().as_bytes().to_vec()));
}
let bytes = fs::read(path).with_context(|| path.display().to_string())?;
Ok(Self::File(bytes))
}
}
pub fn read_optional(path: &Path) -> Result<Option<Vec<u8>>> {
match fs::read(path) {
Ok(bytes) => Ok(Some(bytes)),
Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
Err(error) => Err(error).with_context(|| path.display().to_string()),
}
}
fn files_of(tree: &gix::Tree<'_>) -> Result<BTreeMap<String, (gix::ObjectId, EntryKind)>> {
Ok(tree
.traverse()
.breadthfirst
.files()?
.into_iter()
.filter(|entry| !entry.mode.is_tree())
.map(|entry| {
(
entry.filepath.to_str_lossy().into_owned(),
(entry.oid, entry.mode.kind()),
)
})
.collect())
}
pub fn file_at(root: &Path, sha: &str, path: &Path) -> Result<Option<String>> {
let repo = discover(root).context("reading a file at a commit needs a git repository")?;
let rel = git_path(root, path, repo.workdir())
.with_context(|| format!("{} is not in the repository", path.display()))?;
let id = gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
let commit = repo
.find_commit(id)
.with_context(|| format!("commit {sha} is not in the repository"))?;
Ok(blob_at(&commit.tree()?, &rel))
}
fn blob_at(tree: &gix::Tree<'_>, rel: &Path) -> Option<String> {
let entry = tree.lookup_entry_by_path(rel).ok()??;
let blob = entry.object().ok()?.try_into_blob().ok()?;
Some(String::from_utf8_lossy(&blob.data).into_owned())
}
pub fn files_named_at(
root: &Path,
sha: &str,
dir: &Path,
file_name: &str,
) -> Result<Vec<(String, String)>> {
let repo = discover(root).context("reading files at a commit needs a git repository")?;
let dir = dir
.canonicalize()
.with_context(|| format!("resolve {}", dir.display()))?;
let dir_rel = git_path(root, &dir, repo.workdir())
.with_context(|| format!("{} is not in the repository", dir.display()))?;
let id = gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
let commit = repo
.find_commit(id)
.with_context(|| format!("commit {sha} is not in the repository"))?;
let mut found = Vec::new();
for (rel, (oid, kind)) in files_of(&commit.tree()?)? {
if !matches!(kind, EntryKind::Blob | EntryKind::BlobExecutable) {
continue;
}
let path = Path::new(&rel);
if path.file_name().and_then(|name| name.to_str()) != Some(file_name) {
continue;
}
let under_dir = if dir_rel.as_os_str().is_empty() {
path
} else if let Ok(stripped) = path.strip_prefix(&dir_rel) {
stripped
} else {
continue;
};
let blob = repo
.find_object(oid)
.with_context(|| format!("read {rel} at commit {sha}"))?
.try_into_blob()
.with_context(|| format!("{rel} at commit {sha} is not a blob"))?;
found.push((
under_dir.to_string_lossy().into_owned(),
String::from_utf8_lossy(&blob.data).into_owned(),
));
}
Ok(found)
}
pub fn default_tip(root: &Path, candidates: &[String]) -> Result<String> {
let repo = repo_covering(root).with_context(|| {
format!(
"cannot resolve the default branch: no git repository covers {}",
root.display()
)
})?;
let tip = default_upstream_commit(&repo, candidates)?.context(
"cannot resolve the default branch: there is no `origin` remote; add it and fetch the default branch",
)?;
Ok(tip.to_string())
}
pub fn origin_url(root: &Path) -> Result<String> {
let repo = discover(root).context("open git repository")?;
let remote = repo.find_remote("origin").context("git remote origin")?;
let url = remote.url(Direction::Fetch).context("origin has no URL")?;
Ok(url.to_bstring().to_str_lossy().into_owned())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AddedBy {
pub sha: String,
pub subject: String,
}
pub fn added_by(root: &Path, path: &Path) -> Result<Option<AddedBy>> {
let Ok(repo) = discover(root) else {
return Ok(None);
};
let Ok(head) = repo.head_commit() else {
return Ok(None);
};
added_from(&repo, root, path, head)
}
pub fn added_by_from(root: &Path, path: &Path, start: &str) -> Result<Option<AddedBy>> {
let Ok(repo) = discover(root) else {
return Ok(None);
};
let id =
gix::ObjectId::from_hex(start.as_bytes()).with_context(|| format!("commit {start}"))?;
let commit = repo
.find_commit(id)
.with_context(|| format!("commit {start} is not in the repository"))?;
added_from(&repo, root, path, commit)
}
fn added_from(
repo: &gix::Repository,
root: &Path,
path: &Path,
head: gix::Commit<'_>,
) -> Result<Option<AddedBy>> {
let Some(rel) = git_path(root, path, repo.workdir()) else {
return Ok(None);
};
if !has_path(&head, &rel)? {
return Ok(None);
}
let boundary: Vec<gix::ObjectId> = repo
.shallow_commits()?
.map_or_default(|commits| commits.iter().copied().collect());
let mut commit = head;
let mut named_merge = None;
loop {
let parents: Vec<gix::ObjectId> = if boundary.contains(&commit.id().detach()) {
Vec::new()
} else {
commit.parent_ids().map(gix::Id::detach).collect()
};
if parents.is_empty() && !boundary.is_empty() {
return Ok(None);
}
let mut holder = None;
for (index, id) in parents.into_iter().enumerate() {
let Ok(parent) = repo.find_commit(id) else {
return Ok(None);
};
if has_path(&parent, &rel)? {
holder = Some((index, parent));
break;
}
}
let added = named(&commit)?;
let Some((index, parent)) = holder else {
return Ok(Some(match named_merge {
Some(merge) if pull_request_number(&added.subject).is_none() => merge,
Some(_) | None => added,
}));
};
if index > 0 && pull_request_number(&added.subject).is_some() {
named_merge = Some(added);
}
commit = parent;
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Deleted {
pub path: PathBuf,
pub text: String,
pub parent: String,
}
pub fn candidate_deletions(
root: &Path,
manifest: &Path,
read: &dyn Fn(&str) -> Option<String>,
dir: &Path,
) -> Result<Vec<Deleted>> {
let repo = discover(root).context("reading earlier candidates needs a git repository")?;
let workdir = repo.workdir().map(Path::to_path_buf);
let manifest_rel = git_path(root, manifest, workdir.as_deref())
.with_context(|| format!("{} is not in the repository", manifest.display()))?;
let dir_rel = git_path(root, dir, workdir.as_deref())
.with_context(|| format!("{} is not in the repository", dir.display()))?;
let version_at = |commit: &gix::Commit<'_>| -> Result<Option<String>> {
Ok(blob_at(&commit.tree()?, &manifest_rel).and_then(|raw| read(&raw)))
};
let boundary: Vec<gix::ObjectId> = repo
.shallow_commits()?
.map_or_default(|commits| commits.iter().copied().collect());
let mut commit = repo
.head_commit()
.context("reading earlier candidates needs HEAD")?;
let mut deleted = Vec::new();
loop {
let version = version_at(&commit)?;
if boundary.contains(&commit.id().detach()) {
return Err(lookup::unavailable(anyhow!(
"cannot read the candidates before commit {}: the clone is shallow; fetch the full history{}",
commit.id(),
shallow_hint()
)));
}
let Some(parent) = commit.parent_ids().next() else {
break;
};
let parent = repo.find_commit(parent.detach())?;
if version_at(&parent)? != version {
if version.as_deref().is_some_and(stable) {
break;
}
let files = files_under(&parent, &dir_rel)?;
let kept = files_under(&commit, &dir_rel)?;
for (name, text) in files {
if !kept.contains_key(&name) {
deleted.push(Deleted {
path: dir.join(&name),
text,
parent: parent.id().to_string(),
});
}
}
}
commit = parent;
}
Ok(deleted)
}
fn stable(version: &str) -> bool {
Version::parse(version).is_ok_and(|version| version.pre.is_empty())
}
fn files_under(commit: &gix::Commit<'_>, dir: &Path) -> Result<BTreeMap<PathBuf, String>> {
let tree = commit.tree()?;
let Some(entry) = tree.lookup_entry_by_path(dir)? else {
return Ok(BTreeMap::new());
};
let Ok(subtree) = entry.object()?.try_into_tree() else {
return Ok(BTreeMap::new());
};
let mut files = BTreeMap::new();
for entry in subtree.iter() {
let entry = entry?;
if !entry.mode().is_blob() {
continue;
}
let blob = entry.object()?.try_into_blob()?;
files.insert(
PathBuf::from(entry.filename().to_str_lossy().as_ref()),
String::from_utf8_lossy(&blob.data).into_owned(),
);
}
Ok(files)
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct VersionCommit {
pub sha: String,
pub depth: usize,
}
impl VersionCommit {
#[must_use]
pub const fn new(sha: String, depth: usize) -> Self {
Self { sha, depth }
}
}
#[derive(Debug)]
enum PackageFile {
Missing,
Present(Option<String>),
}
fn package_file_at(
commit: &gix::Commit<'_>,
rel: &Path,
read: &dyn Fn(&str) -> Option<String>,
) -> Result<PackageFile> {
let tree = commit.tree()?;
let Some(entry) = tree
.lookup_entry_by_path(rel)
.with_context(|| format!("reading {} at commit {}", rel.display(), commit.id()))?
else {
return Ok(PackageFile::Missing);
};
match entry.mode().kind() {
EntryKind::Blob | EntryKind::BlobExecutable => {
let blob = entry
.object()
.with_context(|| format!("reading {} at commit {}", rel.display(), commit.id()))?
.detach();
Ok(PackageFile::Present(read(&String::from_utf8_lossy(
&blob.data,
))))
}
EntryKind::Tree | EntryKind::Link | EntryKind::Commit => Ok(PackageFile::Present(None)),
}
}
impl PackageFile {
fn is_release_of(&self, wanted: &str) -> bool {
match self {
Self::Missing => true,
Self::Present(version) => version.as_deref() == Some(wanted),
}
}
}
pub fn tagged_commit(
root: &Path,
path: &Path,
sha: &str,
read: &dyn Fn(&str) -> Option<String>,
) -> Result<Option<VersionCommit>> {
let repo = discover(root).context("reading a tagged commit needs a git repository")?;
let commit = repo
.head_commit()
.context("reading a tagged commit needs HEAD")?;
tagged_commit_from_commit(&repo, commit, "HEAD", root, path, sha, read)
}
pub fn tagged_commit_from(
root: &Path,
start: &str,
path: &Path,
sha: &str,
read: &dyn Fn(&str) -> Option<String>,
) -> Result<Option<VersionCommit>> {
let repo = discover(root).context("reading a tagged commit needs a git repository")?;
let id =
gix::ObjectId::from_hex(start.as_bytes()).with_context(|| format!("commit {start}"))?;
let commit = repo
.find_commit(id)
.with_context(|| format!("commit {start} is not in the repository"))?;
tagged_commit_from_commit(&repo, commit, start, root, path, sha, read)
}
fn tagged_commit_from_commit<'a>(
repo: &'a gix::Repository,
mut commit: gix::Commit<'a>,
start_label: &str,
root: &Path,
path: &Path,
sha: &str,
read: &dyn Fn(&str) -> Option<String>,
) -> Result<Option<VersionCommit>> {
let rel = git_path(root, path, repo.workdir())
.with_context(|| format!("{} is not in the repository", path.display()))?;
let version_at =
|commit: &gix::Commit<'_>| -> Result<PackageFile> { package_file_at(commit, &rel, read) };
let wanted = match version_at(&commit)? {
PackageFile::Present(Some(version)) => version,
PackageFile::Missing | PackageFile::Present(None) => {
bail!("{start_label} has no version in {}", rel.display())
}
};
let boundary: Vec<gix::ObjectId> = repo
.shallow_commits()?
.map_or_default(|commits| commits.iter().copied().collect());
let mut line = Vec::new();
loop {
if commit.id().to_string().eq_ignore_ascii_case(sha) {
return Ok(version_at(&commit)?
.is_release_of(&wanted)
.then(|| VersionCommit {
sha: commit.id().to_string(),
depth: line.len(),
}));
}
if boundary.contains(&commit.id().detach()) {
return Err(lookup::unavailable(anyhow!(
"cannot find tagged commit {sha}: the clone is shallow; fetch the full history{}",
shallow_hint()
)));
}
line.push(commit.id().detach());
let Some(parent) = commit.parent_ids().next() else {
break;
};
commit = repo.find_commit(parent.detach())?;
}
merged_release(repo, &line, sha, &wanted, &version_at)
}
fn merged_release(
repo: &gix::Repository,
line: &[gix::ObjectId],
sha: &str,
wanted: &str,
version_at: &dyn Fn(&gix::Commit<'_>) -> Result<PackageFile>,
) -> Result<Option<VersionCommit>> {
let Ok(tagged) = gix::ObjectId::from_hex(sha.as_bytes()) else {
return Ok(None);
};
let Ok(commit) = repo.find_commit(tagged) else {
return Ok(None);
};
if !version_at(&commit)?.is_release_of(wanted) {
return Ok(None);
}
let contains = |at: gix::ObjectId| -> Result<bool> {
let base = repo.merge_base(at, tagged).with_context(|| {
format!("cannot tell whether HEAD contains tagged commit {sha}; fetch the full history")
})?;
Ok(base.is_some_and(|base| base == tagged))
};
let Some(&head) = line.first() else {
return Ok(None);
};
if !contains(head)? {
return Ok(None);
}
let mut inside = 0;
let mut outside = line.len();
let mut probe = 1;
while probe < line.len() {
if !contains(line[probe])? {
outside = probe;
break;
}
inside = probe;
probe *= 2;
}
while outside - inside > 1 {
let mid = inside + (outside - inside) / 2;
if contains(line[mid])? {
inside = mid;
} else {
outside = mid;
}
}
Ok(Some(VersionCommit {
sha: tagged.to_string(),
depth: inside,
}))
}
fn has_path(commit: &gix::Commit<'_>, rel: &Path) -> Result<bool> {
Ok(commit.tree()?.lookup_entry_by_path(rel)?.is_some())
}
fn named(commit: &gix::Commit<'_>) -> Result<AddedBy> {
Ok(AddedBy {
sha: commit.id().to_string(),
subject: commit.message()?.summary().to_str_lossy().into_owned(),
})
}
#[must_use]
pub fn pull_request_number(subject: &str) -> Option<u64> {
let (_, digits) = subject.trim_end().strip_suffix(')')?.rsplit_once("(#")?;
if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
return None;
}
digits.parse().ok()
}
#[must_use]
pub fn upstream_default_branch(root: &Path) -> Option<String> {
origin_head_branch(&discover(root).ok()?)
}
pub fn off_default_history(root: &Path) -> Result<Option<String>> {
prove_default_history(root, &candidate_names(env_base_ref().as_deref()))
}
pub fn workflows_differ(root: &Path) -> Result<Option<String>> {
workflows_differ_at(root, env_run_sha().as_deref())
}
fn workflows_differ_at(root: &Path, run_sha: Option<&str>) -> Result<Option<String>> {
let repo = repo_covering(root).with_context(|| {
format!(
"release cannot compare workflows: no git repository covers {}",
root.display()
)
})?;
let head = repo
.head_commit()
.context("release cannot compare workflows: HEAD has no commit")?;
let (run, label) = run_sha
.and_then(|sha| find_commit_by_hex(&repo, sha))
.map_or((head, "HEAD"), |commit| (commit, "GITHUB_SHA"));
let upstream = default_upstream_commit(&repo, &candidate_names(env_base_ref().as_deref()))?
.context("release cannot compare workflows: there is no `origin` remote")?;
let upstream = repo.find_commit(upstream)?;
let workflows = |commit: &gix::Commit<'_>| -> Result<Option<gix::ObjectId>> {
Ok(commit
.tree()?
.lookup_entry_by_path(WORKFLOWS)?
.map(|entry| entry.object_id()))
};
if workflows(&run)? == workflows(&upstream)? {
return Ok(None);
}
Ok(Some(format!(
"{WORKFLOWS}/ at {label} {run} differs from the default branch at {upstream}",
run = run.id(),
upstream = upstream.id(),
)))
}
fn find_commit_by_hex<'repo>(
repo: &'repo gix::Repository,
sha: &str,
) -> Option<gix::Commit<'repo>> {
let id = gix::ObjectId::from_hex(sha.as_bytes()).ok()?;
repo.find_commit(id).ok()
}
fn env_run_sha() -> Option<String> {
env::var("GITHUB_SHA")
.ok()
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
}
const WORKFLOWS: &str = ".github/workflows";
#[non_exhaustive]
pub enum FetchDefault {
Origin,
GitHub {
token: String,
repository: String,
},
}
impl fmt::Debug for FetchDefault {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Origin => f.write_str("Origin"),
Self::GitHub {
repository,
token: _,
} => f
.debug_struct("GitHub")
.field("token", &"<redacted>")
.field("repository", repository)
.finish(),
}
}
}
impl FetchDefault {
#[must_use]
pub fn from_env() -> Self {
match (env::var("GITHUB_TOKEN"), env::var("GITHUB_REPOSITORY")) {
(Ok(token), Ok(repository)) if !token.is_empty() && !repository.is_empty() => {
Self::GitHub { token, repository }
}
_ => Self::Origin,
}
}
}
#[must_use]
pub fn github_https_url(repository: &str) -> String {
format!("https://github.com/{repository}.git")
}
#[must_use]
pub fn github_git_user() -> &'static str {
"x-access-token"
}
#[must_use]
pub fn configured_default_branch() -> Option<String> {
env::var("VERCTL_DEFAULT_BRANCH")
.ok()
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
}
pub fn ensure_origin_head(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
if branch.is_empty() {
return Ok(());
}
let Some(repo) = repo_covering(root) else {
return Ok(());
};
if !has_origin(&repo) {
return Ok(());
}
let remote_ref = format!("refs/remotes/origin/{branch}");
if peel_remote(&repo, &remote_ref).is_none() {
fetch_one_branch(&repo, branch, fetch, Shallow::NoChange)?;
}
ensure!(
peel_remote(&repo, &remote_ref).is_some(),
"cannot resolve the default branch ({remote_ref} is missing; fetch the default branch)"
);
let target = FullName::try_from(remote_ref.as_str())
.context("point origin/HEAD at the default branch")?;
let name = FullName::try_from("refs/remotes/origin/HEAD")
.context("point origin/HEAD at the default branch")?;
repo.edit_reference(RefEdit::update(
name,
Target::Symbolic(target),
PreviousValue::Any,
"verctl default branch",
))
.context("point origin/HEAD at the default branch")?;
Ok(())
}
fn shallow_hint() -> &'static str {
if configured_default_branch().is_some() {
""
} else {
", or set VERCTL_DEFAULT_BRANCH so verctl fetches it"
}
}
pub fn ensure_full_history(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
if branch.is_empty() {
return Ok(());
}
let Some(repo) = repo_covering(root) else {
return Ok(());
};
if !has_origin(&repo) || !repo.is_shallow().context("read the shallow boundary")? {
return Ok(());
}
fetch_one_branch(&repo, branch, fetch, Shallow::undo())
}
pub fn ensure_comparable(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
if branch.is_empty() {
return Ok(());
}
let Some(repo) = repo_covering(root) else {
return Ok(());
};
if !has_origin(&repo) {
return Ok(());
}
let shallow = repo.is_shallow().context("read the shallow boundary")?;
let missing = peel_remote(&repo, &format!("refs/remotes/origin/{branch}")).is_none();
match (shallow, missing) {
(true, _) => fetch_one_branch(&repo, branch, fetch, Shallow::undo()),
(false, true) => fetch_one_branch(&repo, branch, fetch, Shallow::NoChange),
(false, false) => Ok(()),
}
}
fn fetch_one_branch(
repo: &gix::Repository,
branch: &str,
fetch: &FetchDefault,
shallow: Shallow,
) -> Result<()> {
let spec = format!("+refs/heads/{branch}:refs/remotes/origin/{branch}");
let url = match fetch {
FetchDefault::Origin => origin_url_of(repo)?,
FetchDefault::GitHub {
repository,
token: _,
} => github_https_url(repository),
};
let remote = repo
.remote_at(url.as_str())
.context("fetch the default branch")?
.with_fetch_tags(Tags::None)
.with_refspecs([spec.as_str()], Direction::Fetch)
.context("fetch the default branch")?;
let connection = remote
.connect(Direction::Fetch)
.with_context(|| format!("git fetch {spec}"))?;
let interrupt = AtomicBool::new(false);
match fetch {
FetchDefault::Origin => connection
.prepare_fetch(Discard, ref_map::Options::default())
.with_context(|| format!("git fetch {spec}"))?
.with_shallow(shallow)
.receive(Discard, &interrupt),
FetchDefault::GitHub {
token,
repository: _,
} => connection
.with_credentials(github_credentials(token))
.prepare_fetch(Discard, ref_map::Options::default())
.with_context(|| format!("git fetch {spec}"))?
.with_shallow(shallow)
.receive(Discard, &interrupt),
}
.with_context(|| format!("git fetch {spec}"))?;
Ok(())
}
fn github_credentials(token: &str) -> impl FnMut(Action) -> gix::Result<Option<Outcome>> + '_ {
move |action| match action {
Action::Get(context) => Ok(Some(Outcome {
identity: Account {
username: github_git_user().to_owned(),
password: token.to_owned(),
oauth_refresh_token: None,
},
next: context.into(),
})),
Action::Store(_) | Action::Erase(_) => Ok(None),
}
}
fn prove_default_history(root: &Path, candidates: &[String]) -> Result<Option<String>> {
let repo = repo_covering(root).with_context(|| {
format!(
"release cannot prove HEAD is on the default branch: no git repository covers {}",
root.display()
)
})?;
let head = repo
.head_commit()
.context("release cannot prove HEAD is on the default branch: HEAD has no commit")?
.id()
.detach();
let upstream = default_upstream_commit(&repo, candidates)?.context(
"release cannot prove HEAD is on the default branch: there is no `origin` remote; add it and fetch the default branch",
)?;
if head == upstream {
return Ok(None);
}
match repo.merge_base(head, upstream) {
Ok(Some(base)) if base == head => Ok(None),
Ok(Some(_) | None) => Ok(Some(format!(
"HEAD {head} is not an ancestor of the default branch at {upstream}"
))),
Err(error) => Err(error).context(
"release cannot prove HEAD is on the default branch (need a full fetch, not a shallow clone)",
),
}
}
#[must_use]
pub fn workdir_covering(dir: &Path) -> Option<PathBuf> {
repo_covering(dir)?
.workdir()
.and_then(|workdir| workdir.canonicalize().ok())
}
pub fn tracked(root: &Path) -> Result<Vec<PathBuf>> {
let Some(repo) = repo_covering(root) else {
return Ok(Vec::new());
};
let index = repo.index_or_empty().context("git index")?;
let project = project_prefix(&repo, root);
Ok(index
.entries()
.iter()
.filter_map(|entry| entry.path(&index).to_str().ok().map(PathBuf::from))
.filter_map(|path| path.strip_prefix(&project).ok().map(Path::to_path_buf))
.collect())
}
#[must_use]
pub fn is_ignored(root: &Path, rel: &Path) -> bool {
let Some(repo) = repo_covering(root) else {
return false;
};
let path = project_prefix(&repo, root).join(rel);
let Ok(index) = repo.index_or_empty() else {
return false;
};
let Ok(mut excludes) = repo.excludes(&index, None, Source::WorktreeThenIdMappingIfNotSkipped)
else {
return false;
};
let mut ignored_at = |path: &Path, mode| {
excludes
.at_path(path, mode)
.is_ok_and(|platform| platform.is_excluded())
};
path.ancestors()
.skip(1)
.filter(|dir| !dir.as_os_str().is_empty())
.any(|dir| ignored_at(dir, Some(Mode::DIR)))
|| ignored_at(&path, None)
}
#[must_use]
pub fn is_repository(root: &Path) -> bool {
repo_covering(root).is_some()
}
fn project_prefix(repo: &gix::Repository, root: &Path) -> PathBuf {
let Some(workdir) = repo.workdir().and_then(|dir| dir.canonicalize().ok()) else {
return PathBuf::new();
};
root.canonicalize()
.ok()
.and_then(|root| root.strip_prefix(&workdir).ok().map(Path::to_path_buf))
.unwrap_or_default()
}
fn discover(dir: &Path) -> Result<gix::Repository> {
let mapping = Mapping {
full: open_options(Trust::Full),
reduced: open_options(Trust::Reduced),
};
let repo = gix::ThreadSafeRepository::discover_opts(
dir,
gix::discover::upwards::Options::default(),
mapping,
)
.with_context(|| format!("no git repository covers {}", dir.display()))?;
let mut repo = repo.to_thread_local();
let (name, email) = fallback_identity();
repo.committer_or_set_fallback(name.as_str(), email.as_str())
.context("set the reflog identity")?;
Ok(repo)
}
fn open_options(trust: Trust) -> open::Options {
let mut options = open::Options::default_for_level(trust);
options.permissions.env.git_prefix = Permission::Deny;
options
}
fn repo_covering(root: &Path) -> Option<gix::Repository> {
let repo = discover(root).ok()?;
let workdir = repo.workdir()?.canonicalize().ok()?;
let root = root.canonicalize().ok()?;
root.starts_with(workdir).then_some(repo)
}
fn has_origin(repo: &gix::Repository) -> bool {
repo.remote_names()
.iter()
.any(|name| name.to_str() == Ok("origin"))
}
fn origin_url_of(repo: &gix::Repository) -> Result<String> {
let remote = repo
.find_remote("origin")
.context("fetch the default branch")?;
let url = remote.url(Direction::Fetch).context("origin has no URL")?;
Ok(url.to_bstring().to_str_lossy().into_owned())
}
fn peel_remote(repo: &gix::Repository, name: &str) -> Option<gix::ObjectId> {
let mut reference = repo.try_find_reference(name).ok()??;
let commit = reference.peel_to_commit().ok()?;
Some(commit.id().detach())
}
fn origin_head_branch(repo: &gix::Repository) -> Option<String> {
let reference = repo.try_find_reference("refs/remotes/origin/HEAD").ok()??;
let target = reference.target();
let target = target.try_name()?.as_bstr().to_str().ok()?;
let name = target.trim_start_matches("refs/remotes/origin/");
(!name.is_empty()).then(|| name.to_owned())
}
fn env_base_ref() -> Option<String> {
env::var("GITHUB_BASE_REF")
.ok()
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
}
#[must_use]
pub fn default_branch_candidates() -> Vec<String> {
candidate_names(env_base_ref().as_deref())
}
#[must_use]
pub fn release_branch_candidates() -> Vec<String> {
release_candidate_names(
configured_default_branch().as_deref(),
github_env::event_default_branch().as_deref(),
env_base_ref().as_deref(),
)
}
fn release_candidate_names(
configured: Option<&str>,
event_default: Option<&str>,
base: Option<&str>,
) -> Vec<String> {
let mut names = Vec::new();
for name in [configured, event_default].into_iter().flatten() {
if !name.is_empty() && !names.iter().any(|known| known == name) {
names.push(name.to_owned());
}
}
for name in candidate_names(None)
.into_iter()
.chain(base.map(str::to_owned))
{
if !name.is_empty() && !names.contains(&name) {
names.push(name);
}
}
names
}
#[must_use]
pub fn comparison_branches() -> Vec<String> {
let mut names = Vec::new();
let sources = [
configured_default_branch(),
github_env::event_default_branch(),
env_base_ref(),
];
for name in sources.into_iter().flatten() {
if !name.is_empty() && !names.contains(&name) {
names.push(name);
}
}
names
}
#[must_use]
pub fn default_branch_candidates_from(base_ref: Option<&str>) -> Vec<String> {
candidate_names(base_ref)
}
fn candidate_names(base_ref: Option<&str>) -> Vec<String> {
let mut names = Vec::new();
if let Some(value) = base_ref.map(str::trim).filter(|value| !value.is_empty()) {
names.push(value.to_owned());
}
for stock in ["main", "master"] {
if !names.iter().any(|name| name == stock) {
names.push(stock.to_owned());
}
}
names
}
fn default_upstream_commit(
repo: &gix::Repository,
candidates: &[String],
) -> Result<Option<gix::ObjectId>> {
if let Some(branch) = origin_head_branch(repo) {
let name = format!("refs/remotes/origin/{branch}");
return match peel_remote(repo, &name) {
Some(commit) => Ok(Some(commit)),
None => bail!(
"cannot resolve the default branch ({name} is missing; fetch the default branch)"
),
};
}
for name in candidates {
let reference = format!("refs/remotes/origin/{name}");
if let Some(commit) = peel_remote(repo, &reference) {
return Ok(Some(commit));
}
}
if has_origin(repo) {
bail!(
"cannot resolve the default branch (origin exists but origin/HEAD, origin/main, and origin/master are missing; fetch the default branch)"
);
}
Ok(None)
}
#[must_use]
pub fn matches_stage(pattern: &str, rel: &str) -> bool {
glob::Pattern::new(pattern)
.is_ok_and(|compiled| compiled.matches(rel) || compiled.matches(&format!("./{rel}")))
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum IgnoredFiles {
#[default]
Skip,
Include,
}
pub fn assert_only_allowed(
root: &Path,
allowed: &[PathBuf],
globs: &[String],
ignored: IgnoredFiles,
) -> Result<Vec<PathBuf>> {
let Ok(repo) = discover(root) else {
return Ok(Vec::new());
};
let dirty = status_paths(&repo, Vec::new(), IgnoredFiles::Skip).context("git status")?;
let workdir = repo.workdir().unwrap_or(root);
let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let workdir = workdir
.canonicalize()
.unwrap_or_else(|_| workdir.to_path_buf());
let mut extra = Vec::new();
let mut staged = Vec::new();
for rel in &dirty {
let abs = workdir.join(rel);
if !abs.starts_with(&root) {
continue;
}
if abs.is_dir() {
continue;
}
if allowed
.iter()
.any(|path| path == &abs || path.ends_with(rel))
{
continue;
}
if globs.iter().any(|pattern| matches_stage(pattern, rel)) {
staged.push(abs);
continue;
}
extra.push(rel.clone());
}
if matches!(ignored, IgnoredFiles::Include) && !globs.is_empty() {
let patterns = globs
.iter()
.map(|pattern| pattern.as_str().into())
.collect();
let ignored =
status_paths(&repo, patterns, IgnoredFiles::Include).context("git status (ignored)")?;
for rel in &ignored {
let abs = workdir.join(rel);
if !abs.starts_with(&root) || abs.is_dir() {
continue;
}
if globs.iter().any(|pattern| matches_stage(pattern, rel))
&& !staged.iter().any(|path| path == &abs)
{
staged.push(abs);
}
}
}
if extra.is_empty() {
return Ok(staged);
}
bail!(
"version produced unexpected paths (declare them in prepare.stage): {}",
extra.join(", ")
);
}
fn status_paths(
repo: &gix::Repository,
patterns: Vec<BString>,
ignored: IgnoredFiles,
) -> Result<BTreeSet<String>> {
let include_ignored = matches!(ignored, IgnoredFiles::Include);
let status = repo
.status(Discard)?
.untracked_files(UntrackedFiles::Files)
.index_worktree_rewrites(None)
.tree_index_track_renames(TrackRenames::Disabled);
let status = if include_ignored {
status.dirwalk_options(|options| options.emit_ignored(Some(EmissionMode::Matching)))
} else {
status
};
let mut paths = BTreeSet::new();
for item in status.into_iter(patterns)? {
let item = item?;
let is_ignored = matches!(
&item,
status::Item::IndexWorktree(index_worktree::Item::DirectoryContents {
entry,
collapsed_directory_status: _
}) if matches!(entry.status, Status::Ignored(_))
);
if is_ignored == include_ignored {
paths.insert(item.location().to_str_lossy().into_owned());
}
}
Ok(paths)
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum PushOutcome {
Empty,
Pushed,
}
pub fn commit_branch_and_push(
root: &Path,
branch: &str,
message: &str,
token: &str,
github: &Repo,
paths: &[PathBuf],
) -> Result<PushOutcome> {
let repo = discover(root).context("open git repository")?;
let workdir = absolute_workdir(&repo)?;
let parent = repo.head_commit().context("HEAD commit")?;
let Some(_) = write_commit_on_branch(&repo, &workdir, &parent, branch, message, paths)? else {
return Ok(PushOutcome::Empty);
};
let url = format!("https://github.com/{}/{}.git", github.owner, github.name);
push(repo.git_dir(), &url, branch, token)?;
Ok(PushOutcome::Pushed)
}
fn absolute_workdir(repo: &gix::Repository) -> Result<PathBuf> {
let workdir = repo.workdir().context("repository has no workdir")?;
path::absolute(workdir).with_context(|| format!("resolve the workdir {}", workdir.display()))
}
const PUSH_TOKEN: &str = "VERCTL_GIT_TOKEN";
const PUSH_CREDENTIAL_HELPER: &str = r#"!f() { test "$1" = get || return 0; echo username=x-access-token; echo "password=$VERCTL_GIT_TOKEN"; }; f"#;
const PUSH_TIMEOUT: Duration = Duration::from_mins(5);
fn push(git_dir: &Path, url: &str, branch: &str, token: &str) -> Result<()> {
let git_dir = git_dir
.canonicalize()
.with_context(|| format!("git directory {}", git_dir.display()))?;
let git_dir = format!(
"--git-dir={}",
git_dir.to_str().context("git directory is not UTF-8")?
);
let helper = format!("credential.helper={PUSH_CREDENTIAL_HELPER}");
let refspec = format!("+refs/heads/{branch}:refs/heads/{branch}");
let argv = process::argv(&[
"git",
&git_dir,
"-c",
"credential.helper=",
"-c",
&helper,
"push",
"--no-verify",
"--quiet",
url,
&refspec,
]);
process::run_limited(
&argv,
&[(PUSH_TOKEN, token), ("GIT_TERMINAL_PROMPT", "0")],
PUSH_TIMEOUT,
)
.context("git push")?;
Ok(())
}
fn write_commit_on_branch(
repo: &gix::Repository,
workdir: &Path,
parent: &gix::Commit<'_>,
branch: &str,
message: &str,
paths: &[PathBuf],
) -> Result<Option<gix::ObjectId>> {
let parent_tree = parent.tree_id().context("HEAD tree")?.detach();
let mut editor = repo.edit_tree(parent_tree).context("edit HEAD tree")?;
let (mut filters, index) = repo
.filter_pipeline(None)
.context("load the .gitattributes filters")?;
for path in paths {
let rel = workdir_rel(workdir, path)?;
let name = rel
.to_str()
.with_context(|| format!("path is not UTF-8: {}", rel.display()))?
.to_owned();
let abs = workdir.join(&rel);
if abs.exists() {
let (kind, data) = worktree_entry(&mut filters, &index, &abs, &rel)?;
let blob = repo
.write_blob(data)
.with_context(|| format!("git add {name}"))?;
editor
.upsert(&name, kind, blob)
.with_context(|| format!("git add {name}"))?;
} else {
editor
.remove(&name)
.with_context(|| format!("git rm {name}"))?;
}
}
let tree = editor.write().context("write tree")?.detach();
if tree == parent_tree {
return Ok(None);
}
let signature = signature(repo);
let commit = Commit {
tree,
parents: [parent.id().detach()].into_iter().collect(),
author: signature.clone(),
committer: signature,
encoding: None,
message: message.into(),
extra_headers: Vec::new(),
};
let id = repo.write_object(&commit).context("git commit")?.detach();
repo.reference(
format!("refs/heads/{branch}"),
id,
PreviousValue::Any,
"verctl: version packages",
)
.context("git commit")?;
Ok(Some(id))
}
fn worktree_entry(
filters: &mut Pipeline<'_>,
index: &State,
abs: &Path,
rel: &Path,
) -> Result<(EntryKind, Vec<u8>)> {
let meta = fs::symlink_metadata(abs).with_context(|| abs.display().to_string())?;
if meta.file_type().is_symlink() {
let target = fs::read_link(abs).with_context(|| abs.display().to_string())?;
let target = target
.to_str()
.with_context(|| format!("link target is not UTF-8: {}", abs.display()))?;
return Ok((EntryKind::Link, target.as_bytes().to_vec()));
}
let file = File::open(abs).with_context(|| abs.display().to_string())?;
let mut clean = filters
.convert_to_git(file, rel, index)
.with_context(|| format!("filter {}", rel.display()))?;
let mut data = Vec::new();
Read::read_to_end(&mut clean, &mut data)
.with_context(|| format!("filter {}", rel.display()))?;
Ok((file_kind(&meta), data))
}
#[cfg(unix)]
fn file_kind(meta: &Metadata) -> EntryKind {
use std::os::unix::fs::PermissionsExt;
if meta.permissions().mode() & 0o111 == 0 {
EntryKind::Blob
} else {
EntryKind::BlobExecutable
}
}
#[cfg(not(unix))]
fn file_kind(_meta: &std::fs::Metadata) -> EntryKind {
EntryKind::Blob
}
fn workdir_rel(workdir: &Path, path: &Path) -> Result<PathBuf> {
let absolute = if path.is_absolute() {
path.to_path_buf()
} else {
workdir.join(path)
};
let normalized: PathBuf = absolute
.components()
.filter(|component| !matches!(component, Component::CurDir))
.collect();
let workdirs = [Some(workdir.to_path_buf()), workdir.canonicalize().ok()];
let through_parent = normalized
.parent()
.and_then(|parent| parent.canonicalize().ok())
.zip(normalized.file_name())
.map(|(parent, name)| parent.join(name));
let paths = [Some(normalized.clone()), through_parent];
paths
.iter()
.flatten()
.find_map(|path| {
workdirs
.iter()
.flatten()
.find_map(|workdir| path.strip_prefix(workdir).ok())
})
.map(Path::to_path_buf)
.with_context(|| format!("path outside workdir: {}", normalized.display()))
}
fn signature(repo: &gix::Repository) -> Signature {
let time = Time::now_local_or_utc();
let config = repo.config_snapshot();
if let (Some(name), Some(email)) = (config.string("user.name"), config.string("user.email")) {
return Signature { name, email, time };
}
let (name, email) = fallback_identity();
Signature {
name: name.into(),
email: email.into(),
time,
}
}
fn fallback_identity() -> (String, String) {
let name = env::var("GIT_AUTHOR_NAME")
.or_else(|_| env::var("GITHUB_ACTOR"))
.unwrap_or_else(|_| "verctl".into());
let email =
env::var("GIT_AUTHOR_EMAIL").unwrap_or_else(|_| format!("{name}@users.noreply.github.com"));
(name, email)
}
#[cfg(test)]
mod tests {
use std::fs;
use std::os::unix::fs::symlink;
use std::path::{Path, PathBuf};
use indoc::indoc;
use tokio::task;
use verctl_core::repo::Repo;
use wiremock::matchers;
use super::{
AddedBy, VersionCommit, added_by, added_by_from, candidate_deletions, file_at, origin_url,
tagged_commit,
};
use crate::test_git::{commit_all, git, init};
fn version_file(raw: &str) -> Option<String> {
let version = raw.trim();
(!version.is_empty()).then(|| version.to_owned())
}
fn fragment(bump: &str, summary: &str) -> String {
indoc::formatdoc! {"
---
demo: {bump}
---
{summary}
"}
}
fn two_candidates(dir: &Path) -> (String, String) {
init(dir);
fs::create_dir(dir.join(".changeset")).unwrap();
fs::write(dir.join("VERSION"), "0.8.0\n").unwrap();
fs::write(dir.join(".changeset/old.md"), fragment("patch", "Old.")).unwrap();
commit_all(dir, "chore: start");
fs::write(dir.join("VERSION"), "0.8.1\n").unwrap();
fs::remove_file(dir.join(".changeset/old.md")).unwrap();
commit_all(dir, "chore: release demo 0.8.1 (#1)");
fs::write(dir.join(".changeset/one.md"), fragment("patch", "One.")).unwrap();
let added = commit_all(dir, "fix: one (#2)");
fs::write(dir.join("VERSION"), "0.8.2-rc.1\n").unwrap();
fs::remove_file(dir.join(".changeset/one.md")).unwrap();
commit_all(dir, "chore: release demo 0.8.2-rc.1 (#3)");
let first_parent = git(dir, &["rev-parse", "HEAD~1"]);
fs::write(dir.join(".changeset/stray.md"), fragment("patch", "Stray.")).unwrap();
commit_all(dir, "docs: stray (#4)");
fs::remove_file(dir.join(".changeset/stray.md")).unwrap();
commit_all(dir, "docs: drop stray (#5)");
fs::write(dir.join(".changeset/two.md"), fragment("minor", "Two.")).unwrap();
commit_all(dir, "feat: two (#6)");
fs::write(dir.join("VERSION"), "0.8.2-rc.2\n").unwrap();
fs::remove_file(dir.join(".changeset/two.md")).unwrap();
commit_all(dir, "chore: release demo 0.8.2-rc.2 (#7)");
(added, first_parent)
}
#[test]
fn candidate_deletions_lists_what_each_candidate_consumed_since_stable() {
let dir = tempfile::TempDir::new().unwrap();
let (_, first_parent) = two_candidates(dir.path());
let deleted = candidate_deletions(
dir.path(),
&dir.path().join("VERSION"),
&version_file,
&dir.path().join(".changeset"),
)
.unwrap();
let names: Vec<(String, String)> = deleted
.iter()
.map(|file| {
(
file.path
.file_name()
.unwrap()
.to_string_lossy()
.into_owned(),
file.text.clone(),
)
})
.collect();
assert_eq!(
names,
[
("two.md".to_owned(), fragment("minor", "Two.")),
("one.md".to_owned(), fragment("patch", "One.")),
]
);
assert_eq!(deleted[1].parent, first_parent);
assert_eq!(deleted[1].path, dir.path().join(".changeset/one.md"));
}
#[test]
fn candidate_deletions_is_empty_on_a_stable_head() {
let dir = tempfile::TempDir::new().unwrap();
two_candidates(dir.path());
fs::write(dir.path().join("VERSION"), "0.8.2\n").unwrap();
commit_all(dir.path(), "chore: release demo 0.8.2 (#8)");
assert_eq!(
candidate_deletions(
dir.path(),
&dir.path().join("VERSION"),
&version_file,
&dir.path().join(".changeset"),
)
.unwrap(),
[]
);
}
#[test]
fn added_by_from_resolves_a_fragment_deleted_at_head() {
let dir = tempfile::TempDir::new().unwrap();
let (added, first_parent) = two_candidates(dir.path());
let path = dir.path().join(".changeset/one.md");
assert_eq!(added_by(dir.path(), &path).unwrap(), None);
assert_eq!(
added_by_from(dir.path(), &path, &first_parent).unwrap(),
Some(AddedBy {
sha: added,
subject: "fix: one (#2)".to_owned(),
})
);
}
#[test]
fn candidate_deletions_fails_at_a_shallow_boundary() {
let dir = tempfile::TempDir::new().unwrap();
two_candidates(dir.path());
let boundary = git(dir.path(), &["rev-parse", "HEAD~2"]);
fs::write(dir.path().join(".git/shallow"), format!("{boundary}\n")).unwrap();
let error = candidate_deletions(
dir.path(),
&dir.path().join("VERSION"),
&version_file,
&dir.path().join(".changeset"),
)
.unwrap_err()
.to_string();
assert!(error.contains(&boundary), "{error}");
assert!(error.contains("shallow"), "{error}");
}
fn tree_names(dir: &Path, sha: &str) -> Vec<String> {
git(dir, &["ls-tree", "-r", "--name-only", sha])
.lines()
.map(str::to_owned)
.collect()
}
fn version_line(raw: &str) -> Option<String> {
raw.lines()
.find_map(|line| line.strip_prefix("version = "))
.map(|version| version.trim_matches('"').to_owned())
}
fn write_version(dir: &Path, version: &str) {
fs::write(
dir.join("Cargo.toml"),
indoc::formatdoc! {r#"
[package]
name = "demo"
version = "{version}"
"#},
)
.unwrap();
}
#[test]
fn a_tag_on_a_later_commit_at_the_same_version_is_the_release() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
write_version(dir.path(), "0.4.6");
let set = commit_all(dir.path(), "chore(release): version packages (#9)");
fs::write(dir.path().join("README"), "later\n").unwrap();
let later = commit_all(dir.path(), "docs: later");
fs::write(dir.path().join("README"), "head\n").unwrap();
commit_all(dir.path(), "docs: head");
let manifest = dir.path().join("Cargo.toml");
let found = tagged_commit(dir.path(), &manifest, &later, &version_line).unwrap();
assert_eq!(
found,
Some(VersionCommit {
sha: later,
depth: 1,
})
);
assert!(
tagged_commit(dir.path(), &manifest, &set, &version_line)
.unwrap()
.is_some()
);
}
#[test]
fn a_tag_on_a_commit_at_another_version_is_not_the_release() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
write_version(dir.path(), "0.4.5");
let older = commit_all(dir.path(), "chore: start");
write_version(dir.path(), "0.4.6");
commit_all(dir.path(), "chore(release): version packages (#9)");
let manifest = dir.path().join("Cargo.toml");
assert_eq!(
tagged_commit(dir.path(), &manifest, &older, &version_line).unwrap(),
None
);
assert_eq!(
tagged_commit(dir.path(), &manifest, &"0".repeat(40), &version_line).unwrap(),
None
);
}
fn write_project(dir: &Path, version: &str) {
fs::write(
dir.join("project.yml"),
indoc::formatdoc! {r#"
name: Demo
targets:
Demo:
settings:
base:
MARKETING_VERSION: "{version}"
"#},
)
.unwrap();
}
fn released_before_the_version_file(dir: &Path) -> String {
init(dir);
write_project(dir, "0.0.16");
let released = commit_all(dir, "chore(release): version packages");
fs::write(dir.join("VERSION"), "0.0.16\n").unwrap();
commit_all(dir, "chore: version the app through a VERSION file");
released
}
fn released_beside_the_version_file(dir: &Path) -> String {
init(dir);
write_project(dir, "0.0.16");
let start = commit_all(dir, "chore: start");
git(dir, &["checkout", "-q", "--detach", &start]);
fs::write(dir.join("publish.yml"), "published\n").unwrap();
let released = commit_all(dir, "ci: publish");
git(dir, &["checkout", "-q", "main"]);
fs::write(dir.join("VERSION"), "0.0.16\n").unwrap();
commit_all(dir, "chore: version the app through a VERSION file");
released
}
fn keep_merged(dir: &Path, sha: &str) {
git(
dir,
&[
"merge",
"-q",
"-s",
"ours",
"-m",
"forkctl: keep published history",
sha,
],
);
}
#[test]
fn a_tag_on_a_commit_before_the_version_file_existed_is_the_release() {
let dir = tempfile::TempDir::new().unwrap();
let released = released_before_the_version_file(dir.path());
let found = tagged_commit(
dir.path(),
&dir.path().join("VERSION"),
&released,
&version_file,
)
.unwrap();
assert_eq!(
found,
Some(VersionCommit {
sha: released,
depth: 1,
})
);
}
#[test]
fn a_merged_tag_on_a_commit_before_the_version_file_existed_is_the_release() {
let dir = tempfile::TempDir::new().unwrap();
let released = released_beside_the_version_file(dir.path());
keep_merged(dir.path(), &released);
let found = tagged_commit(
dir.path(),
&dir.path().join("VERSION"),
&released,
&version_file,
)
.unwrap();
assert_eq!(
found,
Some(VersionCommit {
sha: released,
depth: 0,
})
);
}
#[test]
fn an_unreached_tag_before_the_version_file_existed_is_not_the_release() {
let dir = tempfile::TempDir::new().unwrap();
let released = released_beside_the_version_file(dir.path());
let found = tagged_commit(
dir.path(),
&dir.path().join("VERSION"),
&released,
&version_file,
)
.unwrap();
assert_eq!(found, None);
}
#[test]
fn a_tag_on_a_commit_with_a_directory_at_the_version_path_is_not_the_release() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::create_dir(dir.path().join("VERSION")).unwrap();
fs::write(dir.path().join("VERSION").join("README"), "a directory\n").unwrap();
let tagged = commit_all(dir.path(), "chore: a directory at the path");
fs::remove_dir_all(dir.path().join("VERSION")).unwrap();
fs::write(dir.path().join("VERSION"), "0.0.16\n").unwrap();
commit_all(dir.path(), "chore: version the app through a VERSION file");
let found = tagged_commit(
dir.path(),
&dir.path().join("VERSION"),
&tagged,
&version_file,
)
.unwrap();
assert_eq!(found, None);
}
fn rewritten_and_merged_back(dir: &Path, published_version: &str) -> String {
init(dir);
write_version(dir, "0.0.1");
fs::write(dir.join("publish.yml"), "one\n").unwrap();
let set = commit_all(dir, "chore: start");
write_version(dir, published_version);
fs::write(dir.join("publish.yml"), "two\n").unwrap();
let published = commit_all(dir, "ci: publish");
git(dir, &["checkout", "-q", "--detach", &set]);
fs::write(dir.join("publish.yml"), "three\n").unwrap();
commit_all(dir, "ci: rewritten publish");
keep_merged(dir, &published);
published
}
#[test]
fn a_tag_on_a_merged_commit_at_the_same_version_is_the_release() {
let dir = tempfile::TempDir::new().unwrap();
let published = rewritten_and_merged_back(dir.path(), "0.0.1");
assert_ne!(
git(dir.path(), &["rev-parse", "HEAD^1:publish.yml"]),
git(
dir.path(),
&["rev-parse", &format!("{published}:publish.yml")]
),
"the first-parent commit at the same version changes another file"
);
let found = tagged_commit(
dir.path(),
&dir.path().join("Cargo.toml"),
&published,
&version_line,
)
.unwrap();
assert_eq!(
found,
Some(VersionCommit {
sha: published,
depth: 0,
})
);
}
#[test]
fn a_tag_merged_several_commits_below_head_takes_the_depth_of_the_merge() {
let dir = tempfile::TempDir::new().unwrap();
let published = rewritten_and_merged_back(dir.path(), "0.0.1");
for later in 1..=5 {
fs::write(dir.path().join("README"), format!("later {later}\n")).unwrap();
commit_all(dir.path(), &format!("docs: later {later}"));
}
let found = tagged_commit(
dir.path(),
&dir.path().join("Cargo.toml"),
&published,
&version_line,
)
.unwrap();
assert_eq!(
found,
Some(VersionCommit {
sha: published,
depth: 5,
})
);
}
#[test]
fn a_tag_on_a_merged_commit_at_another_version_is_not_the_release() {
let dir = tempfile::TempDir::new().unwrap();
let published = rewritten_and_merged_back(dir.path(), "0.0.2");
assert_eq!(
tagged_commit(
dir.path(),
&dir.path().join("Cargo.toml"),
&published,
&version_line,
)
.unwrap(),
None
);
}
#[test]
fn a_tag_on_a_commit_head_does_not_contain_is_not_the_release() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
write_version(dir.path(), "0.0.1");
let set = commit_all(dir.path(), "chore: start");
fs::write(dir.path().join("publish.yml"), "two\n").unwrap();
let abandoned = commit_all(dir.path(), "ci: publish");
git(dir.path(), &["checkout", "-q", "--detach", &set]);
fs::write(dir.path().join("publish.yml"), "three\n").unwrap();
commit_all(dir.path(), "ci: rewritten publish");
assert_eq!(
tagged_commit(
dir.path(),
&dir.path().join("Cargo.toml"),
&abandoned,
&version_line,
)
.unwrap(),
None
);
}
#[test]
fn file_at_reads_a_file_at_a_commit_and_nothing_before_it() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join("README"), "start\n").unwrap();
let before = commit_all(dir.path(), "chore: start");
fs::create_dir_all(dir.path().join(".ctl")).unwrap();
fs::write(dir.path().join(".ctl/ver.yaml"), "packages: []\n").unwrap();
let added = commit_all(dir.path(), "chore: add the config");
fs::write(dir.path().join(".ctl/ver.yaml"), "packages: [later]\n").unwrap();
commit_all(dir.path(), "chore: change the config");
let path = Path::new(".ctl/ver.yaml");
assert_eq!(
file_at(dir.path(), &added, path).unwrap().as_deref(),
Some("packages: []\n")
);
assert_eq!(file_at(dir.path(), &before, path).unwrap(), None);
}
#[test]
fn added_by_names_the_commit_that_added_the_file() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join("README"), "start\n").unwrap();
commit_all(dir.path(), "chore: start");
fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
let added = commit_all(dir.path(), "fix: the parser (#12)");
fs::write(dir.path().join("README"), "later\n").unwrap();
commit_all(dir.path(), "docs: later");
assert_eq!(
added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
Some(AddedBy {
sha: added,
subject: "fix: the parser (#12)".into(),
})
);
}
#[test]
fn added_by_follows_a_merge_to_the_commit_that_added_the_file() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join("README"), "start\n").unwrap();
let base = commit_all(dir.path(), "chore: start");
fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
let side = commit_all(dir.path(), "fix: the parser (#12)");
git(dir.path(), &["reset", "-q", "--hard", &base]);
fs::write(dir.path().join("README"), "later\n").unwrap();
let main = commit_all(dir.path(), "docs: later (#13)");
fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
git(dir.path(), &["add", "-A"]);
let tree = git(dir.path(), &["write-tree"]);
let merge = git(
dir.path(),
&[
"commit-tree",
&tree,
"-p",
&main,
"-p",
&side,
"-m",
"feat: release next (#14)",
],
);
git(dir.path(), &["reset", "-q", "--hard", &merge]);
assert_eq!(
added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
Some(AddedBy {
sha: side,
subject: "fix: the parser (#12)".into(),
})
);
}
#[test]
fn added_by_names_a_titled_merge_over_an_unnamed_branch_commit() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join("README"), "start\n").unwrap();
let base = commit_all(dir.path(), "chore: start");
fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
let side = commit_all(dir.path(), "wip");
git(dir.path(), &["reset", "-q", "--hard", &base]);
fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
git(dir.path(), &["add", "-A"]);
let tree = git(dir.path(), &["write-tree"]);
let merge = git(
dir.path(),
&[
"commit-tree",
&tree,
"-p",
&base,
"-p",
&side,
"-m",
"fix: the parser (#12)",
],
);
git(dir.path(), &["reset", "-q", "--hard", &merge]);
assert_eq!(
added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
Some(AddedBy {
sha: merge,
subject: "fix: the parser (#12)".into(),
})
);
}
#[test]
fn added_by_keeps_the_adding_pull_request_after_an_edit() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join("README"), "start\n").unwrap();
let base = commit_all(dir.path(), "chore: start");
fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
let side = commit_all(dir.path(), "wip");
git(dir.path(), &["reset", "-q", "--hard", &base]);
fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
git(dir.path(), &["add", "-A"]);
let tree = git(dir.path(), &["write-tree"]);
let added = git(
dir.path(),
&[
"commit-tree",
&tree,
"-p",
&base,
"-p",
&side,
"-m",
"fix: the parser (#12)",
],
);
git(dir.path(), &["reset", "-q", "--hard", &added]);
fs::write(dir.path().join("fix.md"), "Fix, reworded.\n").unwrap();
let edit = commit_all(dir.path(), "docs: reword the fix");
git(dir.path(), &["reset", "-q", "--hard", &added]);
fs::write(dir.path().join("fix.md"), "Fix, reworded.\n").unwrap();
git(dir.path(), &["add", "-A"]);
let tree = git(dir.path(), &["write-tree"]);
let edited = git(
dir.path(),
&[
"commit-tree",
&tree,
"-p",
&added,
"-p",
&edit,
"-m",
"docs: reword the fix (#13)",
],
);
git(dir.path(), &["reset", "-q", "--hard", &edited]);
fs::write(dir.path().join("fix.md"), "Fix, reworded again.\n").unwrap();
commit_all(dir.path(), "docs: reword the fix again (#14)");
assert_eq!(
added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
Some(AddedBy {
sha: added,
subject: "fix: the parser (#12)".into(),
})
);
}
#[test]
fn added_by_names_nothing_past_a_shallow_boundary() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
commit_all(dir.path(), "fix: the parser (#12)");
fs::write(dir.path().join("README"), "later\n").unwrap();
let boundary = commit_all(dir.path(), "docs: later (#13)");
fs::write(dir.path().join(".git/shallow"), format!("{boundary}\n")).unwrap();
assert_eq!(
git(dir.path(), &["rev-parse", "--is-shallow-repository"]),
"true"
);
assert_eq!(
added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
None
);
}
#[test]
fn origin_url_from_discovered_repo() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
git(
dir.path(),
&[
"remote",
"add",
"origin",
"https://github.com/victor-software-house/verctl.git",
],
);
commit_all(dir.path(), "init");
assert_eq!(
origin_url(dir.path()).unwrap(),
"https://github.com/victor-software-house/verctl.git"
);
}
#[test]
fn empty_paths_do_not_switch_head() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
commit_all(dir.path(), "init");
let before = git(dir.path(), &["symbolic-ref", "HEAD"]);
let repo_id = Repo {
owner: "victor-software-house".into(),
name: "verctl".into(),
};
let out = super::commit_branch_and_push(
dir.path(),
"verctl/release/main",
"chore",
"unused",
&repo_id,
&[],
)
.unwrap();
assert_eq!(out, super::PushOutcome::Empty);
assert_eq!(git(dir.path(), &["symbolic-ref", "HEAD"]), before);
}
#[test]
fn unexpected_dirty_fails_unless_globbed() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(
dir.path().join("Cargo.toml"),
indoc! {r#"
[package]
version = "1.0.0"
"#},
)
.unwrap();
commit_all(dir.path(), "init");
fs::write(dir.path().join("secret.env"), "TOKEN=leak\n").unwrap();
let allowed = [dir.path().join("Cargo.toml")];
let err = super::assert_only_allowed(dir.path(), &allowed, &[], super::IgnoredFiles::Skip)
.unwrap_err();
assert!(format!("{err:#}").contains("secret.env"), "{err:#}");
let staged = super::assert_only_allowed(
dir.path(),
&allowed,
&["*.env".into()],
super::IgnoredFiles::Skip,
)
.unwrap();
assert_eq!(staged.len(), 1);
assert!(staged[0].ends_with("secret.env"), "{staged:?}");
}
#[test]
fn stage_glob_collects_a_deleted_file() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join("Cargo.lock"), "old\n").unwrap();
fs::write(
dir.path().join("Cargo.toml"),
indoc! {r#"
[package]
version = "1.0.0"
"#},
)
.unwrap();
commit_all(dir.path(), "init");
fs::remove_file(dir.path().join("Cargo.lock")).unwrap();
let staged = super::assert_only_allowed(
dir.path(),
&[dir.path().join("Cargo.toml")],
&["Cargo.lock".into()],
super::IgnoredFiles::Skip,
)
.unwrap();
assert_eq!(staged.len(), 1);
assert!(staged[0].ends_with("Cargo.lock"), "{staged:?}");
assert!(!dir.path().join("Cargo.lock").exists());
}
#[test]
fn stage_glob_collects_files_under_a_tree_not_the_directory() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(
dir.path().join("Cargo.toml"),
indoc! {r#"
[package]
version = "1.0.0"
"#},
)
.unwrap();
commit_all(dir.path(), "init");
fs::create_dir_all(dir.path().join("src")).unwrap();
fs::write(dir.path().join("src/lib.rs"), "fn x() {}\n").unwrap();
let staged = super::assert_only_allowed(
dir.path(),
&[dir.path().join("Cargo.toml")],
&["src/**".into()],
super::IgnoredFiles::Skip,
)
.unwrap();
assert_eq!(staged.len(), 1);
assert!(staged[0].ends_with("src/lib.rs"), "{staged:?}");
assert!(!staged.iter().any(|path| path.ends_with("src")));
}
#[test]
fn ignored_workdir_paths_are_not_unexpected() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join(".gitignore"), "/target\n").unwrap();
fs::write(
dir.path().join("Cargo.toml"),
indoc! {r#"
[package]
version = "1.0.0"
"#},
)
.unwrap();
commit_all(dir.path(), "init");
fs::create_dir_all(dir.path().join("target/debug")).unwrap();
fs::write(dir.path().join("target/debug/verctl"), "bin\n").unwrap();
super::assert_only_allowed(
dir.path(),
&[dir.path().join("Cargo.toml")],
&[],
super::IgnoredFiles::Skip,
)
.unwrap();
}
#[test]
fn stage_ignored_opt_in_collects_gitignored_files() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join(".gitignore"), "/generated.rs\n").unwrap();
fs::write(
dir.path().join("Cargo.toml"),
indoc! {r#"
[package]
version = "1.0.0"
"#},
)
.unwrap();
commit_all(dir.path(), "init");
fs::write(dir.path().join("generated.rs"), "gen\n").unwrap();
let allowed = [dir.path().join("Cargo.toml")];
let off = super::assert_only_allowed(
dir.path(),
&allowed,
&["generated.rs".into()],
super::IgnoredFiles::Skip,
)
.unwrap();
assert!(off.is_empty(), "{off:?}");
let on = super::assert_only_allowed(
dir.path(),
&allowed,
&["generated.rs".into()],
super::IgnoredFiles::Include,
)
.unwrap();
assert_eq!(on.len(), 1);
assert!(on[0].ends_with("generated.rs"), "{on:?}");
}
#[test]
fn stage_ignored_recurses_a_gitignored_directory() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join(".gitignore"), "/dist\n").unwrap();
fs::write(
dir.path().join("Cargo.toml"),
indoc! {r#"
[package]
version = "1.0.0"
"#},
)
.unwrap();
commit_all(dir.path(), "init");
fs::create_dir_all(dir.path().join("dist")).unwrap();
fs::write(dir.path().join("dist/out.js"), "ok\n").unwrap();
let allowed = [dir.path().join("Cargo.toml")];
let staged = super::assert_only_allowed(
dir.path(),
&allowed,
&["dist/**".into()],
super::IgnoredFiles::Include,
)
.unwrap();
assert_eq!(staged.len(), 1);
assert!(staged[0].ends_with("dist/out.js"), "{staged:?}");
}
#[test]
fn stage_ignored_pathspec_does_not_collect_other_ignored_trees() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join(".gitignore"), "/dist\n/target\n").unwrap();
fs::write(
dir.path().join("Cargo.toml"),
indoc! {r#"
[package]
version = "1.0.0"
"#},
)
.unwrap();
commit_all(dir.path(), "init");
fs::create_dir_all(dir.path().join("dist")).unwrap();
fs::write(dir.path().join("dist/out.js"), "ok\n").unwrap();
fs::create_dir_all(dir.path().join("target/debug")).unwrap();
fs::write(dir.path().join("target/debug/verctl"), "bin\n").unwrap();
fs::write(dir.path().join("target/CACHEDIR.TAG"), "tag\n").unwrap();
let staged = super::assert_only_allowed(
dir.path(),
&[dir.path().join("Cargo.toml")],
&["dist/**".into()],
super::IgnoredFiles::Include,
)
.unwrap();
assert_eq!(staged.len(), 1, "{staged:?}");
assert!(staged[0].ends_with("dist/out.js"), "{staged:?}");
assert!(
!staged
.iter()
.any(|path| path.to_string_lossy().contains("target")),
"{staged:?}"
);
}
#[test]
fn write_commit_on_branch_removes_a_deleted_staged_path() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join("Cargo.lock"), "old\n").unwrap();
fs::write(
dir.path().join("Cargo.toml"),
indoc! {r#"
[package]
version = "1.0.0"
"#},
)
.unwrap();
commit_all(dir.path(), "init");
fs::remove_file(dir.path().join("Cargo.lock")).unwrap();
let staged = super::assert_only_allowed(
dir.path(),
&[dir.path().join("Cargo.toml")],
&["Cargo.lock".into()],
super::IgnoredFiles::Skip,
)
.unwrap();
let oid = write_commit(dir.path(), &staged).expect("deletion should commit");
let names = tree_names(dir.path(), &oid);
assert!(!names.iter().any(|name| name == "Cargo.lock"), "{names:?}");
assert!(names.iter().any(|name| name == "Cargo.toml"), "{names:?}");
}
#[test]
fn commit_only_lists_given_paths() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(
dir.path().join("Cargo.toml"),
indoc! {r#"
[package]
version = "1.0.0"
"#},
)
.unwrap();
let parent = commit_all(dir.path(), "init");
fs::write(
dir.path().join("Cargo.toml"),
indoc! {r#"
[package]
version = "1.0.1"
"#},
)
.unwrap();
fs::write(
dir.path().join("secret.env"),
indoc! {"
TOKEN=leak
"},
)
.unwrap();
let oid = write_commit(dir.path(), &[dir.path().join("Cargo.toml")]).expect("commit");
let names = tree_names(dir.path(), &oid);
assert!(names.iter().any(|name| name == "Cargo.toml"), "{names:?}");
assert!(!names.iter().any(|name| name == "secret.env"), "{names:?}");
assert_eq!(git(dir.path(), &["rev-parse", "HEAD"]), parent);
}
#[test]
fn dotted_relative_paths_stage() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(
dir.path().join("Cargo.toml"),
indoc! {r#"
[package]
version = "1.0.0"
"#},
)
.unwrap();
commit_all(dir.path(), "init");
fs::write(
dir.path().join("Cargo.toml"),
indoc! {r#"
[package]
version = "1.0.1"
"#},
)
.unwrap();
let oid =
write_commit(dir.path(), &[Path::new("./Cargo.toml").to_path_buf()]).expect("commit");
let names = tree_names(dir.path(), &oid);
assert!(names.iter().any(|name| name == "Cargo.toml"), "{names:?}");
}
#[tokio::test]
async fn push_keeps_the_token_out_of_the_error() {
let server = wiremock::MockServer::start().await;
wiremock::Mock::given(matchers::any())
.respond_with(
wiremock::ResponseTemplate::new(401)
.insert_header("WWW-Authenticate", r#"Basic realm="git""#),
)
.mount(&server)
.await;
let (dir, _) = fixture();
git(dir.path(), &["branch", "verctl/release/main"]);
let url = format!("{}/owner/repo.git", server.uri());
let token = "verctl-push-token-5f3a9c";
let error = task::spawn_blocking(move || {
super::push(&dir.path().join(".git"), &url, "verctl/release/main", token)
})
.await
.unwrap()
.unwrap_err();
let message = format!("{error:#}");
assert!(!message.contains(token), "{message}");
let expected = format!("Basic {}", base64(&format!("x-access-token:{token}")));
let requests = server.received_requests().await.unwrap();
assert!(
requests.iter().any(|request| {
request
.headers
.get("authorization")
.is_some_and(|value| value.as_bytes() == expected.as_bytes())
}),
"no request carried the token as Basic credentials"
);
}
fn base64(text: &str) -> String {
const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::new();
for chunk in text.as_bytes().chunks(3) {
let bytes = [
chunk[0],
chunk.get(1).copied().unwrap_or(0),
chunk.get(2).copied().unwrap_or(0),
];
let joined = u32::from(bytes[0]) << 16 | u32::from(bytes[1]) << 8 | u32::from(bytes[2]);
for index in 0..4 {
if index <= chunk.len() {
let sextet = (joined >> (18 - 6 * index)) & 0x3f;
out.push(char::from(ALPHABET[usize::try_from(sextet).unwrap()]));
} else {
out.push('=');
}
}
}
out
}
#[test]
fn the_commit_applies_clean_filters() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join(".gitattributes"), "*.md text\n").unwrap();
fs::write(dir.path().join("CHANGELOG.md"), "old\n").unwrap();
commit_all(dir.path(), "init");
fs::write(dir.path().join("CHANGELOG.md"), "a\r\nb\r\n").unwrap();
let oid = write_commit(dir.path(), &[dir.path().join("CHANGELOG.md")]).expect("commit");
let blob = format!("{oid}:CHANGELOG.md");
assert_eq!(git(dir.path(), &["cat-file", "-p", &blob]), "a\nb");
}
#[test]
fn a_configured_identity_wins_over_the_fallback() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
git(dir.path(), &["config", "user.name", "Configured Name"]);
git(
dir.path(),
&["config", "user.email", "configured@example.com"],
);
fs::write(dir.path().join("Cargo.toml"), "version = 1\n").unwrap();
commit_all(dir.path(), "init");
fs::write(dir.path().join("Cargo.toml"), "version = 2\n").unwrap();
let oid = write_commit(dir.path(), &[dir.path().join("Cargo.toml")]).expect("commit");
let configured = "Configured Name <configured@example.com>";
assert_eq!(
git(
dir.path(),
&["log", "-1", "--format=%an <%ae>|%cn <%ce>", &oid]
),
format!("{configured}|{configured}")
);
assert_eq!(
git(
dir.path(),
&[
"log",
"-g",
"-1",
"--format=%gn <%ge>",
"refs/heads/verctl/release/main",
],
),
configured
);
}
#[test]
fn a_workdir_found_from_dot_resolves_paths() {
let repo = super::discover(Path::new(".")).unwrap();
let workdir = super::absolute_workdir(&repo).unwrap();
assert!(workdir.is_absolute(), "{}", workdir.display());
assert_eq!(
super::workdir_rel(&workdir, Path::new("./Cargo.toml")).unwrap(),
Path::new("Cargo.toml")
);
}
#[cfg(unix)]
#[test]
fn a_symlinked_workdir_takes_canonical_paths() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
fs::write(dir.path().join("Cargo.toml"), "version = 1\n").unwrap();
commit_all(dir.path(), "init");
fs::write(dir.path().join("Cargo.toml"), "version = 2\n").unwrap();
let links = tempfile::TempDir::new().unwrap();
let link = links.path().join("checkout");
symlink(dir.path(), &link).unwrap();
let canonical = dir.path().canonicalize().unwrap().join("Cargo.toml");
let workdir = super::absolute_workdir(&super::discover(&link).unwrap()).unwrap();
assert_eq!(
super::workdir_rel(&workdir, &canonical).unwrap(),
Path::new("Cargo.toml")
);
assert_eq!(
super::workdir_rel(&workdir, &link.join("Cargo.toml")).unwrap(),
Path::new("Cargo.toml")
);
}
fn write_commit(dir: &Path, paths: &[PathBuf]) -> Option<String> {
let repo = super::discover(dir).unwrap();
let workdir = super::absolute_workdir(&repo).unwrap();
let parent = repo.head_commit().unwrap();
super::write_commit_on_branch(
&repo,
&workdir,
&parent,
"verctl/release/main",
"chore",
paths,
)
.unwrap()
.map(|id| id.to_string())
}
fn stock() -> Vec<String> {
super::candidate_names(None)
}
fn fixture() -> (tempfile::TempDir, String) {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
let sha = commit_all(dir.path(), "init");
(dir, sha)
}
fn add_origin(dir: &Path) {
git(
dir,
&[
"remote",
"add",
"origin",
"https://github.com/victor-software-house/verctl.git",
],
);
}
fn track(dir: &Path, name: &str, sha: &str) {
git(
dir,
&["update-ref", &format!("refs/remotes/origin/{name}"), sha],
);
}
fn set_origin_head(dir: &Path, name: &str) {
git(
dir,
&[
"symbolic-ref",
"refs/remotes/origin/HEAD",
&format!("refs/remotes/origin/{name}"),
],
);
}
fn prove(root: &Path, candidates: &[String]) -> anyhow::Result<()> {
match super::prove_default_history(root, candidates)? {
None => Ok(()),
Some(off) => anyhow::bail!(off),
}
}
#[test]
fn candidate_names_are_base_ref_then_main_master() {
assert_eq!(super::candidate_names(None), ["main", "master"]);
assert_eq!(super::candidate_names(Some("")), ["main", "master"]);
assert_eq!(super::candidate_names(Some(" ")), ["main", "master"]);
assert_eq!(
super::candidate_names(Some("trunk")),
["trunk", "main", "master"]
);
assert_eq!(super::candidate_names(Some("main")), ["main", "master"]);
assert_eq!(
super::candidate_names(Some("release/1.0")),
["release/1.0", "main", "master"]
);
}
#[test]
fn no_repository_refuses() {
let dir = tempfile::TempDir::new().unwrap();
let err = prove(dir.path(), &stock()).unwrap_err();
assert!(
format!("{err:#}").contains("release cannot prove HEAD"),
"{err:#}"
);
assert!(format!("{err:#}").contains("no git repository"), "{err:#}");
}
#[test]
fn no_head_commit_refuses() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
let err = prove(dir.path(), &stock()).unwrap_err();
assert!(format!("{err:#}").contains("HEAD has no commit"), "{err:#}");
}
#[test]
fn a_missing_origin_refuses() {
let (dir, _) = fixture();
let err = prove(dir.path(), &stock()).unwrap_err();
assert!(format!("{err:#}").contains("no `origin` remote"), "{err:#}");
}
#[test]
fn head_on_origin_main_is_ok() {
let (dir, sha) = fixture();
add_origin(dir.path());
track(dir.path(), "main", &sha);
prove(dir.path(), &stock()).unwrap();
}
#[test]
fn head_sha_is_the_peeled_head_commit() {
let (dir, sha) = fixture();
assert_eq!(super::head_sha(dir.path()).unwrap(), sha);
}
#[test]
fn origin_master_without_head_is_ok() {
let (dir, sha) = fixture();
add_origin(dir.path());
track(dir.path(), "master", &sha);
prove(dir.path(), &stock()).unwrap();
}
#[test]
fn origin_head_to_non_main_is_ok() {
let (dir, sha) = fixture();
add_origin(dir.path());
track(dir.path(), "trunk", &sha);
set_origin_head(dir.path(), "trunk");
prove(dir.path(), &stock()).unwrap();
}
#[test]
fn base_ref_trunk_without_origin_head_is_ok() {
let (dir, sha) = fixture();
add_origin(dir.path());
track(dir.path(), "trunk", &sha);
prove(dir.path(), &super::candidate_names(Some("trunk"))).unwrap();
}
#[test]
fn origin_without_default_tracking_ref_fails() {
let (dir, _) = fixture();
add_origin(dir.path());
let err = prove(dir.path(), &stock()).unwrap_err();
assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
}
#[test]
fn origin_trunk_alone_needs_head_or_base_ref() {
let (dir, sha) = fixture();
add_origin(dir.path());
track(dir.path(), "trunk", &sha);
let err = prove(dir.path(), &stock()).unwrap_err();
assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
prove(dir.path(), &super::candidate_names(Some("trunk"))).unwrap();
set_origin_head(dir.path(), "trunk");
prove(dir.path(), &stock()).unwrap();
}
#[test]
fn origin_hotfix_alone_is_not_the_default() {
let (dir, sha) = fixture();
add_origin(dir.path());
track(dir.path(), "hotfix", &sha);
let err = prove(dir.path(), &stock()).unwrap_err();
assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
}
#[test]
fn unpeelable_origin_head_does_not_fall_through_to_main() {
let (dir, sha) = fixture();
add_origin(dir.path());
track(dir.path(), "main", &sha);
set_origin_head(dir.path(), "trunk");
let err = prove(dir.path(), &stock()).unwrap_err();
assert!(format!("{err:#}").contains("origin/trunk"), "{err:#}");
}
#[test]
fn github_https_url_has_no_credentials() {
let url = super::github_https_url("victor-software-house/qctl");
assert_eq!(url, "https://github.com/victor-software-house/qctl.git");
let lower = url.to_ascii_lowercase();
assert!(!lower.contains("bearer"), "{url}");
assert!(!lower.contains("token"), "{url}");
assert!(!lower.contains("x-access-token"), "{url}");
}
#[test]
fn github_git_user_is_x_access_token() {
assert_eq!(super::github_git_user(), "x-access-token");
}
#[test]
fn ensure_origin_head_skips_fetch_when_the_ref_exists() {
let (dir, sha) = fixture();
git(
dir.path(),
&["remote", "add", "origin", "https://127.0.0.1:1/nope.git"],
);
track(dir.path(), "main", &sha);
super::ensure_origin_head(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
assert_eq!(
git(dir.path(), &["symbolic-ref", "refs/remotes/origin/HEAD"]),
"refs/remotes/origin/main"
);
}
#[test]
fn ensure_origin_head_fetches_a_missing_ref_from_origin() {
let upstream_dir = tempfile::TempDir::new().unwrap();
init(upstream_dir.path());
commit_all(upstream_dir.path(), "init");
let work_dir = tempfile::TempDir::new().unwrap();
init(work_dir.path());
commit_all(work_dir.path(), "local");
let url = format!("file://{}", upstream_dir.path().display());
git(work_dir.path(), &["remote", "add", "origin", &url]);
super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
git(
work_dir.path(),
&["rev-parse", "--verify", "refs/remotes/origin/main^{commit}"],
);
assert_eq!(
git(
work_dir.path(),
&["symbolic-ref", "refs/remotes/origin/HEAD"]
),
"refs/remotes/origin/main"
);
}
#[test]
fn a_shallow_clone_gets_the_history_that_holds_the_tagged_commit() {
let upstream = tempfile::TempDir::new().unwrap();
init(upstream.path());
write_version(upstream.path(), "0.0.1");
commit_all(upstream.path(), "chore: start");
write_version(upstream.path(), "0.0.2");
let set = commit_all(upstream.path(), "chore(release): version packages");
fs::write(upstream.path().join("README"), "later\n").unwrap();
commit_all(upstream.path(), "docs: later");
let parent = tempfile::TempDir::new().unwrap();
let url = format!("file://{}", upstream.path().display());
git(
parent.path(),
&["clone", "-q", "--depth", "1", &url, "work"],
);
let work = parent.path().join("work");
let manifest = work.join("Cargo.toml");
let error = tagged_commit(&work, &manifest, &set, &version_line).unwrap_err();
assert!(format!("{error:#}").contains("shallow"), "{error:#}");
super::ensure_full_history(&work, "main", &super::FetchDefault::Origin).unwrap();
let found = tagged_commit(&work, &manifest, &set, &version_line).unwrap();
assert_eq!(found, Some(VersionCommit { sha: set, depth: 1 }));
}
#[test]
fn a_full_clone_is_not_fetched_again() {
let dir = tempfile::TempDir::new().unwrap();
init(dir.path());
commit_all(dir.path(), "init");
git(
dir.path(),
&["remote", "add", "origin", "file:///nonexistent/verctl"],
);
super::ensure_full_history(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
}
#[test]
fn a_pull_request_merge_checkout_compares_against_its_merge_base() {
let upstream = tempfile::TempDir::new().unwrap();
let up = upstream.path();
init(up);
write_version(up, "0.0.1");
commit_all(up, "chore: start");
write_version(up, "0.0.2");
commit_all(up, "chore(release): version packages");
git(up, &["checkout", "-q", "-b", "pr"]);
fs::write(up.join("README"), "change\n").unwrap();
commit_all(up, "docs: change");
git(up, &["checkout", "-q", "--detach", "main"]);
git(
up,
&["merge", "-q", "--no-ff", "pr", "-m", "Merge pr into main"],
);
git(up, &["update-ref", "refs/pull/1/merge", "HEAD"]);
git(up, &["checkout", "-q", "main"]);
write_version(up, "0.0.3");
commit_all(up, "chore(release): version packages");
let work = tempfile::TempDir::new().unwrap();
let dir = work.path();
init(dir);
let url = format!("file://{}", up.display());
git(dir, &["remote", "add", "origin", &url]);
git(
dir,
&[
"fetch",
"-q",
"--depth=1",
"origin",
"+refs/pull/1/merge:refs/remotes/pull/1/merge",
],
);
git(
dir,
&["checkout", "-q", "--detach", "refs/remotes/pull/1/merge"],
);
assert_eq!(git(dir, &["rev-parse", "--is-shallow-repository"]), "true");
let manifest = [Path::new("Cargo.toml")];
let candidates = ["main".to_owned()];
let error = super::files_on_merge_base(dir, &manifest, &candidates).unwrap_err();
assert!(
format!("{error:#}").contains("fetch the default branch"),
"{error:#}"
);
super::ensure_comparable(dir, "main", &super::FetchDefault::Origin).unwrap();
let files = super::files_on_merge_base(dir, &manifest, &candidates).unwrap();
let base = files[0].as_deref().expect("Cargo.toml at the merge-base");
assert_eq!(version_line(base).as_deref(), Some("0.0.2"));
}
#[test]
fn release_candidates_put_the_event_default_after_the_configured_branch() {
assert_eq!(
super::release_candidate_names(None, Some("trunk"), Some("develop")),
["trunk", "main", "master", "develop"]
);
assert_eq!(
super::release_candidate_names(Some("stable"), Some("trunk"), None),
["stable", "trunk", "main", "master"]
);
assert_eq!(
super::release_candidate_names(None, Some("main"), Some("main")),
["main", "master"]
);
assert_eq!(
super::release_candidate_names(None, None, Some("develop")),
["main", "master", "develop"]
);
}
#[test]
fn a_full_clone_with_the_branch_is_not_fetched_for_a_comparison() {
let (dir, sha) = fixture();
git(
dir.path(),
&["remote", "add", "origin", "file:///nonexistent/verctl"],
);
track(dir.path(), "main", &sha);
super::ensure_comparable(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
}
#[test]
fn a_full_clone_without_the_branch_fetches_it_for_a_comparison() {
let upstream = tempfile::TempDir::new().unwrap();
init(upstream.path());
let tip = commit_all(upstream.path(), "init");
let work = tempfile::TempDir::new().unwrap();
init(work.path());
commit_all(work.path(), "local");
let url = format!("file://{}", upstream.path().display());
git(work.path(), &["remote", "add", "origin", &url]);
super::ensure_comparable(work.path(), "main", &super::FetchDefault::Origin).unwrap();
assert_eq!(
git(work.path(), &["rev-parse", "refs/remotes/origin/main"]),
tip
);
}
#[test]
fn fetch_one_branch_does_not_set_depth() {
let src = include_str!("lib.rs");
let prod = src.split("#[cfg(test)]").next().expect("production");
assert!(
!prod.contains("opts.depth"),
"a depth-limited fetch leaves the tip parentless so graph_descendant_of cannot prove ancestry"
);
}
#[test]
fn configured_default_branch_is_only_verctl_default_branch() {
let src = include_str!("lib.rs");
let start = src
.find("pub fn configured_default_branch")
.expect("configured_default_branch");
let rest = &src[start..];
let end = rest
.find("pub fn ensure_origin_head")
.expect("ensure_origin_head");
let body = &rest[..end];
assert!(!body.contains("GITHUB_BASE_REF"), "{body}");
assert!(!body.contains("env_base_ref"), "{body}");
}
#[test]
fn fetched_default_branch_keeps_parents_for_ancestry() {
let upstream_dir = tempfile::TempDir::new().unwrap();
init(upstream_dir.path());
commit_all(upstream_dir.path(), "A");
let work_dir = tempfile::TempDir::new().unwrap();
init(work_dir.path());
let url = format!("file://{}", upstream_dir.path().display());
git(work_dir.path(), &["remote", "add", "origin", &url]);
super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
let first = git(work_dir.path(), &["rev-parse", "refs/remotes/origin/main"]);
git(
work_dir.path(),
&["update-ref", "--no-deref", "HEAD", &first],
);
fs::write(upstream_dir.path().join("b.txt"), "b\n").unwrap();
commit_all(upstream_dir.path(), "B");
fs::write(upstream_dir.path().join("c.txt"), "c\n").unwrap();
commit_all(upstream_dir.path(), "C");
git(
work_dir.path(),
&["update-ref", "-d", "refs/remotes/origin/main"],
);
git(
work_dir.path(),
&["symbolic-ref", "--delete", "refs/remotes/origin/HEAD"],
);
super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
prove(work_dir.path(), &stock()).unwrap();
}
#[test]
fn origin_head_wins_over_main_when_they_differ() {
let (dir, first) = fixture();
add_origin(dir.path());
fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
let second = commit_all(dir.path(), "ahead");
track(dir.path(), "main", &first);
track(dir.path(), "trunk", &second);
set_origin_head(dir.path(), "trunk");
prove(dir.path(), &stock()).unwrap();
}
#[test]
fn head_off_default_history_fails() {
let (dir, first) = fixture();
add_origin(dir.path());
track(dir.path(), "main", &first);
git(dir.path(), &["update-ref", "refs/heads/other", &first]);
git(dir.path(), &["symbolic-ref", "HEAD", "refs/heads/other"]);
fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
let head = commit_all(dir.path(), "ahead");
let off = super::prove_default_history(dir.path(), &stock())
.unwrap()
.unwrap();
assert!(off.contains("not an ancestor"), "{off}");
assert!(off.contains(&head), "{off}");
assert!(off.contains(&first), "{off}");
}
#[test]
fn workflows_at_the_default_tip_match() {
let (dir, _) = fixture();
fs::create_dir_all(dir.path().join(".github/workflows")).unwrap();
fs::write(dir.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
let release = commit_all(dir.path(), "chore(release): version packages");
fs::write(dir.path().join("README"), "later\n").unwrap();
let tip = commit_all(dir.path(), "docs: later");
add_origin(dir.path());
track(dir.path(), "main", &tip);
git(dir.path(), &["update-ref", "--no-deref", "HEAD", &release]);
assert_eq!(super::workflows_differ(dir.path()).unwrap(), None);
}
#[test]
fn a_workflow_changed_since_the_release_commit_differs() {
let (dir, _) = fixture();
fs::create_dir_all(dir.path().join(".github/workflows")).unwrap();
fs::write(dir.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
let release = commit_all(dir.path(), "chore(release): version packages");
fs::write(
dir.path().join(".github/workflows/ci.yml"),
"on: [push, pull_request]\n",
)
.unwrap();
let tip = commit_all(dir.path(), "ci: run on pull requests");
add_origin(dir.path());
track(dir.path(), "main", &tip);
git(dir.path(), &["update-ref", "--no-deref", "HEAD", &release]);
let differs = super::workflows_differ(dir.path()).unwrap().unwrap();
assert!(differs.contains(".github/workflows/"), "{differs}");
assert!(differs.contains(&release), "{differs}");
assert!(differs.contains(&tip), "{differs}");
let (bare, first) = fixture();
add_origin(bare.path());
fs::create_dir_all(bare.path().join(".github/workflows")).unwrap();
fs::write(bare.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
let added = commit_all(bare.path(), "ci: add");
track(bare.path(), "main", &added);
git(bare.path(), &["update-ref", "--no-deref", "HEAD", &first]);
assert!(super::workflows_differ(bare.path()).unwrap().is_some());
}
#[test]
fn the_workflows_compared_are_those_of_the_run_commit() {
let (dir, _) = fixture();
fs::create_dir_all(dir.path().join(".github/workflows")).unwrap();
fs::write(dir.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
let release = commit_all(dir.path(), "chore(release): version packages");
fs::write(
dir.path().join(".github/workflows/ci.yml"),
"on: [push, pull_request]\n",
)
.unwrap();
let tip = commit_all(dir.path(), "ci: run on pull requests");
add_origin(dir.path());
track(dir.path(), "main", &tip);
git(dir.path(), &["update-ref", "--no-deref", "HEAD", &release]);
assert_eq!(
super::workflows_differ_at(dir.path(), Some(&tip)).unwrap(),
None
);
let at_head = super::workflows_differ_at(dir.path(), Some(&"0".repeat(40)))
.unwrap()
.unwrap();
assert!(at_head.contains(&format!("at HEAD {release}")), "{at_head}");
let unset = super::workflows_differ_at(dir.path(), None)
.unwrap()
.unwrap();
assert!(unset.contains(&format!("at HEAD {release}")), "{unset}");
let at_run = super::workflows_differ_at(dir.path(), Some(&release))
.unwrap()
.unwrap();
assert!(
at_run.contains(&format!("at GITHUB_SHA {release}")),
"{at_run}"
);
}
#[test]
fn head_behind_origin_main_is_ok() {
let (dir, first) = fixture();
add_origin(dir.path());
fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
let second = commit_all(dir.path(), "ahead");
track(dir.path(), "main", &second);
git(dir.path(), &["update-ref", "--no-deref", "HEAD", &first]);
prove(dir.path(), &stock()).unwrap();
}
}