1#[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::path::{Component, Path, PathBuf};
11use std::sync::atomic::AtomicBool;
12use std::time::Duration;
13use std::{env, fmt, fs, path};
14
15use anyhow::{Context, Result, anyhow, bail, ensure};
16use gix::actor::Signature;
17use gix::bstr::{BString, ByteSlice};
18use gix::credentials::helper::Action;
19use gix::credentials::protocol::Outcome;
20use gix::date::Time;
21use gix::dir::entry::Status;
22use gix::dir::walk::EmissionMode;
23use gix::filter::Pipeline;
24use gix::index::State;
25use gix::index::entry::Mode;
26use gix::objs::Commit;
27use gix::objs::tree::EntryKind;
28use gix::progress::Discard;
29use gix::refs::transaction::{PreviousValue, RefEdit};
30use gix::refs::{FullName, Target};
31use gix::remote::fetch::{Shallow, Tags};
32use gix::remote::{Direction, ref_map};
33use gix::sec::identity::Account;
34use gix::sec::trust::{DefaultForLevel, Mapping};
35use gix::sec::{Permission, Trust};
36use gix::status::tree_index::TrackRenames;
37use gix::status::{UntrackedFiles, index_worktree};
38use gix::worktree::stack::state::ignore::Source;
39use gix::{open, status};
40use semver::Version;
41use verctl_core::repo::Repo;
42use verctl_core::{env as github_env, lookup, process};
43
44#[must_use]
46pub fn current_branch(root: &Path) -> Option<String> {
47 let repo = repo_covering(root)?;
48 repo.head_id().ok()?;
49 let name = repo.head_name().ok()??;
50 Some(name.shorten().to_string())
51}
52
53pub fn head_sha(root: &Path) -> Result<String> {
60 let repo = discover(root).context("release needs a git repository to name the tag")?;
61 let commit = repo
62 .head_commit()
63 .context("release needs HEAD to name the tag")?;
64 Ok(commit.id().to_string())
65}
66
67pub fn head_contains_commit(root: &Path, sha: &str) -> Result<bool> {
78 let repo = discover(root).context("checking commit ancestry needs a git repository")?;
79 let head = repo
80 .head_commit()
81 .context("checking commit ancestry needs HEAD")?
82 .id();
83 let target =
84 gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
85 if head == target {
86 return Ok(true);
87 }
88 if repo.find_commit(target).is_err() {
89 return Ok(false);
90 }
91 let base = repo.merge_base(head, target).with_context(|| {
92 format!("cannot tell whether HEAD contains commit {sha}; fetch the full history")
93 })?;
94 Ok(base.is_some_and(|base| base == target))
95}
96
97const NEED_FULL_FETCH: &str =
99 "cannot compare versions against the default branch (need a full fetch, not a shallow clone)";
100
101pub fn files_on_merge_base(
120 root: &Path,
121 rels: &[&Path],
122 candidates: &[String],
123) -> Result<Vec<Option<String>>> {
124 let Some(repo) = repo_covering(root) else {
125 return Ok(vec![None; rels.len()]);
126 };
127 let Some(upstream) = default_upstream_commit(&repo, candidates)? else {
128 return Ok(vec![None; rels.len()]);
129 };
130 let head = repo
131 .head_commit()
132 .context("cannot compare versions (need HEAD)")?;
133 let base = repo
134 .merge_base(head.id(), upstream)
135 .context(NEED_FULL_FETCH)?
136 .context(NEED_FULL_FETCH)?;
137 let tree = repo.find_commit(base)?.tree()?;
138 let workdir = repo.workdir().map(Path::to_path_buf);
139 Ok(rels
140 .iter()
141 .map(|rel| git_path(root, rel, workdir.as_deref()).and_then(|path| blob_at(&tree, &path)))
142 .collect())
143}
144
145fn git_path(root: &Path, rel: &Path, workdir: Option<&Path>) -> Option<PathBuf> {
152 let abs = if rel.is_absolute() {
153 rel.canonicalize().ok().or_else(|| {
154 rel.parent()?
155 .canonicalize()
156 .ok()
157 .map(|dir| dir.join(rel.file_name().unwrap_or_default()))
158 })?
159 } else {
160 let inside: PathBuf = rel
161 .components()
162 .filter(|part| !matches!(part, Component::CurDir))
163 .collect();
164 root.canonicalize().ok()?.join(inside)
165 };
166 let workdir = workdir?.canonicalize().ok()?;
167 abs.strip_prefix(workdir).ok().map(Path::to_path_buf)
168}
169
170#[derive(Debug)]
174pub struct MergeBase {
175 repo: gix::Repository,
176 workdir: PathBuf,
177 files: BTreeMap<String, (gix::ObjectId, EntryKind)>,
178 changed: BTreeSet<String>,
179}
180
181impl MergeBase {
182 pub fn read(root: &Path, candidates: &[String]) -> Result<Option<Self>> {
196 let Some(repo) = repo_covering(root) else {
197 return Ok(None);
198 };
199 let Some(upstream) = default_upstream_commit(&repo, candidates)? else {
200 return Ok(None);
201 };
202 let (files, head_files) = {
203 let head = repo
204 .head_commit()
205 .context("cannot compare the Version PR (need HEAD)")?;
206 let base = repo
207 .merge_base(head.id(), upstream)
208 .context(NEED_FULL_FETCH)?
209 .context(NEED_FULL_FETCH)?;
210 (
211 files_of(&repo.find_commit(base)?.tree()?)?,
212 files_of(&head.tree()?)?,
213 )
214 };
215 let workdir = repo
216 .workdir()
217 .context("the Version PR check needs a working tree")?
218 .canonicalize()
219 .context("the working tree")?;
220 let mut candidates: BTreeSet<String> = files
221 .keys()
222 .chain(head_files.keys())
223 .filter(|path| files.get(*path) != head_files.get(*path))
224 .cloned()
225 .collect();
226 candidates.extend(
227 status_paths(&repo, Vec::new(), IgnoredFiles::Skip)
228 .context("git status")?
229 .into_iter()
230 .filter(|path| files.contains_key(path) || head_files.contains_key(path)),
231 );
232 let mut merge_base = Self {
233 repo,
234 workdir,
235 files,
236 changed: BTreeSet::new(),
237 };
238 for path in candidates {
239 if merge_base.differs(&path, head_files.get(&path))? {
240 merge_base.changed.insert(path);
241 }
242 }
243 Ok(Some(merge_base))
244 }
245
246 fn differs(&self, rel: &str, head: Option<&(gix::ObjectId, EntryKind)>) -> Result<bool> {
252 let base = self.files.get(rel);
253 let gitlink = |entry: Option<&(gix::ObjectId, EntryKind)>| {
254 entry.is_some_and(|(_, kind)| *kind == EntryKind::Commit)
255 };
256 if gitlink(base) || gitlink(head) {
257 return Ok(base != head);
258 }
259 let expected = match base {
260 None => Worktree::Missing,
261 Some((_, EntryKind::Link)) => Worktree::Link(self.base_bytes(rel)?.unwrap_or_default()),
262 Some(_) => Worktree::File(self.base_bytes(rel)?.unwrap_or_default()),
263 };
264 Ok(expected != Worktree::read(&self.workdir.join(rel))?)
265 }
266
267 #[must_use]
269 pub fn workdir(&self) -> &Path {
270 &self.workdir
271 }
272
273 #[must_use]
277 pub fn changed(&self) -> &BTreeSet<String> {
278 &self.changed
279 }
280
281 pub fn base_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
287 let Some((oid, _)) = self.files.get(rel) else {
288 return Ok(None);
289 };
290 let blob = self
291 .repo
292 .find_blob(*oid)
293 .with_context(|| format!("{rel} at the merge-base"))?;
294 Ok(Some(blob.data.clone()))
295 }
296
297 pub fn worktree_bytes(&self, rel: &str) -> Result<Option<Vec<u8>>> {
303 read_optional(&self.workdir.join(rel))
304 }
305
306 pub fn write_to(&self, dir: &Path) -> Result<()> {
319 use std::os::unix::fs::PermissionsExt as _;
320 for (rel, (_, kind)) in &self.files {
321 let mode = match kind {
322 EntryKind::Blob => 0o644,
323 EntryKind::BlobExecutable => 0o755,
324 EntryKind::Link | EntryKind::Tree | EntryKind::Commit => continue,
325 };
326 let path = dir.join(rel);
327 if let Some(parent) = path.parent() {
328 fs::create_dir_all(parent)
329 .with_context(|| format!("create {}", parent.display()))?;
330 }
331 let bytes = self.base_bytes(rel)?.unwrap_or_default();
332 fs::write(&path, bytes).with_context(|| format!("write {}", path.display()))?;
333 fs::set_permissions(&path, Permissions::from_mode(mode))
334 .with_context(|| format!("chmod {}", path.display()))?;
335 }
336 Ok(())
337 }
338}
339
340#[derive(Debug, PartialEq, Eq)]
343enum Worktree {
344 Missing,
345 Link(Vec<u8>),
346 File(Vec<u8>),
347}
348
349impl Worktree {
350 fn read(path: &Path) -> Result<Self> {
351 use std::os::unix::ffi::OsStrExt as _;
352 let metadata = match fs::symlink_metadata(path) {
353 Ok(metadata) => metadata,
354 Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Self::Missing),
355 Err(error) => return Err(error).with_context(|| path.display().to_string()),
356 };
357 if metadata.file_type().is_symlink() {
358 let target = fs::read_link(path).with_context(|| path.display().to_string())?;
359 return Ok(Self::Link(target.as_os_str().as_bytes().to_vec()));
360 }
361 let bytes = fs::read(path).with_context(|| path.display().to_string())?;
362 Ok(Self::File(bytes))
363 }
364}
365
366pub fn read_optional(path: &Path) -> Result<Option<Vec<u8>>> {
372 match fs::read(path) {
373 Ok(bytes) => Ok(Some(bytes)),
374 Err(error) if error.kind() == ErrorKind::NotFound => Ok(None),
375 Err(error) => Err(error).with_context(|| path.display().to_string()),
376 }
377}
378
379fn files_of(tree: &gix::Tree<'_>) -> Result<BTreeMap<String, (gix::ObjectId, EntryKind)>> {
383 Ok(tree
384 .traverse()
385 .breadthfirst
386 .files()?
387 .into_iter()
388 .filter(|entry| !entry.mode.is_tree())
389 .map(|entry| {
390 (
391 entry.filepath.to_str_lossy().into_owned(),
392 (entry.oid, entry.mode.kind()),
393 )
394 })
395 .collect())
396}
397
398pub fn file_at(root: &Path, sha: &str, path: &Path) -> Result<Option<String>> {
406 let repo = discover(root).context("reading a file at a commit needs a git repository")?;
407 let rel = git_path(root, path, repo.workdir())
408 .with_context(|| format!("{} is not in the repository", path.display()))?;
409 let id = gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
410 let commit = repo
411 .find_commit(id)
412 .with_context(|| format!("commit {sha} is not in the repository"))?;
413 Ok(blob_at(&commit.tree()?, &rel))
414}
415
416fn blob_at(tree: &gix::Tree<'_>, rel: &Path) -> Option<String> {
417 let entry = tree.lookup_entry_by_path(rel).ok()??;
418 let blob = entry.object().ok()?.try_into_blob().ok()?;
419 Some(String::from_utf8_lossy(&blob.data).into_owned())
420}
421
422pub fn files_named_at(
430 root: &Path,
431 sha: &str,
432 dir: &Path,
433 file_name: &str,
434) -> Result<Vec<(String, String)>> {
435 let repo = discover(root).context("reading files at a commit needs a git repository")?;
436 let dir = dir
437 .canonicalize()
438 .with_context(|| format!("resolve {}", dir.display()))?;
439 let dir_rel = git_path(root, &dir, repo.workdir())
440 .with_context(|| format!("{} is not in the repository", dir.display()))?;
441 let id = gix::ObjectId::from_hex(sha.as_bytes()).with_context(|| format!("commit {sha}"))?;
442 let commit = repo
443 .find_commit(id)
444 .with_context(|| format!("commit {sha} is not in the repository"))?;
445 let mut found = Vec::new();
446 for (rel, (oid, kind)) in files_of(&commit.tree()?)? {
447 if !matches!(kind, EntryKind::Blob | EntryKind::BlobExecutable) {
448 continue;
449 }
450 let path = Path::new(&rel);
451 if path.file_name().and_then(|name| name.to_str()) != Some(file_name) {
452 continue;
453 }
454 let under_dir = if dir_rel.as_os_str().is_empty() {
455 path
456 } else if let Ok(stripped) = path.strip_prefix(&dir_rel) {
457 stripped
458 } else {
459 continue;
460 };
461 let blob = repo
462 .find_object(oid)
463 .with_context(|| format!("read {rel} at commit {sha}"))?
464 .try_into_blob()
465 .with_context(|| format!("{rel} at commit {sha} is not a blob"))?;
466 found.push((
467 under_dir.to_string_lossy().into_owned(),
468 String::from_utf8_lossy(&blob.data).into_owned(),
469 ));
470 }
471 Ok(found)
472}
473
474pub fn default_tip(root: &Path, candidates: &[String]) -> Result<String> {
483 let repo = repo_covering(root).with_context(|| {
484 format!(
485 "cannot resolve the default branch: no git repository covers {}",
486 root.display()
487 )
488 })?;
489 let tip = default_upstream_commit(&repo, candidates)?.context(
490 "cannot resolve the default branch: there is no `origin` remote; add it and fetch the default branch",
491 )?;
492 Ok(tip.to_string())
493}
494
495pub fn origin_url(root: &Path) -> Result<String> {
502 let repo = discover(root).context("open git repository")?;
503 let remote = repo.find_remote("origin").context("git remote origin")?;
504 let url = remote.url(Direction::Fetch).context("origin has no URL")?;
505 Ok(url.to_bstring().to_str_lossy().into_owned())
506}
507
508#[derive(Debug, Clone, PartialEq, Eq)]
510pub struct AddedBy {
511 pub sha: String,
513 pub subject: String,
515}
516
517pub fn added_by(root: &Path, path: &Path) -> Result<Option<AddedBy>> {
549 let Ok(repo) = discover(root) else {
550 return Ok(None);
551 };
552 let Ok(head) = repo.head_commit() else {
553 return Ok(None);
554 };
555 added_from(&repo, root, path, head)
556}
557
558pub fn added_by_from(root: &Path, path: &Path, start: &str) -> Result<Option<AddedBy>> {
569 let Ok(repo) = discover(root) else {
570 return Ok(None);
571 };
572 let id =
573 gix::ObjectId::from_hex(start.as_bytes()).with_context(|| format!("commit {start}"))?;
574 let commit = repo
575 .find_commit(id)
576 .with_context(|| format!("commit {start} is not in the repository"))?;
577 added_from(&repo, root, path, commit)
578}
579
580fn added_from(
581 repo: &gix::Repository,
582 root: &Path,
583 path: &Path,
584 head: gix::Commit<'_>,
585) -> Result<Option<AddedBy>> {
586 let Some(rel) = git_path(root, path, repo.workdir()) else {
587 return Ok(None);
588 };
589 if !has_path(&head, &rel)? {
590 return Ok(None);
591 }
592 let boundary: Vec<gix::ObjectId> = repo
593 .shallow_commits()?
594 .map_or_default(|commits| commits.iter().copied().collect());
595 let mut commit = head;
596 let mut named_merge = None;
597 loop {
598 let parents: Vec<gix::ObjectId> = if boundary.contains(&commit.id().detach()) {
599 Vec::new()
600 } else {
601 commit.parent_ids().map(gix::Id::detach).collect()
602 };
603 if parents.is_empty() && !boundary.is_empty() {
604 return Ok(None);
605 }
606 let mut holder = None;
607 for (index, id) in parents.into_iter().enumerate() {
608 let Ok(parent) = repo.find_commit(id) else {
609 return Ok(None);
610 };
611 if has_path(&parent, &rel)? {
612 holder = Some((index, parent));
613 break;
614 }
615 }
616 let added = named(&commit)?;
617 let Some((index, parent)) = holder else {
618 return Ok(Some(match named_merge {
619 Some(merge) if pull_request_number(&added.subject).is_none() => merge,
620 Some(_) | None => added,
621 }));
622 };
623 if index > 0 && pull_request_number(&added.subject).is_some() {
624 named_merge = Some(added);
625 }
626 commit = parent;
627 }
628}
629
630#[derive(Debug, Clone, PartialEq, Eq)]
632#[non_exhaustive]
633pub struct Deleted {
634 pub path: PathBuf,
636 pub text: String,
638 pub parent: String,
641}
642
643pub fn candidate_deletions(
668 root: &Path,
669 manifest: &Path,
670 read: &dyn Fn(&str) -> Option<String>,
671 dir: &Path,
672) -> Result<Vec<Deleted>> {
673 let repo = discover(root).context("reading earlier candidates needs a git repository")?;
674 let workdir = repo.workdir().map(Path::to_path_buf);
675 let manifest_rel = git_path(root, manifest, workdir.as_deref())
676 .with_context(|| format!("{} is not in the repository", manifest.display()))?;
677 let dir_rel = git_path(root, dir, workdir.as_deref())
678 .with_context(|| format!("{} is not in the repository", dir.display()))?;
679 let version_at = |commit: &gix::Commit<'_>| -> Result<Option<String>> {
680 Ok(blob_at(&commit.tree()?, &manifest_rel).and_then(|raw| read(&raw)))
681 };
682 let boundary: Vec<gix::ObjectId> = repo
683 .shallow_commits()?
684 .map_or_default(|commits| commits.iter().copied().collect());
685 let mut commit = repo
686 .head_commit()
687 .context("reading earlier candidates needs HEAD")?;
688 let mut deleted = Vec::new();
689 loop {
690 let version = version_at(&commit)?;
691 if boundary.contains(&commit.id().detach()) {
692 return Err(lookup::unavailable(anyhow!(
693 "cannot read the candidates before commit {}: the clone is shallow; fetch the full history{}",
694 commit.id(),
695 shallow_hint()
696 )));
697 }
698 let Some(parent) = commit.parent_ids().next() else {
699 break;
700 };
701 let parent = repo.find_commit(parent.detach())?;
702 if version_at(&parent)? != version {
703 if version.as_deref().is_some_and(stable) {
704 break;
705 }
706 let files = files_under(&parent, &dir_rel)?;
707 let kept = files_under(&commit, &dir_rel)?;
708 for (name, text) in files {
709 if !kept.contains_key(&name) {
710 deleted.push(Deleted {
711 path: dir.join(&name),
712 text,
713 parent: parent.id().to_string(),
714 });
715 }
716 }
717 }
718 commit = parent;
719 }
720 Ok(deleted)
721}
722
723fn stable(version: &str) -> bool {
725 Version::parse(version).is_ok_and(|version| version.pre.is_empty())
726}
727
728fn files_under(commit: &gix::Commit<'_>, dir: &Path) -> Result<BTreeMap<PathBuf, String>> {
731 let tree = commit.tree()?;
732 let Some(entry) = tree.lookup_entry_by_path(dir)? else {
733 return Ok(BTreeMap::new());
734 };
735 let Ok(subtree) = entry.object()?.try_into_tree() else {
736 return Ok(BTreeMap::new());
737 };
738 let mut files = BTreeMap::new();
739 for entry in subtree.iter() {
740 let entry = entry?;
741 if !entry.mode().is_blob() {
742 continue;
743 }
744 let blob = entry.object()?.try_into_blob()?;
745 files.insert(
746 PathBuf::from(entry.filename().to_str_lossy().as_ref()),
747 String::from_utf8_lossy(&blob.data).into_owned(),
748 );
749 }
750 Ok(files)
751}
752
753#[derive(Debug, Clone, PartialEq, Eq)]
755#[non_exhaustive]
756pub struct VersionCommit {
757 pub sha: String,
759 pub depth: usize,
761}
762
763impl VersionCommit {
764 #[must_use]
767 pub const fn new(sha: String, depth: usize) -> Self {
768 Self { sha, depth }
769 }
770}
771
772#[derive(Debug)]
774enum PackageFile {
775 Missing,
777 Present(Option<String>),
780}
781
782fn package_file_at(
787 commit: &gix::Commit<'_>,
788 rel: &Path,
789 read: &dyn Fn(&str) -> Option<String>,
790) -> Result<PackageFile> {
791 let tree = commit.tree()?;
792 let Some(entry) = tree
793 .lookup_entry_by_path(rel)
794 .with_context(|| format!("reading {} at commit {}", rel.display(), commit.id()))?
795 else {
796 return Ok(PackageFile::Missing);
797 };
798 match entry.mode().kind() {
799 EntryKind::Blob | EntryKind::BlobExecutable => {
800 let blob = entry
801 .object()
802 .with_context(|| format!("reading {} at commit {}", rel.display(), commit.id()))?
803 .detach();
804 Ok(PackageFile::Present(read(&String::from_utf8_lossy(
805 &blob.data,
806 ))))
807 }
808 EntryKind::Tree | EntryKind::Link | EntryKind::Commit => Ok(PackageFile::Present(None)),
809 }
810}
811
812impl PackageFile {
813 fn is_release_of(&self, wanted: &str) -> bool {
817 match self {
818 Self::Missing => true,
819 Self::Present(version) => version.as_deref() == Some(wanted),
820 }
821 }
822}
823
824pub fn tagged_commit(
865 root: &Path,
866 path: &Path,
867 sha: &str,
868 read: &dyn Fn(&str) -> Option<String>,
869) -> Result<Option<VersionCommit>> {
870 let repo = discover(root).context("reading a tagged commit needs a git repository")?;
871 let commit = repo
872 .head_commit()
873 .context("reading a tagged commit needs HEAD")?;
874 tagged_commit_from_commit(&repo, commit, "HEAD", root, path, sha, read)
875}
876
877pub fn tagged_commit_from(
884 root: &Path,
885 start: &str,
886 path: &Path,
887 sha: &str,
888 read: &dyn Fn(&str) -> Option<String>,
889) -> Result<Option<VersionCommit>> {
890 let repo = discover(root).context("reading a tagged commit needs a git repository")?;
891 let id =
892 gix::ObjectId::from_hex(start.as_bytes()).with_context(|| format!("commit {start}"))?;
893 let commit = repo
894 .find_commit(id)
895 .with_context(|| format!("commit {start} is not in the repository"))?;
896 tagged_commit_from_commit(&repo, commit, start, root, path, sha, read)
897}
898
899fn tagged_commit_from_commit<'a>(
900 repo: &'a gix::Repository,
901 mut commit: gix::Commit<'a>,
902 start_label: &str,
903 root: &Path,
904 path: &Path,
905 sha: &str,
906 read: &dyn Fn(&str) -> Option<String>,
907) -> Result<Option<VersionCommit>> {
908 let rel = git_path(root, path, repo.workdir())
909 .with_context(|| format!("{} is not in the repository", path.display()))?;
910 let version_at =
911 |commit: &gix::Commit<'_>| -> Result<PackageFile> { package_file_at(commit, &rel, read) };
912 let wanted = match version_at(&commit)? {
913 PackageFile::Present(Some(version)) => version,
914 PackageFile::Missing | PackageFile::Present(None) => {
915 bail!("{start_label} has no version in {}", rel.display())
916 }
917 };
918 let boundary: Vec<gix::ObjectId> = repo
919 .shallow_commits()?
920 .map_or_default(|commits| commits.iter().copied().collect());
921 let mut line = Vec::new();
922 loop {
923 if commit.id().to_string().eq_ignore_ascii_case(sha) {
924 return Ok(version_at(&commit)?
925 .is_release_of(&wanted)
926 .then(|| VersionCommit {
927 sha: commit.id().to_string(),
928 depth: line.len(),
929 }));
930 }
931 if boundary.contains(&commit.id().detach()) {
932 return Err(lookup::unavailable(anyhow!(
933 "cannot find tagged commit {sha}: the clone is shallow; fetch the full history{}",
934 shallow_hint()
935 )));
936 }
937 line.push(commit.id().detach());
938 let Some(parent) = commit.parent_ids().next() else {
939 break;
940 };
941 commit = repo.find_commit(parent.detach())?;
942 }
943 merged_release(repo, &line, sha, &wanted, &version_at)
944}
945
946fn merged_release(
959 repo: &gix::Repository,
960 line: &[gix::ObjectId],
961 sha: &str,
962 wanted: &str,
963 version_at: &dyn Fn(&gix::Commit<'_>) -> Result<PackageFile>,
964) -> Result<Option<VersionCommit>> {
965 let Ok(tagged) = gix::ObjectId::from_hex(sha.as_bytes()) else {
966 return Ok(None);
967 };
968 let Ok(commit) = repo.find_commit(tagged) else {
969 return Ok(None);
970 };
971 if !version_at(&commit)?.is_release_of(wanted) {
972 return Ok(None);
973 }
974 let contains = |at: gix::ObjectId| -> Result<bool> {
975 let base = repo.merge_base(at, tagged).with_context(|| {
976 format!("cannot tell whether HEAD contains tagged commit {sha}; fetch the full history")
977 })?;
978 Ok(base.is_some_and(|base| base == tagged))
979 };
980 let Some(&head) = line.first() else {
981 return Ok(None);
982 };
983 if !contains(head)? {
984 return Ok(None);
985 }
986 let mut inside = 0;
987 let mut outside = line.len();
988 let mut probe = 1;
989 while probe < line.len() {
990 if !contains(line[probe])? {
991 outside = probe;
992 break;
993 }
994 inside = probe;
995 probe *= 2;
996 }
997 while outside - inside > 1 {
998 let mid = inside + (outside - inside) / 2;
999 if contains(line[mid])? {
1000 inside = mid;
1001 } else {
1002 outside = mid;
1003 }
1004 }
1005 Ok(Some(VersionCommit {
1006 sha: tagged.to_string(),
1007 depth: inside,
1008 }))
1009}
1010
1011fn has_path(commit: &gix::Commit<'_>, rel: &Path) -> Result<bool> {
1012 Ok(commit.tree()?.lookup_entry_by_path(rel)?.is_some())
1013}
1014
1015fn named(commit: &gix::Commit<'_>) -> Result<AddedBy> {
1016 Ok(AddedBy {
1017 sha: commit.id().to_string(),
1018 subject: commit.message()?.summary().to_str_lossy().into_owned(),
1019 })
1020}
1021
1022#[must_use]
1024pub fn pull_request_number(subject: &str) -> Option<u64> {
1025 let (_, digits) = subject.trim_end().strip_suffix(')')?.rsplit_once("(#")?;
1026 if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
1027 return None;
1028 }
1029 digits.parse().ok()
1030}
1031
1032#[must_use]
1034pub fn upstream_default_branch(root: &Path) -> Option<String> {
1035 origin_head_branch(&discover(root).ok()?)
1036}
1037
1038pub fn off_default_history(root: &Path) -> Result<Option<String>> {
1064 prove_default_history(root, &candidate_names(env_base_ref().as_deref()))
1065}
1066
1067pub fn workflows_differ(root: &Path) -> Result<Option<String>> {
1089 workflows_differ_at(root, env_run_sha().as_deref())
1090}
1091
1092fn workflows_differ_at(root: &Path, run_sha: Option<&str>) -> Result<Option<String>> {
1094 let repo = repo_covering(root).with_context(|| {
1095 format!(
1096 "release cannot compare workflows: no git repository covers {}",
1097 root.display()
1098 )
1099 })?;
1100 let head = repo
1101 .head_commit()
1102 .context("release cannot compare workflows: HEAD has no commit")?;
1103 let (run, label) = run_sha
1104 .and_then(|sha| find_commit_by_hex(&repo, sha))
1105 .map_or((head, "HEAD"), |commit| (commit, "GITHUB_SHA"));
1106 let upstream = default_upstream_commit(&repo, &candidate_names(env_base_ref().as_deref()))?
1107 .context("release cannot compare workflows: there is no `origin` remote")?;
1108 let upstream = repo.find_commit(upstream)?;
1109 let workflows = |commit: &gix::Commit<'_>| -> Result<Option<gix::ObjectId>> {
1110 Ok(commit
1111 .tree()?
1112 .lookup_entry_by_path(WORKFLOWS)?
1113 .map(|entry| entry.object_id()))
1114 };
1115 if workflows(&run)? == workflows(&upstream)? {
1116 return Ok(None);
1117 }
1118 Ok(Some(format!(
1119 "{WORKFLOWS}/ at {label} {run} differs from the default branch at {upstream}",
1120 run = run.id(),
1121 upstream = upstream.id(),
1122 )))
1123}
1124
1125fn find_commit_by_hex<'repo>(
1128 repo: &'repo gix::Repository,
1129 sha: &str,
1130) -> Option<gix::Commit<'repo>> {
1131 let id = gix::ObjectId::from_hex(sha.as_bytes()).ok()?;
1132 repo.find_commit(id).ok()
1133}
1134
1135fn env_run_sha() -> Option<String> {
1136 env::var("GITHUB_SHA")
1137 .ok()
1138 .map(|value| value.trim().to_owned())
1139 .filter(|value| !value.is_empty())
1140}
1141
1142const WORKFLOWS: &str = ".github/workflows";
1144
1145#[non_exhaustive]
1147pub enum FetchDefault {
1148 Origin,
1150 GitHub {
1152 token: String,
1154 repository: String,
1156 },
1157}
1158
1159impl fmt::Debug for FetchDefault {
1162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1163 match self {
1164 Self::Origin => f.write_str("Origin"),
1165 Self::GitHub {
1166 repository,
1167 token: _,
1168 } => f
1169 .debug_struct("GitHub")
1170 .field("token", &"<redacted>")
1171 .field("repository", repository)
1172 .finish(),
1173 }
1174 }
1175}
1176
1177impl FetchDefault {
1178 #[must_use]
1181 pub fn from_env() -> Self {
1182 match (env::var("GITHUB_TOKEN"), env::var("GITHUB_REPOSITORY")) {
1183 (Ok(token), Ok(repository)) if !token.is_empty() && !repository.is_empty() => {
1184 Self::GitHub { token, repository }
1185 }
1186 _ => Self::Origin,
1187 }
1188 }
1189}
1190
1191#[must_use]
1193pub fn github_https_url(repository: &str) -> String {
1194 format!("https://github.com/{repository}.git")
1195}
1196
1197#[must_use]
1199pub fn github_git_user() -> &'static str {
1200 "x-access-token"
1201}
1202
1203#[must_use]
1208pub fn configured_default_branch() -> Option<String> {
1209 env::var("VERCTL_DEFAULT_BRANCH")
1210 .ok()
1211 .map(|value| value.trim().to_owned())
1212 .filter(|value| !value.is_empty())
1213}
1214
1215pub fn ensure_origin_head(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
1230 if branch.is_empty() {
1231 return Ok(());
1232 }
1233 let Some(repo) = repo_covering(root) else {
1234 return Ok(());
1235 };
1236 if !has_origin(&repo) {
1237 return Ok(());
1238 }
1239 let remote_ref = format!("refs/remotes/origin/{branch}");
1240 if peel_remote(&repo, &remote_ref).is_none() {
1241 fetch_one_branch(&repo, branch, fetch, Shallow::NoChange)?;
1242 }
1243 ensure!(
1244 peel_remote(&repo, &remote_ref).is_some(),
1245 "cannot resolve the default branch ({remote_ref} is missing; fetch the default branch)"
1246 );
1247 let target = FullName::try_from(remote_ref.as_str())
1248 .context("point origin/HEAD at the default branch")?;
1249 let name = FullName::try_from("refs/remotes/origin/HEAD")
1250 .context("point origin/HEAD at the default branch")?;
1251 repo.edit_reference(RefEdit::update(
1252 name,
1253 Target::Symbolic(target),
1254 PreviousValue::Any,
1255 "verctl default branch",
1256 ))
1257 .context("point origin/HEAD at the default branch")?;
1258 Ok(())
1259}
1260
1261fn shallow_hint() -> &'static str {
1265 if configured_default_branch().is_some() {
1266 ""
1267 } else {
1268 ", or set VERCTL_DEFAULT_BRANCH so verctl fetches it"
1269 }
1270}
1271
1272pub fn ensure_full_history(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
1295 if branch.is_empty() {
1296 return Ok(());
1297 }
1298 let Some(repo) = repo_covering(root) else {
1299 return Ok(());
1300 };
1301 if !has_origin(&repo) || !repo.is_shallow().context("read the shallow boundary")? {
1302 return Ok(());
1303 }
1304 fetch_one_branch(&repo, branch, fetch, Shallow::undo())
1305}
1306
1307pub fn ensure_comparable(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
1326 if branch.is_empty() {
1327 return Ok(());
1328 }
1329 let Some(repo) = repo_covering(root) else {
1330 return Ok(());
1331 };
1332 if !has_origin(&repo) {
1333 return Ok(());
1334 }
1335 let shallow = repo.is_shallow().context("read the shallow boundary")?;
1336 let missing = peel_remote(&repo, &format!("refs/remotes/origin/{branch}")).is_none();
1337 match (shallow, missing) {
1338 (true, _) => fetch_one_branch(&repo, branch, fetch, Shallow::undo()),
1339 (false, true) => fetch_one_branch(&repo, branch, fetch, Shallow::NoChange),
1340 (false, false) => Ok(()),
1341 }
1342}
1343
1344fn fetch_one_branch(
1349 repo: &gix::Repository,
1350 branch: &str,
1351 fetch: &FetchDefault,
1352 shallow: Shallow,
1353) -> Result<()> {
1354 let spec = format!("+refs/heads/{branch}:refs/remotes/origin/{branch}");
1355 let url = match fetch {
1356 FetchDefault::Origin => origin_url_of(repo)?,
1357 FetchDefault::GitHub {
1358 repository,
1359 token: _,
1360 } => github_https_url(repository),
1361 };
1362 let remote = repo
1363 .remote_at(url.as_str())
1364 .context("fetch the default branch")?
1365 .with_fetch_tags(Tags::None)
1366 .with_refspecs([spec.as_str()], Direction::Fetch)
1367 .context("fetch the default branch")?;
1368 let connection = remote
1369 .connect(Direction::Fetch)
1370 .with_context(|| format!("git fetch {spec}"))?;
1371 let interrupt = AtomicBool::new(false);
1372 match fetch {
1373 FetchDefault::Origin => connection
1374 .prepare_fetch(Discard, ref_map::Options::default())
1375 .with_context(|| format!("git fetch {spec}"))?
1376 .with_shallow(shallow)
1377 .receive(Discard, &interrupt),
1378 FetchDefault::GitHub {
1379 token,
1380 repository: _,
1381 } => connection
1382 .with_credentials(github_credentials(token))
1383 .prepare_fetch(Discard, ref_map::Options::default())
1384 .with_context(|| format!("git fetch {spec}"))?
1385 .with_shallow(shallow)
1386 .receive(Discard, &interrupt),
1387 }
1388 .with_context(|| format!("git fetch {spec}"))?;
1389 Ok(())
1390}
1391
1392fn github_credentials(token: &str) -> impl FnMut(Action) -> gix::Result<Option<Outcome>> + '_ {
1395 move |action| match action {
1396 Action::Get(context) => Ok(Some(Outcome {
1397 identity: Account {
1398 username: github_git_user().to_owned(),
1399 password: token.to_owned(),
1400 oauth_refresh_token: None,
1401 },
1402 next: context.into(),
1403 })),
1404 Action::Store(_) | Action::Erase(_) => Ok(None),
1405 }
1406}
1407
1408fn prove_default_history(root: &Path, candidates: &[String]) -> Result<Option<String>> {
1409 let repo = repo_covering(root).with_context(|| {
1410 format!(
1411 "release cannot prove HEAD is on the default branch: no git repository covers {}",
1412 root.display()
1413 )
1414 })?;
1415 let head = repo
1416 .head_commit()
1417 .context("release cannot prove HEAD is on the default branch: HEAD has no commit")?
1418 .id()
1419 .detach();
1420 let upstream = default_upstream_commit(&repo, candidates)?.context(
1421 "release cannot prove HEAD is on the default branch: there is no `origin` remote; add it and fetch the default branch",
1422 )?;
1423 if head == upstream {
1424 return Ok(None);
1425 }
1426 match repo.merge_base(head, upstream) {
1427 Ok(Some(base)) if base == head => Ok(None),
1428 Ok(Some(_) | None) => Ok(Some(format!(
1429 "HEAD {head} is not an ancestor of the default branch at {upstream}"
1430 ))),
1431 Err(error) => Err(error).context(
1432 "release cannot prove HEAD is on the default branch (need a full fetch, not a shallow clone)",
1433 ),
1434 }
1435}
1436
1437#[must_use]
1442pub fn workdir_covering(dir: &Path) -> Option<PathBuf> {
1443 repo_covering(dir)?
1444 .workdir()
1445 .and_then(|workdir| workdir.canonicalize().ok())
1446}
1447
1448pub fn tracked(root: &Path) -> Result<Vec<PathBuf>> {
1465 let Some(repo) = repo_covering(root) else {
1466 return Ok(Vec::new());
1467 };
1468 let index = repo.index_or_empty().context("git index")?;
1469 let project = project_prefix(&repo, root);
1470 Ok(index
1471 .entries()
1472 .iter()
1473 .filter_map(|entry| entry.path(&index).to_str().ok().map(PathBuf::from))
1474 .filter_map(|path| path.strip_prefix(&project).ok().map(Path::to_path_buf))
1475 .collect())
1476}
1477
1478#[must_use]
1488pub fn is_ignored(root: &Path, rel: &Path) -> bool {
1489 let Some(repo) = repo_covering(root) else {
1490 return false;
1491 };
1492 let path = project_prefix(&repo, root).join(rel);
1493 let Ok(index) = repo.index_or_empty() else {
1494 return false;
1495 };
1496 let Ok(mut excludes) = repo.excludes(&index, None, Source::WorktreeThenIdMappingIfNotSkipped)
1497 else {
1498 return false;
1499 };
1500 let mut ignored_at = |path: &Path, mode| {
1501 excludes
1502 .at_path(path, mode)
1503 .is_ok_and(|platform| platform.is_excluded())
1504 };
1505 path.ancestors()
1506 .skip(1)
1507 .filter(|dir| !dir.as_os_str().is_empty())
1508 .any(|dir| ignored_at(dir, Some(Mode::DIR)))
1509 || ignored_at(&path, None)
1510}
1511
1512#[must_use]
1518pub fn is_repository(root: &Path) -> bool {
1519 repo_covering(root).is_some()
1520}
1521
1522fn project_prefix(repo: &gix::Repository, root: &Path) -> PathBuf {
1524 let Some(workdir) = repo.workdir().and_then(|dir| dir.canonicalize().ok()) else {
1525 return PathBuf::new();
1526 };
1527 root.canonicalize()
1528 .ok()
1529 .and_then(|root| root.strip_prefix(&workdir).ok().map(Path::to_path_buf))
1530 .unwrap_or_default()
1531}
1532
1533fn discover(dir: &Path) -> Result<gix::Repository> {
1550 let mapping = Mapping {
1551 full: open_options(Trust::Full),
1552 reduced: open_options(Trust::Reduced),
1553 };
1554 let repo = gix::ThreadSafeRepository::discover_opts(
1555 dir,
1556 gix::discover::upwards::Options::default(),
1557 mapping,
1558 )
1559 .with_context(|| format!("no git repository covers {}", dir.display()))?;
1560 let mut repo = repo.to_thread_local();
1561 let (name, email) = fallback_identity();
1562 repo.committer_or_set_fallback(name.as_str(), email.as_str())
1563 .context("set the reflog identity")?;
1564 Ok(repo)
1565}
1566
1567fn open_options(trust: Trust) -> open::Options {
1569 let mut options = open::Options::default_for_level(trust);
1570 options.permissions.env.git_prefix = Permission::Deny;
1571 options
1572}
1573
1574fn repo_covering(root: &Path) -> Option<gix::Repository> {
1575 let repo = discover(root).ok()?;
1576 let workdir = repo.workdir()?.canonicalize().ok()?;
1577 let root = root.canonicalize().ok()?;
1578 root.starts_with(workdir).then_some(repo)
1579}
1580
1581fn has_origin(repo: &gix::Repository) -> bool {
1582 repo.remote_names()
1583 .iter()
1584 .any(|name| name.to_str() == Ok("origin"))
1585}
1586
1587fn origin_url_of(repo: &gix::Repository) -> Result<String> {
1588 let remote = repo
1589 .find_remote("origin")
1590 .context("fetch the default branch")?;
1591 let url = remote.url(Direction::Fetch).context("origin has no URL")?;
1592 Ok(url.to_bstring().to_str_lossy().into_owned())
1593}
1594
1595fn peel_remote(repo: &gix::Repository, name: &str) -> Option<gix::ObjectId> {
1596 let mut reference = repo.try_find_reference(name).ok()??;
1597 let commit = reference.peel_to_commit().ok()?;
1598 Some(commit.id().detach())
1599}
1600
1601fn origin_head_branch(repo: &gix::Repository) -> Option<String> {
1602 let reference = repo.try_find_reference("refs/remotes/origin/HEAD").ok()??;
1603 let target = reference.target();
1604 let target = target.try_name()?.as_bstr().to_str().ok()?;
1605 let name = target.trim_start_matches("refs/remotes/origin/");
1606 (!name.is_empty()).then(|| name.to_owned())
1607}
1608
1609fn env_base_ref() -> Option<String> {
1610 env::var("GITHUB_BASE_REF")
1611 .ok()
1612 .map(|value| value.trim().to_owned())
1613 .filter(|value| !value.is_empty())
1614}
1615
1616#[must_use]
1624pub fn default_branch_candidates() -> Vec<String> {
1625 candidate_names(env_base_ref().as_deref())
1626}
1627
1628#[must_use]
1641pub fn release_branch_candidates() -> Vec<String> {
1642 release_candidate_names(
1643 configured_default_branch().as_deref(),
1644 github_env::event_default_branch().as_deref(),
1645 env_base_ref().as_deref(),
1646 )
1647}
1648
1649fn release_candidate_names(
1650 configured: Option<&str>,
1651 event_default: Option<&str>,
1652 base: Option<&str>,
1653) -> Vec<String> {
1654 let mut names = Vec::new();
1655 for name in [configured, event_default].into_iter().flatten() {
1656 if !name.is_empty() && !names.iter().any(|known| known == name) {
1657 names.push(name.to_owned());
1658 }
1659 }
1660 for name in candidate_names(None)
1661 .into_iter()
1662 .chain(base.map(str::to_owned))
1663 {
1664 if !name.is_empty() && !names.contains(&name) {
1665 names.push(name);
1666 }
1667 }
1668 names
1669}
1670
1671#[must_use]
1678pub fn comparison_branches() -> Vec<String> {
1679 let mut names = Vec::new();
1680 let sources = [
1681 configured_default_branch(),
1682 github_env::event_default_branch(),
1683 env_base_ref(),
1684 ];
1685 for name in sources.into_iter().flatten() {
1686 if !name.is_empty() && !names.contains(&name) {
1687 names.push(name);
1688 }
1689 }
1690 names
1691}
1692
1693#[must_use]
1696pub fn default_branch_candidates_from(base_ref: Option<&str>) -> Vec<String> {
1697 candidate_names(base_ref)
1698}
1699
1700fn candidate_names(base_ref: Option<&str>) -> Vec<String> {
1701 let mut names = Vec::new();
1702 if let Some(value) = base_ref.map(str::trim).filter(|value| !value.is_empty()) {
1703 names.push(value.to_owned());
1704 }
1705 for stock in ["main", "master"] {
1706 if !names.iter().any(|name| name == stock) {
1707 names.push(stock.to_owned());
1708 }
1709 }
1710 names
1711}
1712
1713fn default_upstream_commit(
1714 repo: &gix::Repository,
1715 candidates: &[String],
1716) -> Result<Option<gix::ObjectId>> {
1717 if let Some(branch) = origin_head_branch(repo) {
1718 let name = format!("refs/remotes/origin/{branch}");
1719 return match peel_remote(repo, &name) {
1720 Some(commit) => Ok(Some(commit)),
1721 None => bail!(
1722 "cannot resolve the default branch ({name} is missing; fetch the default branch)"
1723 ),
1724 };
1725 }
1726 for name in candidates {
1727 let reference = format!("refs/remotes/origin/{name}");
1728 if let Some(commit) = peel_remote(repo, &reference) {
1729 return Ok(Some(commit));
1730 }
1731 }
1732 if has_origin(repo) {
1733 bail!(
1734 "cannot resolve the default branch (origin exists but origin/HEAD, origin/main, and origin/master are missing; fetch the default branch)"
1735 );
1736 }
1737 Ok(None)
1738}
1739
1740#[must_use]
1743pub fn matches_stage(pattern: &str, rel: &str) -> bool {
1744 glob::Pattern::new(pattern)
1745 .is_ok_and(|compiled| compiled.matches(rel) || compiled.matches(&format!("./{rel}")))
1746}
1747
1748#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1750pub enum IgnoredFiles {
1751 #[default]
1753 Skip,
1754 Include,
1756}
1757
1758pub fn assert_only_allowed(
1773 root: &Path,
1774 allowed: &[PathBuf],
1775 globs: &[String],
1776 ignored: IgnoredFiles,
1777) -> Result<Vec<PathBuf>> {
1778 let Ok(repo) = discover(root) else {
1779 return Ok(Vec::new());
1780 };
1781 let dirty = status_paths(&repo, Vec::new(), IgnoredFiles::Skip).context("git status")?;
1782 let workdir = repo.workdir().unwrap_or(root);
1783 let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
1784 let workdir = workdir
1785 .canonicalize()
1786 .unwrap_or_else(|_| workdir.to_path_buf());
1787 let mut extra = Vec::new();
1788 let mut staged = Vec::new();
1789 for rel in &dirty {
1790 let abs = workdir.join(rel);
1791 if !abs.starts_with(&root) {
1792 continue;
1793 }
1794 if abs.is_dir() {
1795 continue;
1796 }
1797 if allowed
1798 .iter()
1799 .any(|path| path == &abs || path.ends_with(rel))
1800 {
1801 continue;
1802 }
1803 if globs.iter().any(|pattern| matches_stage(pattern, rel)) {
1804 staged.push(abs);
1805 continue;
1806 }
1807 extra.push(rel.clone());
1808 }
1809 if matches!(ignored, IgnoredFiles::Include) && !globs.is_empty() {
1810 let patterns = globs
1811 .iter()
1812 .map(|pattern| pattern.as_str().into())
1813 .collect();
1814 let ignored =
1815 status_paths(&repo, patterns, IgnoredFiles::Include).context("git status (ignored)")?;
1816 for rel in &ignored {
1817 let abs = workdir.join(rel);
1818 if !abs.starts_with(&root) || abs.is_dir() {
1819 continue;
1820 }
1821 if globs.iter().any(|pattern| matches_stage(pattern, rel))
1822 && !staged.iter().any(|path| path == &abs)
1823 {
1824 staged.push(abs);
1825 }
1826 }
1827 }
1828 if extra.is_empty() {
1829 return Ok(staged);
1830 }
1831 bail!(
1832 "version produced unexpected paths (declare them in prepare.stage): {}",
1833 extra.join(", ")
1834 );
1835}
1836
1837fn status_paths(
1843 repo: &gix::Repository,
1844 patterns: Vec<BString>,
1845 ignored: IgnoredFiles,
1846) -> Result<BTreeSet<String>> {
1847 let include_ignored = matches!(ignored, IgnoredFiles::Include);
1848 let status = repo
1849 .status(Discard)?
1850 .untracked_files(UntrackedFiles::Files)
1851 .index_worktree_rewrites(None)
1852 .tree_index_track_renames(TrackRenames::Disabled);
1853 let status = if include_ignored {
1854 status.dirwalk_options(|options| options.emit_ignored(Some(EmissionMode::Matching)))
1855 } else {
1856 status
1857 };
1858 let mut paths = BTreeSet::new();
1859 for item in status.into_iter(patterns)? {
1860 let item = item?;
1861 let is_ignored = matches!(
1862 &item,
1863 status::Item::IndexWorktree(index_worktree::Item::DirectoryContents {
1864 entry,
1865 collapsed_directory_status: _
1866 }) if matches!(entry.status, Status::Ignored(_))
1867 );
1868 if is_ignored == include_ignored {
1869 paths.insert(item.location().to_str_lossy().into_owned());
1870 }
1871 }
1872 Ok(paths)
1873}
1874
1875#[derive(Debug, Clone, Copy, Eq, PartialEq)]
1880pub enum PushOutcome {
1881 Empty,
1883 Pushed,
1885}
1886
1887pub fn commit_branch_and_push(
1904 root: &Path,
1905 branch: &str,
1906 message: &str,
1907 token: &str,
1908 github: &Repo,
1909 paths: &[PathBuf],
1910) -> Result<PushOutcome> {
1911 let repo = discover(root).context("open git repository")?;
1912 let workdir = absolute_workdir(&repo)?;
1913 let parent = repo.head_commit().context("HEAD commit")?;
1914 let Some(_) = write_commit_on_branch(&repo, &workdir, &parent, branch, message, paths)? else {
1915 return Ok(PushOutcome::Empty);
1916 };
1917 let url = format!("https://github.com/{}/{}.git", github.owner, github.name);
1918 push(repo.git_dir(), &url, branch, token)?;
1919 Ok(PushOutcome::Pushed)
1920}
1921
1922fn absolute_workdir(repo: &gix::Repository) -> Result<PathBuf> {
1926 let workdir = repo.workdir().context("repository has no workdir")?;
1927 path::absolute(workdir).with_context(|| format!("resolve the workdir {}", workdir.display()))
1928}
1929
1930const PUSH_TOKEN: &str = "VERCTL_GIT_TOKEN";
1933
1934const PUSH_CREDENTIAL_HELPER: &str = r#"!f() { test "$1" = get || return 0; echo username=x-access-token; echo "password=$VERCTL_GIT_TOKEN"; }; f"#;
1938
1939const PUSH_TIMEOUT: Duration = Duration::from_mins(5);
1941
1942fn push(git_dir: &Path, url: &str, branch: &str, token: &str) -> Result<()> {
1957 let git_dir = git_dir
1958 .canonicalize()
1959 .with_context(|| format!("git directory {}", git_dir.display()))?;
1960 let git_dir = format!(
1961 "--git-dir={}",
1962 git_dir.to_str().context("git directory is not UTF-8")?
1963 );
1964 let helper = format!("credential.helper={PUSH_CREDENTIAL_HELPER}");
1965 let refspec = format!("+refs/heads/{branch}:refs/heads/{branch}");
1966 let argv = process::argv(&[
1967 "git",
1968 &git_dir,
1969 "-c",
1970 "credential.helper=",
1971 "-c",
1972 &helper,
1973 "push",
1974 "--no-verify",
1975 "--quiet",
1976 url,
1977 &refspec,
1978 ]);
1979 process::run_limited(
1980 &argv,
1981 &[(PUSH_TOKEN, token), ("GIT_TERMINAL_PROMPT", "0")],
1982 PUSH_TIMEOUT,
1983 )
1984 .context("git push")?;
1985 Ok(())
1986}
1987
1988fn write_commit_on_branch(
1998 repo: &gix::Repository,
1999 workdir: &Path,
2000 parent: &gix::Commit<'_>,
2001 branch: &str,
2002 message: &str,
2003 paths: &[PathBuf],
2004) -> Result<Option<gix::ObjectId>> {
2005 let parent_tree = parent.tree_id().context("HEAD tree")?.detach();
2006 let mut editor = repo.edit_tree(parent_tree).context("edit HEAD tree")?;
2007 let (mut filters, index) = repo
2008 .filter_pipeline(None)
2009 .context("load the .gitattributes filters")?;
2010 for path in paths {
2011 let rel = workdir_rel(workdir, path)?;
2012 let name = rel
2013 .to_str()
2014 .with_context(|| format!("path is not UTF-8: {}", rel.display()))?
2015 .to_owned();
2016 let abs = workdir.join(&rel);
2017 if abs.exists() {
2018 let (kind, data) = worktree_entry(&mut filters, &index, &abs, &rel)?;
2019 let blob = repo
2020 .write_blob(data)
2021 .with_context(|| format!("git add {name}"))?;
2022 editor
2023 .upsert(&name, kind, blob)
2024 .with_context(|| format!("git add {name}"))?;
2025 } else {
2026 editor
2027 .remove(&name)
2028 .with_context(|| format!("git rm {name}"))?;
2029 }
2030 }
2031 let tree = editor.write().context("write tree")?.detach();
2032 if tree == parent_tree {
2033 return Ok(None);
2034 }
2035 let signature = signature(repo);
2036 let commit = Commit {
2037 tree,
2038 parents: [parent.id().detach()].into_iter().collect(),
2039 author: signature.clone(),
2040 committer: signature,
2041 encoding: None,
2042 message: message.into(),
2043 extra_headers: Vec::new(),
2044 };
2045 let id = repo.write_object(&commit).context("git commit")?.detach();
2046 repo.reference(
2047 format!("refs/heads/{branch}"),
2048 id,
2049 PreviousValue::Any,
2050 "verctl: version packages",
2051 )
2052 .context("git commit")?;
2053 Ok(Some(id))
2054}
2055
2056fn worktree_entry(
2060 filters: &mut Pipeline<'_>,
2061 index: &State,
2062 abs: &Path,
2063 rel: &Path,
2064) -> Result<(EntryKind, Vec<u8>)> {
2065 let meta = fs::symlink_metadata(abs).with_context(|| abs.display().to_string())?;
2066 if meta.file_type().is_symlink() {
2067 let target = fs::read_link(abs).with_context(|| abs.display().to_string())?;
2068 let target = target
2069 .to_str()
2070 .with_context(|| format!("link target is not UTF-8: {}", abs.display()))?;
2071 return Ok((EntryKind::Link, target.as_bytes().to_vec()));
2072 }
2073 let file = File::open(abs).with_context(|| abs.display().to_string())?;
2074 let mut clean = filters
2075 .convert_to_git(file, rel, index)
2076 .with_context(|| format!("filter {}", rel.display()))?;
2077 let mut data = Vec::new();
2078 Read::read_to_end(&mut clean, &mut data)
2079 .with_context(|| format!("filter {}", rel.display()))?;
2080 Ok((file_kind(&meta), data))
2081}
2082
2083#[cfg(unix)]
2084fn file_kind(meta: &Metadata) -> EntryKind {
2085 use std::os::unix::fs::PermissionsExt;
2086 if meta.permissions().mode() & 0o111 == 0 {
2087 EntryKind::Blob
2088 } else {
2089 EntryKind::BlobExecutable
2090 }
2091}
2092
2093#[cfg(not(unix))]
2094fn file_kind(_meta: &std::fs::Metadata) -> EntryKind {
2095 EntryKind::Blob
2096}
2097
2098fn workdir_rel(workdir: &Path, path: &Path) -> Result<PathBuf> {
2108 let absolute = if path.is_absolute() {
2109 path.to_path_buf()
2110 } else {
2111 workdir.join(path)
2112 };
2113 let normalized: PathBuf = absolute
2114 .components()
2115 .filter(|component| !matches!(component, Component::CurDir))
2116 .collect();
2117 let workdirs = [Some(workdir.to_path_buf()), workdir.canonicalize().ok()];
2118 let through_parent = normalized
2119 .parent()
2120 .and_then(|parent| parent.canonicalize().ok())
2121 .zip(normalized.file_name())
2122 .map(|(parent, name)| parent.join(name));
2123 let paths = [Some(normalized.clone()), through_parent];
2124 paths
2125 .iter()
2126 .flatten()
2127 .find_map(|path| {
2128 workdirs
2129 .iter()
2130 .flatten()
2131 .find_map(|workdir| path.strip_prefix(workdir).ok())
2132 })
2133 .map(Path::to_path_buf)
2134 .with_context(|| format!("path outside workdir: {}", normalized.display()))
2135}
2136
2137fn signature(repo: &gix::Repository) -> Signature {
2140 let time = Time::now_local_or_utc();
2141 let config = repo.config_snapshot();
2142 if let (Some(name), Some(email)) = (config.string("user.name"), config.string("user.email")) {
2143 return Signature { name, email, time };
2144 }
2145 let (name, email) = fallback_identity();
2146 Signature {
2147 name: name.into(),
2148 email: email.into(),
2149 time,
2150 }
2151}
2152
2153fn fallback_identity() -> (String, String) {
2157 let name = env::var("GIT_AUTHOR_NAME")
2158 .or_else(|_| env::var("GITHUB_ACTOR"))
2159 .unwrap_or_else(|_| "verctl".into());
2160 let email =
2161 env::var("GIT_AUTHOR_EMAIL").unwrap_or_else(|_| format!("{name}@users.noreply.github.com"));
2162 (name, email)
2163}
2164
2165#[cfg(test)]
2166mod tests {
2167 use std::fs;
2168 use std::os::unix::fs::symlink;
2169 use std::path::{Path, PathBuf};
2170
2171 use indoc::indoc;
2172 use tokio::task;
2173 use verctl_core::repo::Repo;
2174 use wiremock::matchers;
2175
2176 use super::{
2177 AddedBy, VersionCommit, added_by, added_by_from, candidate_deletions, file_at, origin_url,
2178 tagged_commit,
2179 };
2180 use crate::test_git::{commit_all, git, init};
2181
2182 fn version_file(raw: &str) -> Option<String> {
2184 let version = raw.trim();
2185 (!version.is_empty()).then(|| version.to_owned())
2186 }
2187
2188 fn fragment(bump: &str, summary: &str) -> String {
2190 indoc::formatdoc! {"
2191 ---
2192 demo: {bump}
2193 ---
2194
2195 {summary}
2196 "}
2197 }
2198
2199 fn two_candidates(dir: &Path) -> (String, String) {
2204 init(dir);
2205 fs::create_dir(dir.join(".changeset")).unwrap();
2206 fs::write(dir.join("VERSION"), "0.8.0\n").unwrap();
2207 fs::write(dir.join(".changeset/old.md"), fragment("patch", "Old.")).unwrap();
2208 commit_all(dir, "chore: start");
2209 fs::write(dir.join("VERSION"), "0.8.1\n").unwrap();
2210 fs::remove_file(dir.join(".changeset/old.md")).unwrap();
2211 commit_all(dir, "chore: release demo 0.8.1 (#1)");
2212 fs::write(dir.join(".changeset/one.md"), fragment("patch", "One.")).unwrap();
2213 let added = commit_all(dir, "fix: one (#2)");
2214 fs::write(dir.join("VERSION"), "0.8.2-rc.1\n").unwrap();
2215 fs::remove_file(dir.join(".changeset/one.md")).unwrap();
2216 commit_all(dir, "chore: release demo 0.8.2-rc.1 (#3)");
2217 let first_parent = git(dir, &["rev-parse", "HEAD~1"]);
2218 fs::write(dir.join(".changeset/stray.md"), fragment("patch", "Stray.")).unwrap();
2219 commit_all(dir, "docs: stray (#4)");
2220 fs::remove_file(dir.join(".changeset/stray.md")).unwrap();
2221 commit_all(dir, "docs: drop stray (#5)");
2222 fs::write(dir.join(".changeset/two.md"), fragment("minor", "Two.")).unwrap();
2223 commit_all(dir, "feat: two (#6)");
2224 fs::write(dir.join("VERSION"), "0.8.2-rc.2\n").unwrap();
2225 fs::remove_file(dir.join(".changeset/two.md")).unwrap();
2226 commit_all(dir, "chore: release demo 0.8.2-rc.2 (#7)");
2227 (added, first_parent)
2228 }
2229
2230 #[test]
2231 fn candidate_deletions_lists_what_each_candidate_consumed_since_stable() {
2232 let dir = tempfile::TempDir::new().unwrap();
2233 let (_, first_parent) = two_candidates(dir.path());
2234 let deleted = candidate_deletions(
2235 dir.path(),
2236 &dir.path().join("VERSION"),
2237 &version_file,
2238 &dir.path().join(".changeset"),
2239 )
2240 .unwrap();
2241 let names: Vec<(String, String)> = deleted
2242 .iter()
2243 .map(|file| {
2244 (
2245 file.path
2246 .file_name()
2247 .unwrap()
2248 .to_string_lossy()
2249 .into_owned(),
2250 file.text.clone(),
2251 )
2252 })
2253 .collect();
2254 assert_eq!(
2255 names,
2256 [
2257 ("two.md".to_owned(), fragment("minor", "Two.")),
2258 ("one.md".to_owned(), fragment("patch", "One.")),
2259 ]
2260 );
2261 assert_eq!(deleted[1].parent, first_parent);
2262 assert_eq!(deleted[1].path, dir.path().join(".changeset/one.md"));
2263 }
2264
2265 #[test]
2266 fn candidate_deletions_is_empty_on_a_stable_head() {
2267 let dir = tempfile::TempDir::new().unwrap();
2268 two_candidates(dir.path());
2269 fs::write(dir.path().join("VERSION"), "0.8.2\n").unwrap();
2270 commit_all(dir.path(), "chore: release demo 0.8.2 (#8)");
2271 assert_eq!(
2272 candidate_deletions(
2273 dir.path(),
2274 &dir.path().join("VERSION"),
2275 &version_file,
2276 &dir.path().join(".changeset"),
2277 )
2278 .unwrap(),
2279 []
2280 );
2281 }
2282
2283 #[test]
2284 fn added_by_from_resolves_a_fragment_deleted_at_head() {
2285 let dir = tempfile::TempDir::new().unwrap();
2286 let (added, first_parent) = two_candidates(dir.path());
2287 let path = dir.path().join(".changeset/one.md");
2288 assert_eq!(added_by(dir.path(), &path).unwrap(), None);
2289 assert_eq!(
2290 added_by_from(dir.path(), &path, &first_parent).unwrap(),
2291 Some(AddedBy {
2292 sha: added,
2293 subject: "fix: one (#2)".to_owned(),
2294 })
2295 );
2296 }
2297
2298 #[test]
2301 fn candidate_deletions_fails_at_a_shallow_boundary() {
2302 let dir = tempfile::TempDir::new().unwrap();
2303 two_candidates(dir.path());
2304 let boundary = git(dir.path(), &["rev-parse", "HEAD~2"]);
2305 fs::write(dir.path().join(".git/shallow"), format!("{boundary}\n")).unwrap();
2306 let error = candidate_deletions(
2307 dir.path(),
2308 &dir.path().join("VERSION"),
2309 &version_file,
2310 &dir.path().join(".changeset"),
2311 )
2312 .unwrap_err()
2313 .to_string();
2314 assert!(error.contains(&boundary), "{error}");
2315 assert!(error.contains("shallow"), "{error}");
2316 }
2317
2318 fn tree_names(dir: &Path, sha: &str) -> Vec<String> {
2320 git(dir, &["ls-tree", "-r", "--name-only", sha])
2321 .lines()
2322 .map(str::to_owned)
2323 .collect()
2324 }
2325
2326 fn version_line(raw: &str) -> Option<String> {
2327 raw.lines()
2328 .find_map(|line| line.strip_prefix("version = "))
2329 .map(|version| version.trim_matches('"').to_owned())
2330 }
2331
2332 fn write_version(dir: &Path, version: &str) {
2333 fs::write(
2334 dir.join("Cargo.toml"),
2335 indoc::formatdoc! {r#"
2336 [package]
2337 name = "demo"
2338 version = "{version}"
2339 "#},
2340 )
2341 .unwrap();
2342 }
2343
2344 #[test]
2345 fn a_tag_on_a_later_commit_at_the_same_version_is_the_release() {
2346 let dir = tempfile::TempDir::new().unwrap();
2347 init(dir.path());
2348 write_version(dir.path(), "0.4.6");
2349 let set = commit_all(dir.path(), "chore(release): version packages (#9)");
2350 fs::write(dir.path().join("README"), "later\n").unwrap();
2351 let later = commit_all(dir.path(), "docs: later");
2352 fs::write(dir.path().join("README"), "head\n").unwrap();
2353 commit_all(dir.path(), "docs: head");
2354 let manifest = dir.path().join("Cargo.toml");
2355 let found = tagged_commit(dir.path(), &manifest, &later, &version_line).unwrap();
2356 assert_eq!(
2357 found,
2358 Some(VersionCommit {
2359 sha: later,
2360 depth: 1,
2361 })
2362 );
2363 assert!(
2364 tagged_commit(dir.path(), &manifest, &set, &version_line)
2365 .unwrap()
2366 .is_some()
2367 );
2368 }
2369
2370 #[test]
2371 fn a_tag_on_a_commit_at_another_version_is_not_the_release() {
2372 let dir = tempfile::TempDir::new().unwrap();
2373 init(dir.path());
2374 write_version(dir.path(), "0.4.5");
2375 let older = commit_all(dir.path(), "chore: start");
2376 write_version(dir.path(), "0.4.6");
2377 commit_all(dir.path(), "chore(release): version packages (#9)");
2378 let manifest = dir.path().join("Cargo.toml");
2379 assert_eq!(
2380 tagged_commit(dir.path(), &manifest, &older, &version_line).unwrap(),
2381 None
2382 );
2383 assert_eq!(
2384 tagged_commit(dir.path(), &manifest, &"0".repeat(40), &version_line).unwrap(),
2385 None
2386 );
2387 }
2388
2389 fn write_project(dir: &Path, version: &str) {
2392 fs::write(
2393 dir.join("project.yml"),
2394 indoc::formatdoc! {r#"
2395 name: Demo
2396 targets:
2397 Demo:
2398 settings:
2399 base:
2400 MARKETING_VERSION: "{version}"
2401 "#},
2402 )
2403 .unwrap();
2404 }
2405
2406 fn released_before_the_version_file(dir: &Path) -> String {
2410 init(dir);
2411 write_project(dir, "0.0.16");
2412 let released = commit_all(dir, "chore(release): version packages");
2413 fs::write(dir.join("VERSION"), "0.0.16\n").unwrap();
2414 commit_all(dir, "chore: version the app through a VERSION file");
2415 released
2416 }
2417
2418 fn released_beside_the_version_file(dir: &Path) -> String {
2422 init(dir);
2423 write_project(dir, "0.0.16");
2424 let start = commit_all(dir, "chore: start");
2425 git(dir, &["checkout", "-q", "--detach", &start]);
2426 fs::write(dir.join("publish.yml"), "published\n").unwrap();
2427 let released = commit_all(dir, "ci: publish");
2428 git(dir, &["checkout", "-q", "main"]);
2429 fs::write(dir.join("VERSION"), "0.0.16\n").unwrap();
2430 commit_all(dir, "chore: version the app through a VERSION file");
2431 released
2432 }
2433
2434 fn keep_merged(dir: &Path, sha: &str) {
2437 git(
2438 dir,
2439 &[
2440 "merge",
2441 "-q",
2442 "-s",
2443 "ours",
2444 "-m",
2445 "forkctl: keep published history",
2446 sha,
2447 ],
2448 );
2449 }
2450
2451 #[test]
2452 fn a_tag_on_a_commit_before_the_version_file_existed_is_the_release() {
2453 let dir = tempfile::TempDir::new().unwrap();
2454 let released = released_before_the_version_file(dir.path());
2455 let found = tagged_commit(
2456 dir.path(),
2457 &dir.path().join("VERSION"),
2458 &released,
2459 &version_file,
2460 )
2461 .unwrap();
2462 assert_eq!(
2463 found,
2464 Some(VersionCommit {
2465 sha: released,
2466 depth: 1,
2467 })
2468 );
2469 }
2470
2471 #[test]
2472 fn a_merged_tag_on_a_commit_before_the_version_file_existed_is_the_release() {
2473 let dir = tempfile::TempDir::new().unwrap();
2474 let released = released_beside_the_version_file(dir.path());
2475 keep_merged(dir.path(), &released);
2476 let found = tagged_commit(
2477 dir.path(),
2478 &dir.path().join("VERSION"),
2479 &released,
2480 &version_file,
2481 )
2482 .unwrap();
2483 assert_eq!(
2484 found,
2485 Some(VersionCommit {
2486 sha: released,
2487 depth: 0,
2488 })
2489 );
2490 }
2491
2492 #[test]
2493 fn an_unreached_tag_before_the_version_file_existed_is_not_the_release() {
2494 let dir = tempfile::TempDir::new().unwrap();
2495 let released = released_beside_the_version_file(dir.path());
2496 let found = tagged_commit(
2497 dir.path(),
2498 &dir.path().join("VERSION"),
2499 &released,
2500 &version_file,
2501 )
2502 .unwrap();
2503 assert_eq!(found, None);
2504 }
2505
2506 #[test]
2507 fn a_tag_on_a_commit_with_a_directory_at_the_version_path_is_not_the_release() {
2508 let dir = tempfile::TempDir::new().unwrap();
2509 init(dir.path());
2510 fs::create_dir(dir.path().join("VERSION")).unwrap();
2511 fs::write(dir.path().join("VERSION").join("README"), "a directory\n").unwrap();
2512 let tagged = commit_all(dir.path(), "chore: a directory at the path");
2513 fs::remove_dir_all(dir.path().join("VERSION")).unwrap();
2514 fs::write(dir.path().join("VERSION"), "0.0.16\n").unwrap();
2515 commit_all(dir.path(), "chore: version the app through a VERSION file");
2516 let found = tagged_commit(
2517 dir.path(),
2518 &dir.path().join("VERSION"),
2519 &tagged,
2520 &version_file,
2521 )
2522 .unwrap();
2523 assert_eq!(found, None);
2524 }
2525
2526 fn rewritten_and_merged_back(dir: &Path, published_version: &str) -> String {
2533 init(dir);
2534 write_version(dir, "0.0.1");
2535 fs::write(dir.join("publish.yml"), "one\n").unwrap();
2536 let set = commit_all(dir, "chore: start");
2537 write_version(dir, published_version);
2538 fs::write(dir.join("publish.yml"), "two\n").unwrap();
2539 let published = commit_all(dir, "ci: publish");
2540 git(dir, &["checkout", "-q", "--detach", &set]);
2541 fs::write(dir.join("publish.yml"), "three\n").unwrap();
2542 commit_all(dir, "ci: rewritten publish");
2543 keep_merged(dir, &published);
2544 published
2545 }
2546
2547 #[test]
2548 fn a_tag_on_a_merged_commit_at_the_same_version_is_the_release() {
2549 let dir = tempfile::TempDir::new().unwrap();
2550 let published = rewritten_and_merged_back(dir.path(), "0.0.1");
2551 assert_ne!(
2552 git(dir.path(), &["rev-parse", "HEAD^1:publish.yml"]),
2553 git(
2554 dir.path(),
2555 &["rev-parse", &format!("{published}:publish.yml")]
2556 ),
2557 "the first-parent commit at the same version changes another file"
2558 );
2559 let found = tagged_commit(
2560 dir.path(),
2561 &dir.path().join("Cargo.toml"),
2562 &published,
2563 &version_line,
2564 )
2565 .unwrap();
2566 assert_eq!(
2567 found,
2568 Some(VersionCommit {
2569 sha: published,
2570 depth: 0,
2571 })
2572 );
2573 }
2574
2575 #[test]
2576 fn a_tag_merged_several_commits_below_head_takes_the_depth_of_the_merge() {
2577 let dir = tempfile::TempDir::new().unwrap();
2578 let published = rewritten_and_merged_back(dir.path(), "0.0.1");
2579 for later in 1..=5 {
2580 fs::write(dir.path().join("README"), format!("later {later}\n")).unwrap();
2581 commit_all(dir.path(), &format!("docs: later {later}"));
2582 }
2583 let found = tagged_commit(
2584 dir.path(),
2585 &dir.path().join("Cargo.toml"),
2586 &published,
2587 &version_line,
2588 )
2589 .unwrap();
2590 assert_eq!(
2591 found,
2592 Some(VersionCommit {
2593 sha: published,
2594 depth: 5,
2595 })
2596 );
2597 }
2598
2599 #[test]
2600 fn a_tag_on_a_merged_commit_at_another_version_is_not_the_release() {
2601 let dir = tempfile::TempDir::new().unwrap();
2602 let published = rewritten_and_merged_back(dir.path(), "0.0.2");
2603 assert_eq!(
2604 tagged_commit(
2605 dir.path(),
2606 &dir.path().join("Cargo.toml"),
2607 &published,
2608 &version_line,
2609 )
2610 .unwrap(),
2611 None
2612 );
2613 }
2614
2615 #[test]
2616 fn a_tag_on_a_commit_head_does_not_contain_is_not_the_release() {
2617 let dir = tempfile::TempDir::new().unwrap();
2618 init(dir.path());
2619 write_version(dir.path(), "0.0.1");
2620 let set = commit_all(dir.path(), "chore: start");
2621 fs::write(dir.path().join("publish.yml"), "two\n").unwrap();
2622 let abandoned = commit_all(dir.path(), "ci: publish");
2623 git(dir.path(), &["checkout", "-q", "--detach", &set]);
2624 fs::write(dir.path().join("publish.yml"), "three\n").unwrap();
2625 commit_all(dir.path(), "ci: rewritten publish");
2626 assert_eq!(
2627 tagged_commit(
2628 dir.path(),
2629 &dir.path().join("Cargo.toml"),
2630 &abandoned,
2631 &version_line,
2632 )
2633 .unwrap(),
2634 None
2635 );
2636 }
2637
2638 #[test]
2639 fn file_at_reads_a_file_at_a_commit_and_nothing_before_it() {
2640 let dir = tempfile::TempDir::new().unwrap();
2641 init(dir.path());
2642 fs::write(dir.path().join("README"), "start\n").unwrap();
2643 let before = commit_all(dir.path(), "chore: start");
2644 fs::create_dir_all(dir.path().join(".ctl")).unwrap();
2645 fs::write(dir.path().join(".ctl/ver.yaml"), "packages: []\n").unwrap();
2646 let added = commit_all(dir.path(), "chore: add the config");
2647 fs::write(dir.path().join(".ctl/ver.yaml"), "packages: [later]\n").unwrap();
2648 commit_all(dir.path(), "chore: change the config");
2649 let path = Path::new(".ctl/ver.yaml");
2650 assert_eq!(
2651 file_at(dir.path(), &added, path).unwrap().as_deref(),
2652 Some("packages: []\n")
2653 );
2654 assert_eq!(file_at(dir.path(), &before, path).unwrap(), None);
2655 }
2656
2657 #[test]
2658 fn added_by_names_the_commit_that_added_the_file() {
2659 let dir = tempfile::TempDir::new().unwrap();
2660 init(dir.path());
2661 fs::write(dir.path().join("README"), "start\n").unwrap();
2662 commit_all(dir.path(), "chore: start");
2663 fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2664 let added = commit_all(dir.path(), "fix: the parser (#12)");
2665 fs::write(dir.path().join("README"), "later\n").unwrap();
2666 commit_all(dir.path(), "docs: later");
2667 assert_eq!(
2668 added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
2669 Some(AddedBy {
2670 sha: added,
2671 subject: "fix: the parser (#12)".into(),
2672 })
2673 );
2674 }
2675
2676 #[test]
2679 fn added_by_follows_a_merge_to_the_commit_that_added_the_file() {
2680 let dir = tempfile::TempDir::new().unwrap();
2681 init(dir.path());
2682 fs::write(dir.path().join("README"), "start\n").unwrap();
2683 let base = commit_all(dir.path(), "chore: start");
2684 fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2685 let side = commit_all(dir.path(), "fix: the parser (#12)");
2686 git(dir.path(), &["reset", "-q", "--hard", &base]);
2687 fs::write(dir.path().join("README"), "later\n").unwrap();
2688 let main = commit_all(dir.path(), "docs: later (#13)");
2689 fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2690 git(dir.path(), &["add", "-A"]);
2691 let tree = git(dir.path(), &["write-tree"]);
2692 let merge = git(
2693 dir.path(),
2694 &[
2695 "commit-tree",
2696 &tree,
2697 "-p",
2698 &main,
2699 "-p",
2700 &side,
2701 "-m",
2702 "feat: release next (#14)",
2703 ],
2704 );
2705 git(dir.path(), &["reset", "-q", "--hard", &merge]);
2706 assert_eq!(
2707 added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
2708 Some(AddedBy {
2709 sha: side,
2710 subject: "fix: the parser (#12)".into(),
2711 })
2712 );
2713 }
2714
2715 #[test]
2719 fn added_by_names_a_titled_merge_over_an_unnamed_branch_commit() {
2720 let dir = tempfile::TempDir::new().unwrap();
2721 init(dir.path());
2722 fs::write(dir.path().join("README"), "start\n").unwrap();
2723 let base = commit_all(dir.path(), "chore: start");
2724 fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2725 let side = commit_all(dir.path(), "wip");
2726 git(dir.path(), &["reset", "-q", "--hard", &base]);
2727 fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2728 git(dir.path(), &["add", "-A"]);
2729 let tree = git(dir.path(), &["write-tree"]);
2730 let merge = git(
2731 dir.path(),
2732 &[
2733 "commit-tree",
2734 &tree,
2735 "-p",
2736 &base,
2737 "-p",
2738 &side,
2739 "-m",
2740 "fix: the parser (#12)",
2741 ],
2742 );
2743 git(dir.path(), &["reset", "-q", "--hard", &merge]);
2744 assert_eq!(
2745 added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
2746 Some(AddedBy {
2747 sha: merge,
2748 subject: "fix: the parser (#12)".into(),
2749 })
2750 );
2751 }
2752
2753 #[test]
2757 fn added_by_keeps_the_adding_pull_request_after_an_edit() {
2758 let dir = tempfile::TempDir::new().unwrap();
2759 init(dir.path());
2760 fs::write(dir.path().join("README"), "start\n").unwrap();
2761 let base = commit_all(dir.path(), "chore: start");
2762 fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2763 let side = commit_all(dir.path(), "wip");
2764 git(dir.path(), &["reset", "-q", "--hard", &base]);
2765 fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2766 git(dir.path(), &["add", "-A"]);
2767 let tree = git(dir.path(), &["write-tree"]);
2768 let added = git(
2769 dir.path(),
2770 &[
2771 "commit-tree",
2772 &tree,
2773 "-p",
2774 &base,
2775 "-p",
2776 &side,
2777 "-m",
2778 "fix: the parser (#12)",
2779 ],
2780 );
2781 git(dir.path(), &["reset", "-q", "--hard", &added]);
2782 fs::write(dir.path().join("fix.md"), "Fix, reworded.\n").unwrap();
2783 let edit = commit_all(dir.path(), "docs: reword the fix");
2784 git(dir.path(), &["reset", "-q", "--hard", &added]);
2785 fs::write(dir.path().join("fix.md"), "Fix, reworded.\n").unwrap();
2786 git(dir.path(), &["add", "-A"]);
2787 let tree = git(dir.path(), &["write-tree"]);
2788 let edited = git(
2789 dir.path(),
2790 &[
2791 "commit-tree",
2792 &tree,
2793 "-p",
2794 &added,
2795 "-p",
2796 &edit,
2797 "-m",
2798 "docs: reword the fix (#13)",
2799 ],
2800 );
2801 git(dir.path(), &["reset", "-q", "--hard", &edited]);
2802 fs::write(dir.path().join("fix.md"), "Fix, reworded again.\n").unwrap();
2803 commit_all(dir.path(), "docs: reword the fix again (#14)");
2804 assert_eq!(
2805 added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
2806 Some(AddedBy {
2807 sha: added,
2808 subject: "fix: the parser (#12)".into(),
2809 })
2810 );
2811 }
2812
2813 #[test]
2816 fn added_by_names_nothing_past_a_shallow_boundary() {
2817 let dir = tempfile::TempDir::new().unwrap();
2818 init(dir.path());
2819 fs::write(dir.path().join("fix.md"), "Fix.\n").unwrap();
2820 commit_all(dir.path(), "fix: the parser (#12)");
2821 fs::write(dir.path().join("README"), "later\n").unwrap();
2822 let boundary = commit_all(dir.path(), "docs: later (#13)");
2823 fs::write(dir.path().join(".git/shallow"), format!("{boundary}\n")).unwrap();
2824 assert_eq!(
2825 git(dir.path(), &["rev-parse", "--is-shallow-repository"]),
2826 "true"
2827 );
2828 assert_eq!(
2829 added_by(dir.path(), &dir.path().join("fix.md")).unwrap(),
2830 None
2831 );
2832 }
2833
2834 #[test]
2835 fn origin_url_from_discovered_repo() {
2836 let dir = tempfile::TempDir::new().unwrap();
2837 init(dir.path());
2838 git(
2839 dir.path(),
2840 &[
2841 "remote",
2842 "add",
2843 "origin",
2844 "https://github.com/victor-software-house/verctl.git",
2845 ],
2846 );
2847 commit_all(dir.path(), "init");
2848 assert_eq!(
2849 origin_url(dir.path()).unwrap(),
2850 "https://github.com/victor-software-house/verctl.git"
2851 );
2852 }
2853
2854 #[test]
2855 fn empty_paths_do_not_switch_head() {
2856 let dir = tempfile::TempDir::new().unwrap();
2857 init(dir.path());
2858 commit_all(dir.path(), "init");
2859 let before = git(dir.path(), &["symbolic-ref", "HEAD"]);
2860 let repo_id = Repo {
2861 owner: "victor-software-house".into(),
2862 name: "verctl".into(),
2863 };
2864 let out = super::commit_branch_and_push(
2865 dir.path(),
2866 "verctl/release/main",
2867 "chore",
2868 "unused",
2869 &repo_id,
2870 &[],
2871 )
2872 .unwrap();
2873 assert_eq!(out, super::PushOutcome::Empty);
2874 assert_eq!(git(dir.path(), &["symbolic-ref", "HEAD"]), before);
2875 }
2876
2877 #[test]
2878 fn unexpected_dirty_fails_unless_globbed() {
2879 let dir = tempfile::TempDir::new().unwrap();
2880 init(dir.path());
2881 fs::write(
2882 dir.path().join("Cargo.toml"),
2883 indoc! {r#"
2884 [package]
2885 version = "1.0.0"
2886 "#},
2887 )
2888 .unwrap();
2889 commit_all(dir.path(), "init");
2890 fs::write(dir.path().join("secret.env"), "TOKEN=leak\n").unwrap();
2891 let allowed = [dir.path().join("Cargo.toml")];
2892 let err = super::assert_only_allowed(dir.path(), &allowed, &[], super::IgnoredFiles::Skip)
2893 .unwrap_err();
2894 assert!(format!("{err:#}").contains("secret.env"), "{err:#}");
2895 let staged = super::assert_only_allowed(
2896 dir.path(),
2897 &allowed,
2898 &["*.env".into()],
2899 super::IgnoredFiles::Skip,
2900 )
2901 .unwrap();
2902 assert_eq!(staged.len(), 1);
2903 assert!(staged[0].ends_with("secret.env"), "{staged:?}");
2904 }
2905
2906 #[test]
2907 fn stage_glob_collects_a_deleted_file() {
2908 let dir = tempfile::TempDir::new().unwrap();
2909 init(dir.path());
2910 fs::write(dir.path().join("Cargo.lock"), "old\n").unwrap();
2911 fs::write(
2912 dir.path().join("Cargo.toml"),
2913 indoc! {r#"
2914 [package]
2915 version = "1.0.0"
2916 "#},
2917 )
2918 .unwrap();
2919 commit_all(dir.path(), "init");
2920 fs::remove_file(dir.path().join("Cargo.lock")).unwrap();
2921 let staged = super::assert_only_allowed(
2922 dir.path(),
2923 &[dir.path().join("Cargo.toml")],
2924 &["Cargo.lock".into()],
2925 super::IgnoredFiles::Skip,
2926 )
2927 .unwrap();
2928 assert_eq!(staged.len(), 1);
2929 assert!(staged[0].ends_with("Cargo.lock"), "{staged:?}");
2930 assert!(!dir.path().join("Cargo.lock").exists());
2931 }
2932
2933 #[test]
2934 fn stage_glob_collects_files_under_a_tree_not_the_directory() {
2935 let dir = tempfile::TempDir::new().unwrap();
2936 init(dir.path());
2937 fs::write(
2938 dir.path().join("Cargo.toml"),
2939 indoc! {r#"
2940 [package]
2941 version = "1.0.0"
2942 "#},
2943 )
2944 .unwrap();
2945 commit_all(dir.path(), "init");
2946 fs::create_dir_all(dir.path().join("src")).unwrap();
2947 fs::write(dir.path().join("src/lib.rs"), "fn x() {}\n").unwrap();
2948 let staged = super::assert_only_allowed(
2949 dir.path(),
2950 &[dir.path().join("Cargo.toml")],
2951 &["src/**".into()],
2952 super::IgnoredFiles::Skip,
2953 )
2954 .unwrap();
2955 assert_eq!(staged.len(), 1);
2956 assert!(staged[0].ends_with("src/lib.rs"), "{staged:?}");
2957 assert!(!staged.iter().any(|path| path.ends_with("src")));
2958 }
2959
2960 #[test]
2961 fn ignored_workdir_paths_are_not_unexpected() {
2962 let dir = tempfile::TempDir::new().unwrap();
2963 init(dir.path());
2964 fs::write(dir.path().join(".gitignore"), "/target\n").unwrap();
2965 fs::write(
2966 dir.path().join("Cargo.toml"),
2967 indoc! {r#"
2968 [package]
2969 version = "1.0.0"
2970 "#},
2971 )
2972 .unwrap();
2973 commit_all(dir.path(), "init");
2974 fs::create_dir_all(dir.path().join("target/debug")).unwrap();
2975 fs::write(dir.path().join("target/debug/verctl"), "bin\n").unwrap();
2976 super::assert_only_allowed(
2977 dir.path(),
2978 &[dir.path().join("Cargo.toml")],
2979 &[],
2980 super::IgnoredFiles::Skip,
2981 )
2982 .unwrap();
2983 }
2984
2985 #[test]
2986 fn stage_ignored_opt_in_collects_gitignored_files() {
2987 let dir = tempfile::TempDir::new().unwrap();
2988 init(dir.path());
2989 fs::write(dir.path().join(".gitignore"), "/generated.rs\n").unwrap();
2990 fs::write(
2991 dir.path().join("Cargo.toml"),
2992 indoc! {r#"
2993 [package]
2994 version = "1.0.0"
2995 "#},
2996 )
2997 .unwrap();
2998 commit_all(dir.path(), "init");
2999 fs::write(dir.path().join("generated.rs"), "gen\n").unwrap();
3000 let allowed = [dir.path().join("Cargo.toml")];
3001 let off = super::assert_only_allowed(
3002 dir.path(),
3003 &allowed,
3004 &["generated.rs".into()],
3005 super::IgnoredFiles::Skip,
3006 )
3007 .unwrap();
3008 assert!(off.is_empty(), "{off:?}");
3009 let on = super::assert_only_allowed(
3010 dir.path(),
3011 &allowed,
3012 &["generated.rs".into()],
3013 super::IgnoredFiles::Include,
3014 )
3015 .unwrap();
3016 assert_eq!(on.len(), 1);
3017 assert!(on[0].ends_with("generated.rs"), "{on:?}");
3018 }
3019
3020 #[test]
3021 fn stage_ignored_recurses_a_gitignored_directory() {
3022 let dir = tempfile::TempDir::new().unwrap();
3023 init(dir.path());
3024 fs::write(dir.path().join(".gitignore"), "/dist\n").unwrap();
3025 fs::write(
3026 dir.path().join("Cargo.toml"),
3027 indoc! {r#"
3028 [package]
3029 version = "1.0.0"
3030 "#},
3031 )
3032 .unwrap();
3033 commit_all(dir.path(), "init");
3034 fs::create_dir_all(dir.path().join("dist")).unwrap();
3035 fs::write(dir.path().join("dist/out.js"), "ok\n").unwrap();
3036 let allowed = [dir.path().join("Cargo.toml")];
3037 let staged = super::assert_only_allowed(
3038 dir.path(),
3039 &allowed,
3040 &["dist/**".into()],
3041 super::IgnoredFiles::Include,
3042 )
3043 .unwrap();
3044 assert_eq!(staged.len(), 1);
3045 assert!(staged[0].ends_with("dist/out.js"), "{staged:?}");
3046 }
3047
3048 #[test]
3049 fn stage_ignored_pathspec_does_not_collect_other_ignored_trees() {
3050 let dir = tempfile::TempDir::new().unwrap();
3051 init(dir.path());
3052 fs::write(dir.path().join(".gitignore"), "/dist\n/target\n").unwrap();
3053 fs::write(
3054 dir.path().join("Cargo.toml"),
3055 indoc! {r#"
3056 [package]
3057 version = "1.0.0"
3058 "#},
3059 )
3060 .unwrap();
3061 commit_all(dir.path(), "init");
3062 fs::create_dir_all(dir.path().join("dist")).unwrap();
3063 fs::write(dir.path().join("dist/out.js"), "ok\n").unwrap();
3064 fs::create_dir_all(dir.path().join("target/debug")).unwrap();
3065 fs::write(dir.path().join("target/debug/verctl"), "bin\n").unwrap();
3066 fs::write(dir.path().join("target/CACHEDIR.TAG"), "tag\n").unwrap();
3067 let staged = super::assert_only_allowed(
3068 dir.path(),
3069 &[dir.path().join("Cargo.toml")],
3070 &["dist/**".into()],
3071 super::IgnoredFiles::Include,
3072 )
3073 .unwrap();
3074 assert_eq!(staged.len(), 1, "{staged:?}");
3075 assert!(staged[0].ends_with("dist/out.js"), "{staged:?}");
3076 assert!(
3077 !staged
3078 .iter()
3079 .any(|path| path.to_string_lossy().contains("target")),
3080 "{staged:?}"
3081 );
3082 }
3083
3084 #[test]
3085 fn write_commit_on_branch_removes_a_deleted_staged_path() {
3086 let dir = tempfile::TempDir::new().unwrap();
3087 init(dir.path());
3088 fs::write(dir.path().join("Cargo.lock"), "old\n").unwrap();
3089 fs::write(
3090 dir.path().join("Cargo.toml"),
3091 indoc! {r#"
3092 [package]
3093 version = "1.0.0"
3094 "#},
3095 )
3096 .unwrap();
3097 commit_all(dir.path(), "init");
3098 fs::remove_file(dir.path().join("Cargo.lock")).unwrap();
3099 let staged = super::assert_only_allowed(
3100 dir.path(),
3101 &[dir.path().join("Cargo.toml")],
3102 &["Cargo.lock".into()],
3103 super::IgnoredFiles::Skip,
3104 )
3105 .unwrap();
3106 let oid = write_commit(dir.path(), &staged).expect("deletion should commit");
3107 let names = tree_names(dir.path(), &oid);
3108 assert!(!names.iter().any(|name| name == "Cargo.lock"), "{names:?}");
3109 assert!(names.iter().any(|name| name == "Cargo.toml"), "{names:?}");
3110 }
3111
3112 #[test]
3113 fn commit_only_lists_given_paths() {
3114 let dir = tempfile::TempDir::new().unwrap();
3115 init(dir.path());
3116 fs::write(
3117 dir.path().join("Cargo.toml"),
3118 indoc! {r#"
3119 [package]
3120 version = "1.0.0"
3121 "#},
3122 )
3123 .unwrap();
3124 let parent = commit_all(dir.path(), "init");
3125 fs::write(
3126 dir.path().join("Cargo.toml"),
3127 indoc! {r#"
3128 [package]
3129 version = "1.0.1"
3130 "#},
3131 )
3132 .unwrap();
3133 fs::write(
3134 dir.path().join("secret.env"),
3135 indoc! {"
3136 TOKEN=leak
3137 "},
3138 )
3139 .unwrap();
3140 let oid = write_commit(dir.path(), &[dir.path().join("Cargo.toml")]).expect("commit");
3141 let names = tree_names(dir.path(), &oid);
3142 assert!(names.iter().any(|name| name == "Cargo.toml"), "{names:?}");
3143 assert!(!names.iter().any(|name| name == "secret.env"), "{names:?}");
3144 assert_eq!(git(dir.path(), &["rev-parse", "HEAD"]), parent);
3145 }
3146
3147 #[test]
3148 fn dotted_relative_paths_stage() {
3149 let dir = tempfile::TempDir::new().unwrap();
3150 init(dir.path());
3151 fs::write(
3152 dir.path().join("Cargo.toml"),
3153 indoc! {r#"
3154 [package]
3155 version = "1.0.0"
3156 "#},
3157 )
3158 .unwrap();
3159 commit_all(dir.path(), "init");
3160 fs::write(
3161 dir.path().join("Cargo.toml"),
3162 indoc! {r#"
3163 [package]
3164 version = "1.0.1"
3165 "#},
3166 )
3167 .unwrap();
3168 let oid =
3169 write_commit(dir.path(), &[Path::new("./Cargo.toml").to_path_buf()]).expect("commit");
3170 let names = tree_names(dir.path(), &oid);
3171 assert!(names.iter().any(|name| name == "Cargo.toml"), "{names:?}");
3172 }
3173
3174 #[tokio::test]
3177 async fn push_keeps_the_token_out_of_the_error() {
3178 let server = wiremock::MockServer::start().await;
3179 wiremock::Mock::given(matchers::any())
3180 .respond_with(
3181 wiremock::ResponseTemplate::new(401)
3182 .insert_header("WWW-Authenticate", r#"Basic realm="git""#),
3183 )
3184 .mount(&server)
3185 .await;
3186 let (dir, _) = fixture();
3187 git(dir.path(), &["branch", "verctl/release/main"]);
3188 let url = format!("{}/owner/repo.git", server.uri());
3189 let token = "verctl-push-token-5f3a9c";
3190 let error = task::spawn_blocking(move || {
3191 super::push(&dir.path().join(".git"), &url, "verctl/release/main", token)
3192 })
3193 .await
3194 .unwrap()
3195 .unwrap_err();
3196 let message = format!("{error:#}");
3197 assert!(!message.contains(token), "{message}");
3198 let expected = format!("Basic {}", base64(&format!("x-access-token:{token}")));
3199 let requests = server.received_requests().await.unwrap();
3200 assert!(
3201 requests.iter().any(|request| {
3202 request
3203 .headers
3204 .get("authorization")
3205 .is_some_and(|value| value.as_bytes() == expected.as_bytes())
3206 }),
3207 "no request carried the token as Basic credentials"
3208 );
3209 }
3210
3211 fn base64(text: &str) -> String {
3213 const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3214 let mut out = String::new();
3215 for chunk in text.as_bytes().chunks(3) {
3216 let bytes = [
3217 chunk[0],
3218 chunk.get(1).copied().unwrap_or(0),
3219 chunk.get(2).copied().unwrap_or(0),
3220 ];
3221 let joined = u32::from(bytes[0]) << 16 | u32::from(bytes[1]) << 8 | u32::from(bytes[2]);
3222 for index in 0..4 {
3223 if index <= chunk.len() {
3224 let sextet = (joined >> (18 - 6 * index)) & 0x3f;
3225 out.push(char::from(ALPHABET[usize::try_from(sextet).unwrap()]));
3226 } else {
3227 out.push('=');
3228 }
3229 }
3230 }
3231 out
3232 }
3233
3234 #[test]
3237 fn the_commit_applies_clean_filters() {
3238 let dir = tempfile::TempDir::new().unwrap();
3239 init(dir.path());
3240 fs::write(dir.path().join(".gitattributes"), "*.md text\n").unwrap();
3241 fs::write(dir.path().join("CHANGELOG.md"), "old\n").unwrap();
3242 commit_all(dir.path(), "init");
3243 fs::write(dir.path().join("CHANGELOG.md"), "a\r\nb\r\n").unwrap();
3244 let oid = write_commit(dir.path(), &[dir.path().join("CHANGELOG.md")]).expect("commit");
3245 let blob = format!("{oid}:CHANGELOG.md");
3246 assert_eq!(git(dir.path(), &["cat-file", "-p", &blob]), "a\nb");
3247 }
3248
3249 #[test]
3253 fn a_configured_identity_wins_over_the_fallback() {
3254 let dir = tempfile::TempDir::new().unwrap();
3255 init(dir.path());
3256 git(dir.path(), &["config", "user.name", "Configured Name"]);
3257 git(
3258 dir.path(),
3259 &["config", "user.email", "configured@example.com"],
3260 );
3261 fs::write(dir.path().join("Cargo.toml"), "version = 1\n").unwrap();
3262 commit_all(dir.path(), "init");
3263 fs::write(dir.path().join("Cargo.toml"), "version = 2\n").unwrap();
3264 let oid = write_commit(dir.path(), &[dir.path().join("Cargo.toml")]).expect("commit");
3265 let configured = "Configured Name <configured@example.com>";
3266 assert_eq!(
3267 git(
3268 dir.path(),
3269 &["log", "-1", "--format=%an <%ae>|%cn <%ce>", &oid]
3270 ),
3271 format!("{configured}|{configured}")
3272 );
3273 assert_eq!(
3274 git(
3275 dir.path(),
3276 &[
3277 "log",
3278 "-g",
3279 "-1",
3280 "--format=%gn <%ge>",
3281 "refs/heads/verctl/release/main",
3282 ],
3283 ),
3284 configured
3285 );
3286 }
3287
3288 #[test]
3293 fn a_workdir_found_from_dot_resolves_paths() {
3294 let repo = super::discover(Path::new(".")).unwrap();
3295 let workdir = super::absolute_workdir(&repo).unwrap();
3296 assert!(workdir.is_absolute(), "{}", workdir.display());
3297 assert_eq!(
3298 super::workdir_rel(&workdir, Path::new("./Cargo.toml")).unwrap(),
3299 Path::new("Cargo.toml")
3300 );
3301 }
3302
3303 #[cfg(unix)]
3306 #[test]
3307 fn a_symlinked_workdir_takes_canonical_paths() {
3308 let dir = tempfile::TempDir::new().unwrap();
3309 init(dir.path());
3310 fs::write(dir.path().join("Cargo.toml"), "version = 1\n").unwrap();
3311 commit_all(dir.path(), "init");
3312 fs::write(dir.path().join("Cargo.toml"), "version = 2\n").unwrap();
3313 let links = tempfile::TempDir::new().unwrap();
3314 let link = links.path().join("checkout");
3315 symlink(dir.path(), &link).unwrap();
3316 let canonical = dir.path().canonicalize().unwrap().join("Cargo.toml");
3317 let workdir = super::absolute_workdir(&super::discover(&link).unwrap()).unwrap();
3318 assert_eq!(
3319 super::workdir_rel(&workdir, &canonical).unwrap(),
3320 Path::new("Cargo.toml")
3321 );
3322 assert_eq!(
3323 super::workdir_rel(&workdir, &link.join("Cargo.toml")).unwrap(),
3324 Path::new("Cargo.toml")
3325 );
3326 }
3327
3328 fn write_commit(dir: &Path, paths: &[PathBuf]) -> Option<String> {
3331 let repo = super::discover(dir).unwrap();
3332 let workdir = super::absolute_workdir(&repo).unwrap();
3333 let parent = repo.head_commit().unwrap();
3334 super::write_commit_on_branch(
3335 &repo,
3336 &workdir,
3337 &parent,
3338 "verctl/release/main",
3339 "chore",
3340 paths,
3341 )
3342 .unwrap()
3343 .map(|id| id.to_string())
3344 }
3345
3346 fn stock() -> Vec<String> {
3347 super::candidate_names(None)
3348 }
3349
3350 fn fixture() -> (tempfile::TempDir, String) {
3351 let dir = tempfile::TempDir::new().unwrap();
3352 init(dir.path());
3353 let sha = commit_all(dir.path(), "init");
3354 (dir, sha)
3355 }
3356
3357 fn add_origin(dir: &Path) {
3358 git(
3359 dir,
3360 &[
3361 "remote",
3362 "add",
3363 "origin",
3364 "https://github.com/victor-software-house/verctl.git",
3365 ],
3366 );
3367 }
3368
3369 fn track(dir: &Path, name: &str, sha: &str) {
3370 git(
3371 dir,
3372 &["update-ref", &format!("refs/remotes/origin/{name}"), sha],
3373 );
3374 }
3375
3376 fn set_origin_head(dir: &Path, name: &str) {
3377 git(
3378 dir,
3379 &[
3380 "symbolic-ref",
3381 "refs/remotes/origin/HEAD",
3382 &format!("refs/remotes/origin/{name}"),
3383 ],
3384 );
3385 }
3386
3387 fn prove(root: &Path, candidates: &[String]) -> anyhow::Result<()> {
3389 match super::prove_default_history(root, candidates)? {
3390 None => Ok(()),
3391 Some(off) => anyhow::bail!(off),
3392 }
3393 }
3394
3395 #[test]
3396 fn candidate_names_are_base_ref_then_main_master() {
3397 assert_eq!(super::candidate_names(None), ["main", "master"]);
3398 assert_eq!(super::candidate_names(Some("")), ["main", "master"]);
3399 assert_eq!(super::candidate_names(Some(" ")), ["main", "master"]);
3400 assert_eq!(
3401 super::candidate_names(Some("trunk")),
3402 ["trunk", "main", "master"]
3403 );
3404 assert_eq!(super::candidate_names(Some("main")), ["main", "master"]);
3405 assert_eq!(
3406 super::candidate_names(Some("release/1.0")),
3407 ["release/1.0", "main", "master"]
3408 );
3409 }
3410
3411 #[test]
3412 fn no_repository_refuses() {
3413 let dir = tempfile::TempDir::new().unwrap();
3414 let err = prove(dir.path(), &stock()).unwrap_err();
3415 assert!(
3416 format!("{err:#}").contains("release cannot prove HEAD"),
3417 "{err:#}"
3418 );
3419 assert!(format!("{err:#}").contains("no git repository"), "{err:#}");
3420 }
3421
3422 #[test]
3423 fn no_head_commit_refuses() {
3424 let dir = tempfile::TempDir::new().unwrap();
3425 init(dir.path());
3426 let err = prove(dir.path(), &stock()).unwrap_err();
3427 assert!(format!("{err:#}").contains("HEAD has no commit"), "{err:#}");
3428 }
3429
3430 #[test]
3431 fn a_missing_origin_refuses() {
3432 let (dir, _) = fixture();
3433 let err = prove(dir.path(), &stock()).unwrap_err();
3434 assert!(format!("{err:#}").contains("no `origin` remote"), "{err:#}");
3435 }
3436
3437 #[test]
3438 fn head_on_origin_main_is_ok() {
3439 let (dir, sha) = fixture();
3440 add_origin(dir.path());
3441 track(dir.path(), "main", &sha);
3442 prove(dir.path(), &stock()).unwrap();
3443 }
3444
3445 #[test]
3446 fn head_sha_is_the_peeled_head_commit() {
3447 let (dir, sha) = fixture();
3448 assert_eq!(super::head_sha(dir.path()).unwrap(), sha);
3449 }
3450
3451 #[test]
3452 fn origin_master_without_head_is_ok() {
3453 let (dir, sha) = fixture();
3454 add_origin(dir.path());
3455 track(dir.path(), "master", &sha);
3456 prove(dir.path(), &stock()).unwrap();
3457 }
3458
3459 #[test]
3460 fn origin_head_to_non_main_is_ok() {
3461 let (dir, sha) = fixture();
3462 add_origin(dir.path());
3463 track(dir.path(), "trunk", &sha);
3464 set_origin_head(dir.path(), "trunk");
3465 prove(dir.path(), &stock()).unwrap();
3466 }
3467
3468 #[test]
3469 fn base_ref_trunk_without_origin_head_is_ok() {
3470 let (dir, sha) = fixture();
3471 add_origin(dir.path());
3472 track(dir.path(), "trunk", &sha);
3473 prove(dir.path(), &super::candidate_names(Some("trunk"))).unwrap();
3474 }
3475
3476 #[test]
3477 fn origin_without_default_tracking_ref_fails() {
3478 let (dir, _) = fixture();
3479 add_origin(dir.path());
3480 let err = prove(dir.path(), &stock()).unwrap_err();
3481 assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
3482 }
3483
3484 #[test]
3485 fn origin_trunk_alone_needs_head_or_base_ref() {
3486 let (dir, sha) = fixture();
3487 add_origin(dir.path());
3488 track(dir.path(), "trunk", &sha);
3489 let err = prove(dir.path(), &stock()).unwrap_err();
3490 assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
3491 prove(dir.path(), &super::candidate_names(Some("trunk"))).unwrap();
3492 set_origin_head(dir.path(), "trunk");
3493 prove(dir.path(), &stock()).unwrap();
3494 }
3495
3496 #[test]
3497 fn origin_hotfix_alone_is_not_the_default() {
3498 let (dir, sha) = fixture();
3499 add_origin(dir.path());
3500 track(dir.path(), "hotfix", &sha);
3501 let err = prove(dir.path(), &stock()).unwrap_err();
3502 assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
3503 }
3504
3505 #[test]
3506 fn unpeelable_origin_head_does_not_fall_through_to_main() {
3507 let (dir, sha) = fixture();
3508 add_origin(dir.path());
3509 track(dir.path(), "main", &sha);
3510 set_origin_head(dir.path(), "trunk");
3511 let err = prove(dir.path(), &stock()).unwrap_err();
3512 assert!(format!("{err:#}").contains("origin/trunk"), "{err:#}");
3513 }
3514
3515 #[test]
3516 fn github_https_url_has_no_credentials() {
3517 let url = super::github_https_url("victor-software-house/qctl");
3518 assert_eq!(url, "https://github.com/victor-software-house/qctl.git");
3519 let lower = url.to_ascii_lowercase();
3520 assert!(!lower.contains("bearer"), "{url}");
3521 assert!(!lower.contains("token"), "{url}");
3522 assert!(!lower.contains("x-access-token"), "{url}");
3523 }
3524
3525 #[test]
3526 fn github_git_user_is_x_access_token() {
3527 assert_eq!(super::github_git_user(), "x-access-token");
3528 }
3529
3530 #[test]
3531 fn ensure_origin_head_skips_fetch_when_the_ref_exists() {
3532 let (dir, sha) = fixture();
3533 git(
3534 dir.path(),
3535 &["remote", "add", "origin", "https://127.0.0.1:1/nope.git"],
3536 );
3537 track(dir.path(), "main", &sha);
3538 super::ensure_origin_head(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3539 assert_eq!(
3540 git(dir.path(), &["symbolic-ref", "refs/remotes/origin/HEAD"]),
3541 "refs/remotes/origin/main"
3542 );
3543 }
3544
3545 #[test]
3546 fn ensure_origin_head_fetches_a_missing_ref_from_origin() {
3547 let upstream_dir = tempfile::TempDir::new().unwrap();
3548 init(upstream_dir.path());
3549 commit_all(upstream_dir.path(), "init");
3550
3551 let work_dir = tempfile::TempDir::new().unwrap();
3552 init(work_dir.path());
3553 commit_all(work_dir.path(), "local");
3554 let url = format!("file://{}", upstream_dir.path().display());
3555 git(work_dir.path(), &["remote", "add", "origin", &url]);
3556
3557 super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3558 git(
3559 work_dir.path(),
3560 &["rev-parse", "--verify", "refs/remotes/origin/main^{commit}"],
3561 );
3562 assert_eq!(
3563 git(
3564 work_dir.path(),
3565 &["symbolic-ref", "refs/remotes/origin/HEAD"]
3566 ),
3567 "refs/remotes/origin/main"
3568 );
3569 }
3570
3571 #[test]
3572 fn a_shallow_clone_gets_the_history_that_holds_the_tagged_commit() {
3573 let upstream = tempfile::TempDir::new().unwrap();
3574 init(upstream.path());
3575 write_version(upstream.path(), "0.0.1");
3576 commit_all(upstream.path(), "chore: start");
3577 write_version(upstream.path(), "0.0.2");
3578 let set = commit_all(upstream.path(), "chore(release): version packages");
3579 fs::write(upstream.path().join("README"), "later\n").unwrap();
3580 commit_all(upstream.path(), "docs: later");
3581
3582 let parent = tempfile::TempDir::new().unwrap();
3583 let url = format!("file://{}", upstream.path().display());
3584 git(
3585 parent.path(),
3586 &["clone", "-q", "--depth", "1", &url, "work"],
3587 );
3588 let work = parent.path().join("work");
3589 let manifest = work.join("Cargo.toml");
3590 let error = tagged_commit(&work, &manifest, &set, &version_line).unwrap_err();
3591 assert!(format!("{error:#}").contains("shallow"), "{error:#}");
3592
3593 super::ensure_full_history(&work, "main", &super::FetchDefault::Origin).unwrap();
3594 let found = tagged_commit(&work, &manifest, &set, &version_line).unwrap();
3595 assert_eq!(found, Some(VersionCommit { sha: set, depth: 1 }));
3596 }
3597
3598 #[test]
3599 fn a_full_clone_is_not_fetched_again() {
3600 let dir = tempfile::TempDir::new().unwrap();
3601 init(dir.path());
3602 commit_all(dir.path(), "init");
3603 git(
3605 dir.path(),
3606 &["remote", "add", "origin", "file:///nonexistent/verctl"],
3607 );
3608 super::ensure_full_history(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3609 }
3610
3611 #[test]
3616 fn a_pull_request_merge_checkout_compares_against_its_merge_base() {
3617 let upstream = tempfile::TempDir::new().unwrap();
3618 let up = upstream.path();
3619 init(up);
3620 write_version(up, "0.0.1");
3621 commit_all(up, "chore: start");
3622 write_version(up, "0.0.2");
3623 commit_all(up, "chore(release): version packages");
3624 git(up, &["checkout", "-q", "-b", "pr"]);
3625 fs::write(up.join("README"), "change\n").unwrap();
3626 commit_all(up, "docs: change");
3627 git(up, &["checkout", "-q", "--detach", "main"]);
3628 git(
3629 up,
3630 &["merge", "-q", "--no-ff", "pr", "-m", "Merge pr into main"],
3631 );
3632 git(up, &["update-ref", "refs/pull/1/merge", "HEAD"]);
3633 git(up, &["checkout", "-q", "main"]);
3634 write_version(up, "0.0.3");
3635 commit_all(up, "chore(release): version packages");
3636
3637 let work = tempfile::TempDir::new().unwrap();
3638 let dir = work.path();
3639 init(dir);
3640 let url = format!("file://{}", up.display());
3641 git(dir, &["remote", "add", "origin", &url]);
3642 git(
3643 dir,
3644 &[
3645 "fetch",
3646 "-q",
3647 "--depth=1",
3648 "origin",
3649 "+refs/pull/1/merge:refs/remotes/pull/1/merge",
3650 ],
3651 );
3652 git(
3653 dir,
3654 &["checkout", "-q", "--detach", "refs/remotes/pull/1/merge"],
3655 );
3656 assert_eq!(git(dir, &["rev-parse", "--is-shallow-repository"]), "true");
3657
3658 let manifest = [Path::new("Cargo.toml")];
3659 let candidates = ["main".to_owned()];
3660 let error = super::files_on_merge_base(dir, &manifest, &candidates).unwrap_err();
3661 assert!(
3662 format!("{error:#}").contains("fetch the default branch"),
3663 "{error:#}"
3664 );
3665
3666 super::ensure_comparable(dir, "main", &super::FetchDefault::Origin).unwrap();
3667 let files = super::files_on_merge_base(dir, &manifest, &candidates).unwrap();
3668 let base = files[0].as_deref().expect("Cargo.toml at the merge-base");
3669 assert_eq!(version_line(base).as_deref(), Some("0.0.2"));
3670 }
3671
3672 #[test]
3673 fn release_candidates_put_the_event_default_after_the_configured_branch() {
3674 assert_eq!(
3675 super::release_candidate_names(None, Some("trunk"), Some("develop")),
3676 ["trunk", "main", "master", "develop"]
3677 );
3678 assert_eq!(
3679 super::release_candidate_names(Some("stable"), Some("trunk"), None),
3680 ["stable", "trunk", "main", "master"]
3681 );
3682 assert_eq!(
3683 super::release_candidate_names(None, Some("main"), Some("main")),
3684 ["main", "master"]
3685 );
3686 assert_eq!(
3687 super::release_candidate_names(None, None, Some("develop")),
3688 ["main", "master", "develop"]
3689 );
3690 }
3691
3692 #[test]
3693 fn a_full_clone_with_the_branch_is_not_fetched_for_a_comparison() {
3694 let (dir, sha) = fixture();
3695 git(
3697 dir.path(),
3698 &["remote", "add", "origin", "file:///nonexistent/verctl"],
3699 );
3700 track(dir.path(), "main", &sha);
3701 super::ensure_comparable(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3702 }
3703
3704 #[test]
3705 fn a_full_clone_without_the_branch_fetches_it_for_a_comparison() {
3706 let upstream = tempfile::TempDir::new().unwrap();
3707 init(upstream.path());
3708 let tip = commit_all(upstream.path(), "init");
3709
3710 let work = tempfile::TempDir::new().unwrap();
3711 init(work.path());
3712 commit_all(work.path(), "local");
3713 let url = format!("file://{}", upstream.path().display());
3714 git(work.path(), &["remote", "add", "origin", &url]);
3715
3716 super::ensure_comparable(work.path(), "main", &super::FetchDefault::Origin).unwrap();
3717 assert_eq!(
3718 git(work.path(), &["rev-parse", "refs/remotes/origin/main"]),
3719 tip
3720 );
3721 }
3722
3723 #[test]
3724 fn fetch_one_branch_does_not_set_depth() {
3725 let src = include_str!("lib.rs");
3726 let prod = src.split("#[cfg(test)]").next().expect("production");
3727 assert!(
3728 !prod.contains("opts.depth"),
3729 "a depth-limited fetch leaves the tip parentless so graph_descendant_of cannot prove ancestry"
3730 );
3731 }
3732
3733 #[test]
3734 fn configured_default_branch_is_only_verctl_default_branch() {
3735 let src = include_str!("lib.rs");
3736 let start = src
3737 .find("pub fn configured_default_branch")
3738 .expect("configured_default_branch");
3739 let rest = &src[start..];
3740 let end = rest
3741 .find("pub fn ensure_origin_head")
3742 .expect("ensure_origin_head");
3743 let body = &rest[..end];
3744 assert!(!body.contains("GITHUB_BASE_REF"), "{body}");
3745 assert!(!body.contains("env_base_ref"), "{body}");
3746 }
3747
3748 #[test]
3749 fn fetched_default_branch_keeps_parents_for_ancestry() {
3750 let upstream_dir = tempfile::TempDir::new().unwrap();
3751 init(upstream_dir.path());
3752 commit_all(upstream_dir.path(), "A");
3753
3754 let work_dir = tempfile::TempDir::new().unwrap();
3755 init(work_dir.path());
3756 let url = format!("file://{}", upstream_dir.path().display());
3757 git(work_dir.path(), &["remote", "add", "origin", &url]);
3758 super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3759 let first = git(work_dir.path(), &["rev-parse", "refs/remotes/origin/main"]);
3760 git(
3761 work_dir.path(),
3762 &["update-ref", "--no-deref", "HEAD", &first],
3763 );
3764
3765 fs::write(upstream_dir.path().join("b.txt"), "b\n").unwrap();
3766 commit_all(upstream_dir.path(), "B");
3767 fs::write(upstream_dir.path().join("c.txt"), "c\n").unwrap();
3768 commit_all(upstream_dir.path(), "C");
3769
3770 git(
3771 work_dir.path(),
3772 &["update-ref", "-d", "refs/remotes/origin/main"],
3773 );
3774 git(
3775 work_dir.path(),
3776 &["symbolic-ref", "--delete", "refs/remotes/origin/HEAD"],
3777 );
3778 super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3779 prove(work_dir.path(), &stock()).unwrap();
3780 }
3781
3782 #[test]
3783 fn origin_head_wins_over_main_when_they_differ() {
3784 let (dir, first) = fixture();
3785 add_origin(dir.path());
3786 fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
3787 let second = commit_all(dir.path(), "ahead");
3788 track(dir.path(), "main", &first);
3789 track(dir.path(), "trunk", &second);
3790 set_origin_head(dir.path(), "trunk");
3791 prove(dir.path(), &stock()).unwrap();
3792 }
3793
3794 #[test]
3797 fn head_off_default_history_fails() {
3798 let (dir, first) = fixture();
3799 add_origin(dir.path());
3800 track(dir.path(), "main", &first);
3801 git(dir.path(), &["update-ref", "refs/heads/other", &first]);
3802 git(dir.path(), &["symbolic-ref", "HEAD", "refs/heads/other"]);
3803 fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
3804 let head = commit_all(dir.path(), "ahead");
3805 let off = super::prove_default_history(dir.path(), &stock())
3806 .unwrap()
3807 .unwrap();
3808 assert!(off.contains("not an ancestor"), "{off}");
3809 assert!(off.contains(&head), "{off}");
3810 assert!(off.contains(&first), "{off}");
3811 }
3812
3813 #[test]
3814 fn workflows_at_the_default_tip_match() {
3815 let (dir, _) = fixture();
3816 fs::create_dir_all(dir.path().join(".github/workflows")).unwrap();
3817 fs::write(dir.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
3818 let release = commit_all(dir.path(), "chore(release): version packages");
3819 fs::write(dir.path().join("README"), "later\n").unwrap();
3820 let tip = commit_all(dir.path(), "docs: later");
3821 add_origin(dir.path());
3822 track(dir.path(), "main", &tip);
3823 git(dir.path(), &["update-ref", "--no-deref", "HEAD", &release]);
3824 assert_eq!(super::workflows_differ(dir.path()).unwrap(), None);
3825 }
3826
3827 #[test]
3830 fn a_workflow_changed_since_the_release_commit_differs() {
3831 let (dir, _) = fixture();
3832 fs::create_dir_all(dir.path().join(".github/workflows")).unwrap();
3833 fs::write(dir.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
3834 let release = commit_all(dir.path(), "chore(release): version packages");
3835 fs::write(
3836 dir.path().join(".github/workflows/ci.yml"),
3837 "on: [push, pull_request]\n",
3838 )
3839 .unwrap();
3840 let tip = commit_all(dir.path(), "ci: run on pull requests");
3841 add_origin(dir.path());
3842 track(dir.path(), "main", &tip);
3843 git(dir.path(), &["update-ref", "--no-deref", "HEAD", &release]);
3844 let differs = super::workflows_differ(dir.path()).unwrap().unwrap();
3845 assert!(differs.contains(".github/workflows/"), "{differs}");
3846 assert!(differs.contains(&release), "{differs}");
3847 assert!(differs.contains(&tip), "{differs}");
3848
3849 let (bare, first) = fixture();
3850 add_origin(bare.path());
3851 fs::create_dir_all(bare.path().join(".github/workflows")).unwrap();
3852 fs::write(bare.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
3853 let added = commit_all(bare.path(), "ci: add");
3854 track(bare.path(), "main", &added);
3855 git(bare.path(), &["update-ref", "--no-deref", "HEAD", &first]);
3856 assert!(super::workflows_differ(bare.path()).unwrap().is_some());
3857 }
3858
3859 #[test]
3864 fn the_workflows_compared_are_those_of_the_run_commit() {
3865 let (dir, _) = fixture();
3866 fs::create_dir_all(dir.path().join(".github/workflows")).unwrap();
3867 fs::write(dir.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
3868 let release = commit_all(dir.path(), "chore(release): version packages");
3869 fs::write(
3870 dir.path().join(".github/workflows/ci.yml"),
3871 "on: [push, pull_request]\n",
3872 )
3873 .unwrap();
3874 let tip = commit_all(dir.path(), "ci: run on pull requests");
3875 add_origin(dir.path());
3876 track(dir.path(), "main", &tip);
3877 git(dir.path(), &["update-ref", "--no-deref", "HEAD", &release]);
3878
3879 assert_eq!(
3880 super::workflows_differ_at(dir.path(), Some(&tip)).unwrap(),
3881 None
3882 );
3883
3884 let at_head = super::workflows_differ_at(dir.path(), Some(&"0".repeat(40)))
3885 .unwrap()
3886 .unwrap();
3887 assert!(at_head.contains(&format!("at HEAD {release}")), "{at_head}");
3888 let unset = super::workflows_differ_at(dir.path(), None)
3889 .unwrap()
3890 .unwrap();
3891 assert!(unset.contains(&format!("at HEAD {release}")), "{unset}");
3892
3893 let at_run = super::workflows_differ_at(dir.path(), Some(&release))
3894 .unwrap()
3895 .unwrap();
3896 assert!(
3897 at_run.contains(&format!("at GITHUB_SHA {release}")),
3898 "{at_run}"
3899 );
3900 }
3901
3902 #[test]
3903 fn head_behind_origin_main_is_ok() {
3904 let (dir, first) = fixture();
3905 add_origin(dir.path());
3906 fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
3907 let second = commit_all(dir.path(), "ahead");
3908 track(dir.path(), "main", &second);
3909 git(dir.path(), &["update-ref", "--no-deref", "HEAD", &first]);
3910 prove(dir.path(), &stock()).unwrap();
3911 }
3912}