1use std::fs::{self, Permissions};
2use std::num::NonZeroU32;
3use std::path::{Path, PathBuf};
4use std::sync::atomic::AtomicBool;
5use std::{env, fmt};
6
7use anyhow::{Context, Result, bail, ensure};
8use gix::bstr::ByteSlice;
9use gix::credentials::helper::Action;
10use gix::credentials::protocol::Outcome;
11use gix::objs::tree::EntryKind;
12use gix::progress::Discard;
13use gix::refs::transaction::{PreviousValue, RefEdit};
14use gix::refs::{FullName, Target};
15use gix::remote::fetch::{Shallow, Tags};
16use gix::remote::{Direction, ref_map};
17use gix::sec::identity::Account;
18
19use crate::branches::{
20 candidate_names, default_upstream_commit, env_base_ref, has_origin, origin_head_branch,
21 origin_url_of, peel_remote,
22};
23use crate::merge_base::files_of;
24use crate::status::project_prefix;
25use crate::{discover, repo_covering};
26
27pub fn default_tip(root: &Path, candidates: &[String]) -> Result<String> {
36 let repo = repo_covering(root).with_context(|| {
37 format!(
38 "cannot resolve the default branch: no git repository covers {}",
39 root.display()
40 )
41 })?;
42 let tip = default_upstream_commit(&repo, candidates)?.context(
43 "cannot resolve the default branch: there is no `origin` remote; add it and fetch the default branch",
44 )?;
45 Ok(tip.to_string())
46}
47
48pub fn origin_url(root: &Path) -> Result<String> {
55 let repo = discover(root).context("open git repository")?;
56 let remote = repo.find_remote("origin").context("git remote origin")?;
57 let url = remote.url(Direction::Fetch).context("origin has no URL")?;
58 Ok(url.to_bstring().to_str_lossy().into_owned())
59}
60
61#[must_use]
63pub fn upstream_default_branch(root: &Path) -> Option<String> {
64 origin_head_branch(&discover(root).ok()?)
65}
66
67pub fn off_default_history(root: &Path) -> Result<Option<String>> {
93 prove_default_history(root, &candidate_names(env_base_ref().as_deref()))
94}
95
96pub fn workflows_differ(root: &Path) -> Result<Option<String>> {
118 workflows_differ_at(root, env_run_sha().as_deref())
119}
120
121pub(crate) fn workflows_differ_at(root: &Path, run_sha: Option<&str>) -> Result<Option<String>> {
123 let repo = repo_covering(root).with_context(|| {
124 format!(
125 "release cannot compare workflows: no git repository covers {}",
126 root.display()
127 )
128 })?;
129 let head = repo
130 .head_commit()
131 .context("release cannot compare workflows: HEAD has no commit")?;
132 let (run, label) = run_sha
133 .and_then(|sha| find_commit_by_hex(&repo, sha))
134 .map_or((head, "HEAD"), |commit| (commit, "GITHUB_SHA"));
135 let upstream = default_upstream_commit(&repo, &candidate_names(env_base_ref().as_deref()))?
136 .context("release cannot compare workflows: there is no `origin` remote")?;
137 let upstream = repo.find_commit(upstream)?;
138 let workflows = |commit: &gix::Commit<'_>| -> Result<Option<gix::ObjectId>> {
139 Ok(commit
140 .tree()?
141 .lookup_entry_by_path(WORKFLOWS)?
142 .map(|entry| entry.object_id()))
143 };
144 if workflows(&run)? == workflows(&upstream)? {
145 return Ok(None);
146 }
147 Ok(Some(format!(
148 "{WORKFLOWS}/ at {label} {run} differs from the default branch at {upstream}",
149 run = run.id(),
150 upstream = upstream.id(),
151 )))
152}
153
154fn find_commit_by_hex<'repo>(
157 repo: &'repo gix::Repository,
158 sha: &str,
159) -> Option<gix::Commit<'repo>> {
160 let id = gix::ObjectId::from_hex(sha.as_bytes()).ok()?;
161 repo.find_commit(id).ok()
162}
163
164fn env_run_sha() -> Option<String> {
165 env::var("GITHUB_SHA")
166 .ok()
167 .map(|value| value.trim().to_owned())
168 .filter(|value| !value.is_empty())
169}
170
171const WORKFLOWS: &str = ".github/workflows";
173
174#[non_exhaustive]
176pub enum FetchDefault {
177 Origin,
179 GitHub {
181 token: String,
183 repository: String,
185 },
186}
187
188impl fmt::Debug for FetchDefault {
191 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
192 match self {
193 Self::Origin => f.write_str("Origin"),
194 Self::GitHub {
195 repository,
196 token: _,
197 } => f
198 .debug_struct("GitHub")
199 .field("token", &"<redacted>")
200 .field("repository", repository)
201 .finish(),
202 }
203 }
204}
205
206impl FetchDefault {
207 #[must_use]
210 pub fn from_env() -> Self {
211 match (env::var("GITHUB_TOKEN"), env::var("GITHUB_REPOSITORY")) {
212 (Ok(token), Ok(repository)) if !token.is_empty() && !repository.is_empty() => {
213 Self::GitHub { token, repository }
214 }
215 _ => Self::Origin,
216 }
217 }
218}
219
220#[must_use]
222pub fn github_https_url(repository: &str) -> String {
223 format!("https://github.com/{repository}.git")
224}
225
226#[must_use]
228pub fn github_git_user() -> &'static str {
229 "x-access-token"
230}
231
232#[must_use]
237pub fn configured_default_branch() -> Option<String> {
238 env::var("VERCTL_DEFAULT_BRANCH")
239 .ok()
240 .map(|value| value.trim().to_owned())
241 .filter(|value| !value.is_empty())
242}
243
244pub fn ensure_origin_head(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
259 if branch.is_empty() {
260 return Ok(());
261 }
262 let Some(repo) = repo_covering(root) else {
263 return Ok(());
264 };
265 if !has_origin(&repo) {
266 return Ok(());
267 }
268 let remote_ref = format!("refs/remotes/origin/{branch}");
269 if peel_remote(&repo, &remote_ref).is_none() {
270 fetch_one_branch(&repo, branch, fetch, Shallow::NoChange)?;
271 }
272 ensure!(
273 peel_remote(&repo, &remote_ref).is_some(),
274 "cannot resolve the default branch ({remote_ref} is missing; fetch the default branch)"
275 );
276 let target = FullName::try_from(remote_ref.as_str())
277 .context("point origin/HEAD at the default branch")?;
278 let name = FullName::try_from("refs/remotes/origin/HEAD")
279 .context("point origin/HEAD at the default branch")?;
280 repo.edit_reference(RefEdit::update(
281 name,
282 Target::Symbolic(target),
283 PreviousValue::Any,
284 "verctl default branch",
285 ))
286 .context("point origin/HEAD at the default branch")?;
287 Ok(())
288}
289
290pub(crate) fn shallow_hint() -> &'static str {
294 if configured_default_branch().is_some() {
295 ""
296 } else {
297 ", or set VERCTL_DEFAULT_BRANCH so verctl fetches it"
298 }
299}
300
301pub fn ensure_full_history(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
324 if branch.is_empty() {
325 return Ok(());
326 }
327 let Some(repo) = repo_covering(root) else {
328 return Ok(());
329 };
330 if !has_origin(&repo) || !repo.is_shallow().context("read the shallow boundary")? {
331 return Ok(());
332 }
333 fetch_one_branch(&repo, branch, fetch, Shallow::undo())
334}
335
336pub fn ensure_comparable(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
355 if branch.is_empty() {
356 return Ok(());
357 }
358 let Some(repo) = repo_covering(root) else {
359 return Ok(());
360 };
361 if !has_origin(&repo) {
362 return Ok(());
363 }
364 let shallow = repo.is_shallow().context("read the shallow boundary")?;
365 let missing = peel_remote(&repo, &format!("refs/remotes/origin/{branch}")).is_none();
366 match (shallow, missing) {
367 (true, _) => fetch_one_branch(&repo, branch, fetch, Shallow::undo()),
368 (false, true) => fetch_one_branch(&repo, branch, fetch, Shallow::NoChange),
369 (false, false) => Ok(()),
370 }
371}
372
373pub fn extract_tag_tree(
388 root: &Path,
389 tag: &str,
390 dir: &Path,
391 fetch: &FetchDefault,
392) -> Result<PathBuf> {
393 use std::os::unix::fs::PermissionsExt as _;
394
395 ensure!(!tag.is_empty(), "baseline tag name must not be empty");
396 let repo =
397 discover(root).context("extracting a baseline release tag needs a git repository")?;
398 let mut commit_id = peel_tag_commit(&repo, tag)?;
399 if commit_id.is_none() && has_origin(&repo) {
400 let shallow = if repo.is_shallow().context("read the shallow boundary")? {
401 Shallow::DepthAtRemote(NonZeroU32::MIN)
402 } else {
403 Shallow::NoChange
404 };
405 let spec = format!("+refs/tags/{tag}:refs/tags/{tag}");
406 fetch_one_ref(&repo, &spec, fetch, shallow, "fetch the baseline tag")?;
407 commit_id = peel_tag_commit(&repo, tag)?;
408 }
409 let Some(commit_id) = commit_id else {
410 bail!(
411 "baseline tag {tag} was not found locally or on origin; verctl semver needs the release tag to build locked rustdoc JSON"
412 );
413 };
414 let tree = repo
415 .find_commit(commit_id)
416 .with_context(|| format!("read commit {commit_id} for tag {tag}"))?
417 .tree()
418 .with_context(|| format!("read tree for tag {tag}"))?;
419 let files = files_of(&tree)?;
420 for (rel, (oid, kind)) in files {
421 let mode = match kind {
422 EntryKind::Blob => 0o644,
423 EntryKind::BlobExecutable => 0o755,
424 EntryKind::Link | EntryKind::Tree | EntryKind::Commit => continue,
425 };
426 let path = dir.join(&rel);
427 if let Some(parent) = path.parent() {
428 fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
429 }
430 let blob = repo
431 .find_blob(oid)
432 .with_context(|| format!("read blob {rel} at tag {tag}"))?;
433 fs::write(&path, &blob.data).with_context(|| format!("write {}", path.display()))?;
434 fs::set_permissions(&path, Permissions::from_mode(mode))
435 .with_context(|| format!("chmod {}", path.display()))?;
436 }
437 let prefix = project_prefix(&repo, root);
438 Ok(if prefix.as_os_str().is_empty() {
439 dir.to_path_buf()
440 } else {
441 dir.join(prefix)
442 })
443}
444
445fn peel_tag_commit(repo: &gix::Repository, tag: &str) -> Result<Option<gix::ObjectId>> {
446 let full = format!("refs/tags/{tag}");
447 let Some(mut reference) = repo
448 .try_find_reference(&full)
449 .with_context(|| format!("look up {full}"))?
450 else {
451 return Ok(None);
452 };
453 let commit = reference
454 .peel_to_commit()
455 .with_context(|| format!("tag {tag} does not point to a commit"))?;
456 Ok(Some(commit.id().detach()))
457}
458
459fn fetch_one_branch(
464 repo: &gix::Repository,
465 branch: &str,
466 fetch: &FetchDefault,
467 shallow: Shallow,
468) -> Result<()> {
469 let spec = format!("+refs/heads/{branch}:refs/remotes/origin/{branch}");
470 fetch_one_ref(repo, &spec, fetch, shallow, "fetch the default branch")
471}
472
473fn fetch_one_ref(
474 repo: &gix::Repository,
475 spec: &str,
476 fetch: &FetchDefault,
477 shallow: Shallow,
478 context: &str,
479) -> Result<()> {
480 let url = match fetch {
481 FetchDefault::Origin => origin_url_of(repo)?,
482 FetchDefault::GitHub {
483 repository,
484 token: _,
485 } => github_https_url(repository),
486 };
487 let remote = repo
488 .remote_at(url.as_str())
489 .with_context(|| context.to_owned())?
490 .with_fetch_tags(Tags::None)
491 .with_refspecs([spec], Direction::Fetch)
492 .with_context(|| context.to_owned())?;
493 let connection = remote
494 .connect(Direction::Fetch)
495 .with_context(|| format!("git fetch {spec}"))?;
496 let interrupt = AtomicBool::new(false);
497 match fetch {
498 FetchDefault::Origin => connection
499 .prepare_fetch(Discard, ref_map::Options::default())
500 .with_context(|| format!("git fetch {spec}"))?
501 .with_shallow(shallow)
502 .receive(Discard, &interrupt),
503 FetchDefault::GitHub {
504 token,
505 repository: _,
506 } => connection
507 .with_credentials(github_credentials(token))
508 .prepare_fetch(Discard, ref_map::Options::default())
509 .with_context(|| format!("git fetch {spec}"))?
510 .with_shallow(shallow)
511 .receive(Discard, &interrupt),
512 }
513 .with_context(|| format!("git fetch {spec}"))?;
514 Ok(())
515}
516
517fn github_credentials(token: &str) -> impl FnMut(Action) -> gix::Result<Option<Outcome>> + '_ {
520 move |action| match action {
521 Action::Get(context) => Ok(Some(Outcome {
522 identity: Account {
523 username: github_git_user().to_owned(),
524 password: token.to_owned(),
525 oauth_refresh_token: None,
526 },
527 next: context.into(),
528 })),
529 Action::Store(_) | Action::Erase(_) => Ok(None),
530 }
531}
532
533pub(crate) fn prove_default_history(root: &Path, candidates: &[String]) -> Result<Option<String>> {
534 let repo = repo_covering(root).with_context(|| {
535 format!(
536 "release cannot prove HEAD is on the default branch: no git repository covers {}",
537 root.display()
538 )
539 })?;
540 let head = repo
541 .head_commit()
542 .context("release cannot prove HEAD is on the default branch: HEAD has no commit")?
543 .id()
544 .detach();
545 let upstream = default_upstream_commit(&repo, candidates)?.context(
546 "release cannot prove HEAD is on the default branch: there is no `origin` remote; add it and fetch the default branch",
547 )?;
548 if head == upstream {
549 return Ok(None);
550 }
551 match repo.merge_base(head, upstream) {
552 Ok(Some(base)) if base == head => Ok(None),
553 Ok(Some(_) | None) => Ok(Some(format!(
554 "HEAD {head} is not an ancestor of the default branch at {upstream}"
555 ))),
556 Err(error) => Err(error).context(
557 "release cannot prove HEAD is on the default branch (need a full fetch, not a shallow clone)",
558 ),
559 }
560}