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();
3150 fs::write(
3151 dir.path().join("Cargo.toml"),
3152 indoc! {r#"
3153 [package]
3154 version = "1.0.0"
3155 "#},
3156 )
3157 .unwrap();
3158 commit_all(dir.path(), "init");
3159 fs::create_dir_all(dir.path().join("dist")).unwrap();
3160 fs::write(dir.path().join("dist/out.js"), "ok\n").unwrap();
3161 fs::create_dir_all(dir.path().join("target/debug")).unwrap();
3162 fs::write(dir.path().join("target/debug/verctl"), "bin\n").unwrap();
3163 fs::write(dir.path().join("target/CACHEDIR.TAG"), "tag\n").unwrap();
3164 let staged = super::assert_only_allowed(
3165 dir.path(),
3166 &[dir.path().join("Cargo.toml")],
3167 &["dist/**".into()],
3168 super::IgnoredFiles::Include,
3169 )
3170 .unwrap();
3171 assert_eq!(staged.len(), 1, "{staged:?}");
3172 assert!(staged[0].ends_with("dist/out.js"), "{staged:?}");
3173 assert!(
3174 !staged
3175 .iter()
3176 .any(|path| path.to_string_lossy().contains("target")),
3177 "{staged:?}"
3178 );
3179 }
3180
3181 #[test]
3182 fn write_commit_on_branch_removes_a_deleted_staged_path() {
3183 let dir = tempfile::TempDir::new().unwrap();
3184 init(dir.path());
3185 fs::write(dir.path().join("Cargo.lock"), "old\n").unwrap();
3186 fs::write(
3187 dir.path().join("Cargo.toml"),
3188 indoc! {r#"
3189 [package]
3190 version = "1.0.0"
3191 "#},
3192 )
3193 .unwrap();
3194 commit_all(dir.path(), "init");
3195 fs::remove_file(dir.path().join("Cargo.lock")).unwrap();
3196 let staged = super::assert_only_allowed(
3197 dir.path(),
3198 &[dir.path().join("Cargo.toml")],
3199 &["Cargo.lock".into()],
3200 super::IgnoredFiles::Skip,
3201 )
3202 .unwrap();
3203 let oid = write_commit(dir.path(), &staged).expect("deletion should commit");
3204 let names = tree_names(dir.path(), &oid);
3205 assert!(!names.iter().any(|name| name == "Cargo.lock"), "{names:?}");
3206 assert!(names.iter().any(|name| name == "Cargo.toml"), "{names:?}");
3207 }
3208
3209 #[test]
3210 fn commit_only_lists_given_paths() {
3211 let dir = tempfile::TempDir::new().unwrap();
3212 init(dir.path());
3213 fs::write(
3214 dir.path().join("Cargo.toml"),
3215 indoc! {r#"
3216 [package]
3217 version = "1.0.0"
3218 "#},
3219 )
3220 .unwrap();
3221 let parent = commit_all(dir.path(), "init");
3222 fs::write(
3223 dir.path().join("Cargo.toml"),
3224 indoc! {r#"
3225 [package]
3226 version = "1.0.1"
3227 "#},
3228 )
3229 .unwrap();
3230 fs::write(
3231 dir.path().join("secret.env"),
3232 indoc! {"
3233 TOKEN=leak
3234 "},
3235 )
3236 .unwrap();
3237 let oid = write_commit(dir.path(), &[dir.path().join("Cargo.toml")]).expect("commit");
3238 let names = tree_names(dir.path(), &oid);
3239 assert!(names.iter().any(|name| name == "Cargo.toml"), "{names:?}");
3240 assert!(!names.iter().any(|name| name == "secret.env"), "{names:?}");
3241 assert_eq!(git(dir.path(), &["rev-parse", "HEAD"]), parent);
3242 }
3243
3244 #[test]
3245 fn dotted_relative_paths_stage() {
3246 let dir = tempfile::TempDir::new().unwrap();
3247 init(dir.path());
3248 fs::write(
3249 dir.path().join("Cargo.toml"),
3250 indoc! {r#"
3251 [package]
3252 version = "1.0.0"
3253 "#},
3254 )
3255 .unwrap();
3256 commit_all(dir.path(), "init");
3257 fs::write(
3258 dir.path().join("Cargo.toml"),
3259 indoc! {r#"
3260 [package]
3261 version = "1.0.1"
3262 "#},
3263 )
3264 .unwrap();
3265 let oid =
3266 write_commit(dir.path(), &[Path::new("./Cargo.toml").to_path_buf()]).expect("commit");
3267 let names = tree_names(dir.path(), &oid);
3268 assert!(names.iter().any(|name| name == "Cargo.toml"), "{names:?}");
3269 }
3270
3271 #[tokio::test]
3274 async fn push_keeps_the_token_out_of_the_error() {
3275 let server = wiremock::MockServer::start().await;
3276 wiremock::Mock::given(matchers::any())
3277 .respond_with(
3278 wiremock::ResponseTemplate::new(401)
3279 .insert_header("WWW-Authenticate", r#"Basic realm="git""#),
3280 )
3281 .mount(&server)
3282 .await;
3283 let (dir, _) = fixture();
3284 git(dir.path(), &["branch", "verctl/release/main"]);
3285 let url = format!("{}/owner/repo.git", server.uri());
3286 let token = "verctl-push-token-5f3a9c";
3287 let error = task::spawn_blocking(move || {
3288 super::push(&dir.path().join(".git"), &url, "verctl/release/main", token)
3289 })
3290 .await
3291 .unwrap()
3292 .unwrap_err();
3293 let message = format!("{error:#}");
3294 assert!(!message.contains(token), "{message}");
3295 let expected = format!("Basic {}", base64(&format!("x-access-token:{token}")));
3296 let requests = server.received_requests().await.unwrap();
3297 assert!(
3298 requests.iter().any(|request| {
3299 request
3300 .headers
3301 .get("authorization")
3302 .is_some_and(|value| value.as_bytes() == expected.as_bytes())
3303 }),
3304 "no request carried the token as Basic credentials"
3305 );
3306 }
3307
3308 fn base64(text: &str) -> String {
3310 const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
3311 let mut out = String::new();
3312 for chunk in text.as_bytes().chunks(3) {
3313 let bytes = [
3314 chunk[0],
3315 chunk.get(1).copied().unwrap_or(0),
3316 chunk.get(2).copied().unwrap_or(0),
3317 ];
3318 let joined = u32::from(bytes[0]) << 16 | u32::from(bytes[1]) << 8 | u32::from(bytes[2]);
3319 for index in 0..4 {
3320 if index <= chunk.len() {
3321 let sextet = (joined >> (18 - 6 * index)) & 0x3f;
3322 out.push(char::from(ALPHABET[usize::try_from(sextet).unwrap()]));
3323 } else {
3324 out.push('=');
3325 }
3326 }
3327 }
3328 out
3329 }
3330
3331 #[test]
3334 fn the_commit_applies_clean_filters() {
3335 let dir = tempfile::TempDir::new().unwrap();
3336 init(dir.path());
3337 fs::write(dir.path().join(".gitattributes"), "*.md text\n").unwrap();
3338 fs::write(dir.path().join("CHANGELOG.md"), "old\n").unwrap();
3339 commit_all(dir.path(), "init");
3340 fs::write(dir.path().join("CHANGELOG.md"), "a\r\nb\r\n").unwrap();
3341 let oid = write_commit(dir.path(), &[dir.path().join("CHANGELOG.md")]).expect("commit");
3342 let blob = format!("{oid}:CHANGELOG.md");
3343 assert_eq!(git(dir.path(), &["cat-file", "-p", &blob]), "a\nb");
3344 }
3345
3346 #[test]
3350 fn a_configured_identity_wins_over_the_fallback() {
3351 let dir = tempfile::TempDir::new().unwrap();
3352 init(dir.path());
3353 git(dir.path(), &["config", "user.name", "Configured Name"]);
3354 git(
3355 dir.path(),
3356 &["config", "user.email", "configured@example.com"],
3357 );
3358 fs::write(dir.path().join("Cargo.toml"), "version = 1\n").unwrap();
3359 commit_all(dir.path(), "init");
3360 fs::write(dir.path().join("Cargo.toml"), "version = 2\n").unwrap();
3361 let oid = write_commit(dir.path(), &[dir.path().join("Cargo.toml")]).expect("commit");
3362 let configured = "Configured Name <configured@example.com>";
3363 assert_eq!(
3364 git(
3365 dir.path(),
3366 &["log", "-1", "--format=%an <%ae>|%cn <%ce>", &oid]
3367 ),
3368 format!("{configured}|{configured}")
3369 );
3370 assert_eq!(
3371 git(
3372 dir.path(),
3373 &[
3374 "log",
3375 "-g",
3376 "-1",
3377 "--format=%gn <%ge>",
3378 "refs/heads/verctl/release/main",
3379 ],
3380 ),
3381 configured
3382 );
3383 }
3384
3385 #[test]
3390 fn a_workdir_found_from_dot_resolves_paths() {
3391 let repo = super::discover(Path::new(".")).unwrap();
3392 let workdir = super::absolute_workdir(&repo).unwrap();
3393 assert!(workdir.is_absolute(), "{}", workdir.display());
3394 assert_eq!(
3395 super::workdir_rel(&workdir, Path::new("./Cargo.toml")).unwrap(),
3396 Path::new("Cargo.toml")
3397 );
3398 }
3399
3400 #[cfg(unix)]
3403 #[test]
3404 fn a_symlinked_workdir_takes_canonical_paths() {
3405 let dir = tempfile::TempDir::new().unwrap();
3406 init(dir.path());
3407 fs::write(dir.path().join("Cargo.toml"), "version = 1\n").unwrap();
3408 commit_all(dir.path(), "init");
3409 fs::write(dir.path().join("Cargo.toml"), "version = 2\n").unwrap();
3410 let links = tempfile::TempDir::new().unwrap();
3411 let link = links.path().join("checkout");
3412 symlink(dir.path(), &link).unwrap();
3413 let canonical = dir.path().canonicalize().unwrap().join("Cargo.toml");
3414 let workdir = super::absolute_workdir(&super::discover(&link).unwrap()).unwrap();
3415 assert_eq!(
3416 super::workdir_rel(&workdir, &canonical).unwrap(),
3417 Path::new("Cargo.toml")
3418 );
3419 assert_eq!(
3420 super::workdir_rel(&workdir, &link.join("Cargo.toml")).unwrap(),
3421 Path::new("Cargo.toml")
3422 );
3423 }
3424
3425 fn write_commit(dir: &Path, paths: &[PathBuf]) -> Option<String> {
3428 let repo = super::discover(dir).unwrap();
3429 let workdir = super::absolute_workdir(&repo).unwrap();
3430 let parent = repo.head_commit().unwrap();
3431 super::write_commit_on_branch(
3432 &repo,
3433 &workdir,
3434 &parent,
3435 "verctl/release/main",
3436 "chore",
3437 paths,
3438 )
3439 .unwrap()
3440 .map(|id| id.to_string())
3441 }
3442
3443 fn stock() -> Vec<String> {
3444 super::candidate_names(None)
3445 }
3446
3447 fn fixture() -> (tempfile::TempDir, String) {
3448 let dir = tempfile::TempDir::new().unwrap();
3449 init(dir.path());
3450 let sha = commit_all(dir.path(), "init");
3451 (dir, sha)
3452 }
3453
3454 fn add_origin(dir: &Path) {
3455 git(
3456 dir,
3457 &[
3458 "remote",
3459 "add",
3460 "origin",
3461 "https://github.com/victor-software-house/verctl.git",
3462 ],
3463 );
3464 }
3465
3466 fn track(dir: &Path, name: &str, sha: &str) {
3467 git(
3468 dir,
3469 &["update-ref", &format!("refs/remotes/origin/{name}"), sha],
3470 );
3471 }
3472
3473 fn set_origin_head(dir: &Path, name: &str) {
3474 git(
3475 dir,
3476 &[
3477 "symbolic-ref",
3478 "refs/remotes/origin/HEAD",
3479 &format!("refs/remotes/origin/{name}"),
3480 ],
3481 );
3482 }
3483
3484 fn prove(root: &Path, candidates: &[String]) -> anyhow::Result<()> {
3486 match super::prove_default_history(root, candidates)? {
3487 None => Ok(()),
3488 Some(off) => anyhow::bail!(off),
3489 }
3490 }
3491
3492 #[test]
3493 fn candidate_names_are_base_ref_then_main_master() {
3494 assert_eq!(super::candidate_names(None), ["main", "master"]);
3495 assert_eq!(super::candidate_names(Some("")), ["main", "master"]);
3496 assert_eq!(super::candidate_names(Some(" ")), ["main", "master"]);
3497 assert_eq!(
3498 super::candidate_names(Some("trunk")),
3499 ["trunk", "main", "master"]
3500 );
3501 assert_eq!(super::candidate_names(Some("main")), ["main", "master"]);
3502 assert_eq!(
3503 super::candidate_names(Some("release/1.0")),
3504 ["release/1.0", "main", "master"]
3505 );
3506 }
3507
3508 #[test]
3509 fn no_repository_refuses() {
3510 let dir = tempfile::TempDir::new().unwrap();
3511 let err = prove(dir.path(), &stock()).unwrap_err();
3512 assert!(
3513 format!("{err:#}").contains("release cannot prove HEAD"),
3514 "{err:#}"
3515 );
3516 assert!(format!("{err:#}").contains("no git repository"), "{err:#}");
3517 }
3518
3519 #[test]
3520 fn no_head_commit_refuses() {
3521 let dir = tempfile::TempDir::new().unwrap();
3522 init(dir.path());
3523 let err = prove(dir.path(), &stock()).unwrap_err();
3524 assert!(format!("{err:#}").contains("HEAD has no commit"), "{err:#}");
3525 }
3526
3527 #[test]
3528 fn a_missing_origin_refuses() {
3529 let (dir, _) = fixture();
3530 let err = prove(dir.path(), &stock()).unwrap_err();
3531 assert!(format!("{err:#}").contains("no `origin` remote"), "{err:#}");
3532 }
3533
3534 #[test]
3535 fn head_on_origin_main_is_ok() {
3536 let (dir, sha) = fixture();
3537 add_origin(dir.path());
3538 track(dir.path(), "main", &sha);
3539 prove(dir.path(), &stock()).unwrap();
3540 }
3541
3542 #[test]
3543 fn head_sha_is_the_peeled_head_commit() {
3544 let (dir, sha) = fixture();
3545 assert_eq!(super::head_sha(dir.path()).unwrap(), sha);
3546 }
3547
3548 #[test]
3549 fn origin_master_without_head_is_ok() {
3550 let (dir, sha) = fixture();
3551 add_origin(dir.path());
3552 track(dir.path(), "master", &sha);
3553 prove(dir.path(), &stock()).unwrap();
3554 }
3555
3556 #[test]
3557 fn origin_head_to_non_main_is_ok() {
3558 let (dir, sha) = fixture();
3559 add_origin(dir.path());
3560 track(dir.path(), "trunk", &sha);
3561 set_origin_head(dir.path(), "trunk");
3562 prove(dir.path(), &stock()).unwrap();
3563 }
3564
3565 #[test]
3566 fn base_ref_trunk_without_origin_head_is_ok() {
3567 let (dir, sha) = fixture();
3568 add_origin(dir.path());
3569 track(dir.path(), "trunk", &sha);
3570 prove(dir.path(), &super::candidate_names(Some("trunk"))).unwrap();
3571 }
3572
3573 #[test]
3574 fn origin_without_default_tracking_ref_fails() {
3575 let (dir, _) = fixture();
3576 add_origin(dir.path());
3577 let err = prove(dir.path(), &stock()).unwrap_err();
3578 assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
3579 }
3580
3581 #[test]
3582 fn origin_trunk_alone_needs_head_or_base_ref() {
3583 let (dir, sha) = fixture();
3584 add_origin(dir.path());
3585 track(dir.path(), "trunk", &sha);
3586 let err = prove(dir.path(), &stock()).unwrap_err();
3587 assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
3588 prove(dir.path(), &super::candidate_names(Some("trunk"))).unwrap();
3589 set_origin_head(dir.path(), "trunk");
3590 prove(dir.path(), &stock()).unwrap();
3591 }
3592
3593 #[test]
3594 fn origin_hotfix_alone_is_not_the_default() {
3595 let (dir, sha) = fixture();
3596 add_origin(dir.path());
3597 track(dir.path(), "hotfix", &sha);
3598 let err = prove(dir.path(), &stock()).unwrap_err();
3599 assert!(format!("{err:#}").contains("origin exists"), "{err:#}");
3600 }
3601
3602 #[test]
3603 fn unpeelable_origin_head_does_not_fall_through_to_main() {
3604 let (dir, sha) = fixture();
3605 add_origin(dir.path());
3606 track(dir.path(), "main", &sha);
3607 set_origin_head(dir.path(), "trunk");
3608 let err = prove(dir.path(), &stock()).unwrap_err();
3609 assert!(format!("{err:#}").contains("origin/trunk"), "{err:#}");
3610 }
3611
3612 #[test]
3613 fn github_https_url_has_no_credentials() {
3614 let url = super::github_https_url("victor-software-house/qctl");
3615 assert_eq!(url, "https://github.com/victor-software-house/qctl.git");
3616 let lower = url.to_ascii_lowercase();
3617 assert!(!lower.contains("bearer"), "{url}");
3618 assert!(!lower.contains("token"), "{url}");
3619 assert!(!lower.contains("x-access-token"), "{url}");
3620 }
3621
3622 #[test]
3623 fn github_git_user_is_x_access_token() {
3624 assert_eq!(super::github_git_user(), "x-access-token");
3625 }
3626
3627 #[test]
3628 fn ensure_origin_head_skips_fetch_when_the_ref_exists() {
3629 let (dir, sha) = fixture();
3630 git(
3631 dir.path(),
3632 &["remote", "add", "origin", "https://127.0.0.1:1/nope.git"],
3633 );
3634 track(dir.path(), "main", &sha);
3635 super::ensure_origin_head(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3636 assert_eq!(
3637 git(dir.path(), &["symbolic-ref", "refs/remotes/origin/HEAD"]),
3638 "refs/remotes/origin/main"
3639 );
3640 }
3641
3642 #[test]
3643 fn ensure_origin_head_fetches_a_missing_ref_from_origin() {
3644 let upstream_dir = tempfile::TempDir::new().unwrap();
3645 init(upstream_dir.path());
3646 commit_all(upstream_dir.path(), "init");
3647
3648 let work_dir = tempfile::TempDir::new().unwrap();
3649 init(work_dir.path());
3650 commit_all(work_dir.path(), "local");
3651 let url = format!("file://{}", upstream_dir.path().display());
3652 git(work_dir.path(), &["remote", "add", "origin", &url]);
3653
3654 super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3655 git(
3656 work_dir.path(),
3657 &["rev-parse", "--verify", "refs/remotes/origin/main^{commit}"],
3658 );
3659 assert_eq!(
3660 git(
3661 work_dir.path(),
3662 &["symbolic-ref", "refs/remotes/origin/HEAD"]
3663 ),
3664 "refs/remotes/origin/main"
3665 );
3666 }
3667
3668 #[test]
3669 fn a_shallow_clone_gets_the_history_that_holds_the_tagged_commit() {
3670 let upstream = tempfile::TempDir::new().unwrap();
3671 init(upstream.path());
3672 write_version(upstream.path(), "0.0.1");
3673 commit_all(upstream.path(), "chore: start");
3674 write_version(upstream.path(), "0.0.2");
3675 let set = commit_all(upstream.path(), "chore(release): version packages");
3676 fs::write(upstream.path().join("README"), "later\n").unwrap();
3677 commit_all(upstream.path(), "docs: later");
3678
3679 let parent = tempfile::TempDir::new().unwrap();
3680 let url = format!("file://{}", upstream.path().display());
3681 git(
3682 parent.path(),
3683 &["clone", "-q", "--depth", "1", &url, "work"],
3684 );
3685 let work = parent.path().join("work");
3686 let manifest = work.join("Cargo.toml");
3687 let error = tagged_commit(&work, &manifest, &set, &version_line).unwrap_err();
3688 assert!(format!("{error:#}").contains("shallow"), "{error:#}");
3689
3690 super::ensure_full_history(&work, "main", &super::FetchDefault::Origin).unwrap();
3691 let found = tagged_commit(&work, &manifest, &set, &version_line).unwrap();
3692 assert_eq!(found, Some(VersionCommit { sha: set, depth: 1 }));
3693 }
3694
3695 #[test]
3696 fn a_full_clone_is_not_fetched_again() {
3697 let dir = tempfile::TempDir::new().unwrap();
3698 init(dir.path());
3699 commit_all(dir.path(), "init");
3700 git(
3702 dir.path(),
3703 &["remote", "add", "origin", "file:///nonexistent/verctl"],
3704 );
3705 super::ensure_full_history(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3706 }
3707
3708 #[test]
3713 fn a_pull_request_merge_checkout_compares_against_its_merge_base() {
3714 let upstream = tempfile::TempDir::new().unwrap();
3715 let up = upstream.path();
3716 init(up);
3717 write_version(up, "0.0.1");
3718 commit_all(up, "chore: start");
3719 write_version(up, "0.0.2");
3720 commit_all(up, "chore(release): version packages");
3721 git(up, &["checkout", "-q", "-b", "pr"]);
3722 fs::write(up.join("README"), "change\n").unwrap();
3723 commit_all(up, "docs: change");
3724 git(up, &["checkout", "-q", "--detach", "main"]);
3725 git(
3726 up,
3727 &["merge", "-q", "--no-ff", "pr", "-m", "Merge pr into main"],
3728 );
3729 git(up, &["update-ref", "refs/pull/1/merge", "HEAD"]);
3730 git(up, &["checkout", "-q", "main"]);
3731 write_version(up, "0.0.3");
3732 commit_all(up, "chore(release): version packages");
3733
3734 let work = tempfile::TempDir::new().unwrap();
3735 let dir = work.path();
3736 init(dir);
3737 let url = format!("file://{}", up.display());
3738 git(dir, &["remote", "add", "origin", &url]);
3739 git(
3740 dir,
3741 &[
3742 "fetch",
3743 "-q",
3744 "--depth=1",
3745 "origin",
3746 "+refs/pull/1/merge:refs/remotes/pull/1/merge",
3747 ],
3748 );
3749 git(
3750 dir,
3751 &["checkout", "-q", "--detach", "refs/remotes/pull/1/merge"],
3752 );
3753 assert_eq!(git(dir, &["rev-parse", "--is-shallow-repository"]), "true");
3754
3755 let manifest = [Path::new("Cargo.toml")];
3756 let candidates = ["main".to_owned()];
3757 let error = super::files_on_merge_base(dir, &manifest, &candidates).unwrap_err();
3758 assert!(
3759 format!("{error:#}").contains("fetch the default branch"),
3760 "{error:#}"
3761 );
3762
3763 super::ensure_comparable(dir, "main", &super::FetchDefault::Origin).unwrap();
3764 let files = super::files_on_merge_base(dir, &manifest, &candidates).unwrap();
3765 let base = files[0].as_deref().expect("Cargo.toml at the merge-base");
3766 assert_eq!(version_line(base).as_deref(), Some("0.0.2"));
3767 }
3768
3769 #[test]
3770 fn release_candidates_put_the_event_default_after_the_configured_branch() {
3771 assert_eq!(
3772 super::release_candidate_names(None, Some("trunk"), Some("develop")),
3773 ["trunk", "main", "master", "develop"]
3774 );
3775 assert_eq!(
3776 super::release_candidate_names(Some("stable"), Some("trunk"), None),
3777 ["stable", "trunk", "main", "master"]
3778 );
3779 assert_eq!(
3780 super::release_candidate_names(None, Some("main"), Some("main")),
3781 ["main", "master"]
3782 );
3783 assert_eq!(
3784 super::release_candidate_names(None, None, Some("develop")),
3785 ["main", "master", "develop"]
3786 );
3787 }
3788
3789 #[test]
3790 fn a_full_clone_with_the_branch_is_not_fetched_for_a_comparison() {
3791 let (dir, sha) = fixture();
3792 git(
3794 dir.path(),
3795 &["remote", "add", "origin", "file:///nonexistent/verctl"],
3796 );
3797 track(dir.path(), "main", &sha);
3798 super::ensure_comparable(dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3799 }
3800
3801 #[test]
3802 fn a_full_clone_without_the_branch_fetches_it_for_a_comparison() {
3803 let upstream = tempfile::TempDir::new().unwrap();
3804 init(upstream.path());
3805 let tip = commit_all(upstream.path(), "init");
3806
3807 let work = tempfile::TempDir::new().unwrap();
3808 init(work.path());
3809 commit_all(work.path(), "local");
3810 let url = format!("file://{}", upstream.path().display());
3811 git(work.path(), &["remote", "add", "origin", &url]);
3812
3813 super::ensure_comparable(work.path(), "main", &super::FetchDefault::Origin).unwrap();
3814 assert_eq!(
3815 git(work.path(), &["rev-parse", "refs/remotes/origin/main"]),
3816 tip
3817 );
3818 }
3819
3820 #[test]
3821 fn fetch_one_branch_does_not_set_depth() {
3822 let src = include_str!("lib.rs");
3823 let prod = src.split("#[cfg(test)]").next().expect("production");
3824 assert!(
3825 !prod.contains("opts.depth"),
3826 "a depth-limited fetch leaves the tip parentless so graph_descendant_of cannot prove ancestry"
3827 );
3828 }
3829
3830 #[test]
3831 fn configured_default_branch_is_only_verctl_default_branch() {
3832 let src = include_str!("lib.rs");
3833 let start = src
3834 .find("pub fn configured_default_branch")
3835 .expect("configured_default_branch");
3836 let rest = &src[start..];
3837 let end = rest
3838 .find("pub fn ensure_origin_head")
3839 .expect("ensure_origin_head");
3840 let body = &rest[..end];
3841 assert!(!body.contains("GITHUB_BASE_REF"), "{body}");
3842 assert!(!body.contains("env_base_ref"), "{body}");
3843 }
3844
3845 #[test]
3846 fn fetched_default_branch_keeps_parents_for_ancestry() {
3847 let upstream_dir = tempfile::TempDir::new().unwrap();
3848 init(upstream_dir.path());
3849 commit_all(upstream_dir.path(), "A");
3850
3851 let work_dir = tempfile::TempDir::new().unwrap();
3852 init(work_dir.path());
3853 let url = format!("file://{}", upstream_dir.path().display());
3854 git(work_dir.path(), &["remote", "add", "origin", &url]);
3855 super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3856 let first = git(work_dir.path(), &["rev-parse", "refs/remotes/origin/main"]);
3857 git(
3858 work_dir.path(),
3859 &["update-ref", "--no-deref", "HEAD", &first],
3860 );
3861
3862 fs::write(upstream_dir.path().join("b.txt"), "b\n").unwrap();
3863 commit_all(upstream_dir.path(), "B");
3864 fs::write(upstream_dir.path().join("c.txt"), "c\n").unwrap();
3865 commit_all(upstream_dir.path(), "C");
3866
3867 git(
3868 work_dir.path(),
3869 &["update-ref", "-d", "refs/remotes/origin/main"],
3870 );
3871 git(
3872 work_dir.path(),
3873 &["symbolic-ref", "--delete", "refs/remotes/origin/HEAD"],
3874 );
3875 super::ensure_origin_head(work_dir.path(), "main", &super::FetchDefault::Origin).unwrap();
3876 prove(work_dir.path(), &stock()).unwrap();
3877 }
3878
3879 #[test]
3880 fn origin_head_wins_over_main_when_they_differ() {
3881 let (dir, first) = fixture();
3882 add_origin(dir.path());
3883 fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
3884 let second = commit_all(dir.path(), "ahead");
3885 track(dir.path(), "main", &first);
3886 track(dir.path(), "trunk", &second);
3887 set_origin_head(dir.path(), "trunk");
3888 prove(dir.path(), &stock()).unwrap();
3889 }
3890
3891 #[test]
3894 fn head_off_default_history_fails() {
3895 let (dir, first) = fixture();
3896 add_origin(dir.path());
3897 track(dir.path(), "main", &first);
3898 git(dir.path(), &["update-ref", "refs/heads/other", &first]);
3899 git(dir.path(), &["symbolic-ref", "HEAD", "refs/heads/other"]);
3900 fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
3901 let head = commit_all(dir.path(), "ahead");
3902 let off = super::prove_default_history(dir.path(), &stock())
3903 .unwrap()
3904 .unwrap();
3905 assert!(off.contains("not an ancestor"), "{off}");
3906 assert!(off.contains(&head), "{off}");
3907 assert!(off.contains(&first), "{off}");
3908 }
3909
3910 #[test]
3911 fn workflows_at_the_default_tip_match() {
3912 let (dir, _) = fixture();
3913 fs::create_dir_all(dir.path().join(".github/workflows")).unwrap();
3914 fs::write(dir.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
3915 let release = commit_all(dir.path(), "chore(release): version packages");
3916 fs::write(dir.path().join("README"), "later\n").unwrap();
3917 let tip = commit_all(dir.path(), "docs: later");
3918 add_origin(dir.path());
3919 track(dir.path(), "main", &tip);
3920 git(dir.path(), &["update-ref", "--no-deref", "HEAD", &release]);
3921 assert_eq!(super::workflows_differ(dir.path()).unwrap(), None);
3922 }
3923
3924 #[test]
3927 fn a_workflow_changed_since_the_release_commit_differs() {
3928 let (dir, _) = fixture();
3929 fs::create_dir_all(dir.path().join(".github/workflows")).unwrap();
3930 fs::write(dir.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
3931 let release = commit_all(dir.path(), "chore(release): version packages");
3932 fs::write(
3933 dir.path().join(".github/workflows/ci.yml"),
3934 "on: [push, pull_request]\n",
3935 )
3936 .unwrap();
3937 let tip = commit_all(dir.path(), "ci: run on pull requests");
3938 add_origin(dir.path());
3939 track(dir.path(), "main", &tip);
3940 git(dir.path(), &["update-ref", "--no-deref", "HEAD", &release]);
3941 let differs = super::workflows_differ(dir.path()).unwrap().unwrap();
3942 assert!(differs.contains(".github/workflows/"), "{differs}");
3943 assert!(differs.contains(&release), "{differs}");
3944 assert!(differs.contains(&tip), "{differs}");
3945
3946 let (bare, first) = fixture();
3947 add_origin(bare.path());
3948 fs::create_dir_all(bare.path().join(".github/workflows")).unwrap();
3949 fs::write(bare.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
3950 let added = commit_all(bare.path(), "ci: add");
3951 track(bare.path(), "main", &added);
3952 git(bare.path(), &["update-ref", "--no-deref", "HEAD", &first]);
3953 assert!(super::workflows_differ(bare.path()).unwrap().is_some());
3954 }
3955
3956 #[test]
3961 fn the_workflows_compared_are_those_of_the_run_commit() {
3962 let (dir, _) = fixture();
3963 fs::create_dir_all(dir.path().join(".github/workflows")).unwrap();
3964 fs::write(dir.path().join(".github/workflows/ci.yml"), "on: push\n").unwrap();
3965 let release = commit_all(dir.path(), "chore(release): version packages");
3966 fs::write(
3967 dir.path().join(".github/workflows/ci.yml"),
3968 "on: [push, pull_request]\n",
3969 )
3970 .unwrap();
3971 let tip = commit_all(dir.path(), "ci: run on pull requests");
3972 add_origin(dir.path());
3973 track(dir.path(), "main", &tip);
3974 git(dir.path(), &["update-ref", "--no-deref", "HEAD", &release]);
3975
3976 assert_eq!(
3977 super::workflows_differ_at(dir.path(), Some(&tip)).unwrap(),
3978 None
3979 );
3980
3981 let at_head = super::workflows_differ_at(dir.path(), Some(&"0".repeat(40)))
3982 .unwrap()
3983 .unwrap();
3984 assert!(at_head.contains(&format!("at HEAD {release}")), "{at_head}");
3985 let unset = super::workflows_differ_at(dir.path(), None)
3986 .unwrap()
3987 .unwrap();
3988 assert!(unset.contains(&format!("at HEAD {release}")), "{unset}");
3989
3990 let at_run = super::workflows_differ_at(dir.path(), Some(&release))
3991 .unwrap()
3992 .unwrap();
3993 assert!(
3994 at_run.contains(&format!("at GITHUB_SHA {release}")),
3995 "{at_run}"
3996 );
3997 }
3998
3999 #[test]
4000 fn head_behind_origin_main_is_ok() {
4001 let (dir, first) = fixture();
4002 add_origin(dir.path());
4003 fs::write(dir.path().join("extra.txt"), "x\n").unwrap();
4004 let second = commit_all(dir.path(), "ahead");
4005 track(dir.path(), "main", &second);
4006 git(dir.path(), &["update-ref", "--no-deref", "HEAD", &first]);
4007 prove(dir.path(), &stock()).unwrap();
4008 }
4009
4010 #[test]
4011 fn extract_tag_tree_reads_local_annotated_tag_and_preserves_files() {
4012 let (dir, _) = fixture();
4013 fs::write(dir.path().join("Cargo.toml"), "version = \"0.1.0\"\n").unwrap();
4014 commit_all(dir.path(), "release 0.1.0");
4015 git(dir.path(), &["tag", "-a", "v0.1.0", "-m", "v0.1.0"]);
4016 fs::write(dir.path().join("Cargo.toml"), "version = \"0.1.1\"\n").unwrap();
4017 commit_all(dir.path(), "next");
4018
4019 let dest = tempfile::TempDir::new().unwrap();
4020 let extracted = super::extract_tag_tree(
4021 dir.path(),
4022 "v0.1.0",
4023 dest.path(),
4024 &super::FetchDefault::Origin,
4025 )
4026 .unwrap();
4027 assert_eq!(extracted, dest.path());
4028 assert_eq!(
4029 fs::read_to_string(extracted.join("Cargo.toml")).unwrap(),
4030 "version = \"0.1.0\"\n"
4031 );
4032 }
4033
4034 #[test]
4035 fn extract_tag_tree_fetches_missing_tag_in_shallow_clone() {
4036 let upstream = tempfile::TempDir::new().unwrap();
4037 init(upstream.path());
4038 fs::write(upstream.path().join("Cargo.toml"), "version = \"0.1.0\"\n").unwrap();
4039 commit_all(upstream.path(), "v0.1.0");
4040 git(upstream.path(), &["tag", "v0.1.0"]);
4041 fs::write(upstream.path().join("Cargo.toml"), "version = \"0.1.1\"\n").unwrap();
4042 commit_all(upstream.path(), "ahead");
4043
4044 let parent = tempfile::TempDir::new().unwrap();
4045 let url = format!("file://{}", upstream.path().display());
4046 git(
4047 parent.path(),
4048 &["clone", "-q", "--depth", "1", "--no-tags", &url, "work"],
4049 );
4050 let work = parent.path().join("work");
4051 let dest = tempfile::TempDir::new().unwrap();
4052 let extracted =
4053 super::extract_tag_tree(&work, "v0.1.0", dest.path(), &super::FetchDefault::Origin)
4054 .unwrap();
4055 assert_eq!(
4056 fs::read_to_string(extracted.join("Cargo.toml")).unwrap(),
4057 "version = \"0.1.0\"\n"
4058 );
4059 }
4060
4061 #[test]
4062 fn extract_tag_tree_fails_naming_missing_tag() {
4063 let (dir, _) = fixture();
4064 let dest = tempfile::TempDir::new().unwrap();
4065 let error = super::extract_tag_tree(
4066 dir.path(),
4067 "v9.9.9",
4068 dest.path(),
4069 &super::FetchDefault::Origin,
4070 )
4071 .unwrap_err();
4072 let message = format!("{error:#}");
4073 assert!(message.contains("v9.9.9"), "{message}");
4074 }
4075}