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