verctl-git 0.9.5

Git repository access and history queries for verctl
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
use std::fs::{self, Permissions};
use std::num::NonZeroU32;
use std::path::{Path, PathBuf};
use std::sync::atomic::AtomicBool;
use std::{env, fmt};

use anyhow::{Context, Result, bail, ensure};
use gix::bstr::ByteSlice;
use gix::credentials::helper::Action;
use gix::credentials::protocol::Outcome;
use gix::objs::tree::EntryKind;
use gix::progress::Discard;
use gix::refs::transaction::{PreviousValue, RefEdit};
use gix::refs::{FullName, Target};
use gix::remote::fetch::{Shallow, Tags};
use gix::remote::{Direction, ref_map};
use gix::sec::identity::Account;

use crate::branches::{
    candidate_names, default_upstream_commit, env_base_ref, has_origin, origin_head_branch,
    origin_url_of, peel_remote,
};
use crate::merge_base::files_of;
use crate::status::project_prefix;
use crate::{discover, repo_covering};

/// The commit at the default branch's tip, as a full hex SHA. The branch
/// resolves as for [`crate::files_on_merge_base`]: `origin/HEAD`, or else the
/// first of `candidates` that `origin` has.
///
/// # Errors
///
/// Returns an error when no repository covers `root`, when there is no
/// `origin` remote, or when `origin` has none of those refs.
pub fn default_tip(root: &Path, candidates: &[String]) -> Result<String> {
    let repo = repo_covering(root).with_context(|| {
        format!(
            "cannot resolve the default branch: no git repository covers {}",
            root.display()
        )
    })?;
    let tip = default_upstream_commit(&repo, candidates)?.context(
        "cannot resolve the default branch: there is no `origin` remote; add it and fetch the default branch",
    )?;
    Ok(tip.to_string())
}

/// The URL of the `origin` remote.
///
/// # Errors
///
/// Returns an error when `root` is not inside a git repository, when there is
/// no `origin` remote, or when `origin` has no fetch URL.
pub fn origin_url(root: &Path) -> Result<String> {
    let repo = discover(root).context("open git repository")?;
    let remote = repo.find_remote("origin").context("git remote origin")?;
    let url = remote.url(Direction::Fetch).context("origin has no URL")?;
    Ok(url.to_bstring().to_str_lossy().into_owned())
}

/// The branch `origin/HEAD` points at, or `None` when that ref is unset.
#[must_use]
pub fn upstream_default_branch(root: &Path) -> Option<String> {
    origin_head_branch(&discover(root).ok()?)
}

/// Whether HEAD is off the default-branch history: `None` when the default
/// branch contains HEAD, or why it does not, naming both commits.
///
/// Being off the branch is a finding the caller may allow. A missing fact is
/// not a finding: a proof that cannot run fails and names the missing fact.
/// A check that passed by skipping itself would let a release run from any
/// commit, in exactly the CI shapes where the proof matters.
///
/// Each of these fails:
///
/// - no repository;
/// - no HEAD commit;
/// - no `origin` remote;
/// - an `origin` with no peelable default-tracking ref;
/// - a shallow clone that cannot walk the graph.
///
/// # Errors
///
/// Returns an error when:
///
/// - no repository covers `root`;
/// - HEAD has no commit;
/// - there is no `origin` remote;
/// - resolving the default branch ref fails;
/// - the merge-base cannot be computed, as in a shallow clone.
pub fn off_default_history(root: &Path) -> Result<Option<String>> {
    prove_default_history(root, &candidate_names(env_base_ref().as_deref()))
}

/// Whether `.github/workflows/` at the commit the run executes differs from
/// the default branch's tip.
/// It is `None` when the two trees are the same object, and otherwise names
/// both commits.
///
/// Actions runs the workflows of `GITHUB_SHA`.
/// In a reusable workflow's publish job HEAD is the version commit instead.
/// So the tree compared is the one at `GITHUB_SHA` when that variable names a
/// commit in the repository, and HEAD's otherwise.
///
/// A retry of an old release commit runs its workflows as they were at that
/// commit. Steps or permissions changed since can publish to the registry and
/// then fail to tag, and the registry cannot take a version back.
///
/// Equal tree ids prove equal content, so no file is read. A tree that is
/// missing on both sides counts as equal.
///
/// # Errors
///
/// Returns an error when no repository covers `root`, HEAD has no commit, or
/// the default branch ref is missing or cannot be resolved.
pub fn workflows_differ(root: &Path) -> Result<Option<String>> {
    workflows_differ_at(root, env_run_sha().as_deref())
}

/// [`workflows_differ`] with the run's commit given in place of `GITHUB_SHA`.
pub(crate) fn workflows_differ_at(root: &Path, run_sha: Option<&str>) -> Result<Option<String>> {
    let repo = repo_covering(root).with_context(|| {
        format!(
            "release cannot compare workflows: no git repository covers {}",
            root.display()
        )
    })?;
    let head = repo
        .head_commit()
        .context("release cannot compare workflows: HEAD has no commit")?;
    let (run, label) = run_sha
        .and_then(|sha| find_commit_by_hex(&repo, sha))
        .map_or((head, "HEAD"), |commit| (commit, "GITHUB_SHA"));
    let upstream = default_upstream_commit(&repo, &candidate_names(env_base_ref().as_deref()))?
        .context("release cannot compare workflows: there is no `origin` remote")?;
    let upstream = repo.find_commit(upstream)?;
    let workflows = |commit: &gix::Commit<'_>| -> Result<Option<gix::ObjectId>> {
        Ok(commit
            .tree()?
            .lookup_entry_by_path(WORKFLOWS)?
            .map(|entry| entry.object_id()))
    };
    if workflows(&run)? == workflows(&upstream)? {
        return Ok(None);
    }
    Ok(Some(format!(
        "{WORKFLOWS}/ at {label} {run} differs from the default branch at {upstream}",
        run = run.id(),
        upstream = upstream.id(),
    )))
}

/// The commit a full hex SHA names, or `None` when it is not valid hex or
/// names no commit in the repository.
fn find_commit_by_hex<'repo>(
    repo: &'repo gix::Repository,
    sha: &str,
) -> Option<gix::Commit<'repo>> {
    let id = gix::ObjectId::from_hex(sha.as_bytes()).ok()?;
    repo.find_commit(id).ok()
}

fn env_run_sha() -> Option<String> {
    env::var("GITHUB_SHA")
        .ok()
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
}

/// Where a repository keeps its GitHub Actions workflows.
const WORKFLOWS: &str = ".github/workflows";

/// How to fetch `origin/<branch>` when that ref is missing.
#[non_exhaustive]
pub enum FetchDefault {
    /// `git fetch origin`.
    Origin,
    /// GitHub HTTPS. Credentials are the callback, never the URL.
    GitHub {
        /// Access token for the fetch.
        token: String,
        /// The `owner/name` slug.
        repository: String,
    },
}

/// Prints the repository but never the token, so a logged value leaks no
/// credential.
impl fmt::Debug for FetchDefault {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Origin => f.write_str("Origin"),
            Self::GitHub {
                repository,
                token: _,
            } => f
                .debug_struct("GitHub")
                .field("token", &"<redacted>")
                .field("repository", repository)
                .finish(),
        }
    }
}

impl FetchDefault {
    /// `GitHub` when `GITHUB_TOKEN` and `GITHUB_REPOSITORY` are both set and
    /// non-empty, else `Origin`.
    #[must_use]
    pub fn from_env() -> Self {
        match (env::var("GITHUB_TOKEN"), env::var("GITHUB_REPOSITORY")) {
            (Ok(token), Ok(repository)) if !token.is_empty() && !repository.is_empty() => {
                Self::GitHub { token, repository }
            }
            _ => Self::Origin,
        }
    }
}

/// HTTPS URL for an `owner/name` slug. No credentials in the URL.
#[must_use]
pub fn github_https_url(repository: &str) -> String {
    format!("https://github.com/{repository}.git")
}

/// Username GitHub git-over-HTTPS expects. Not an HTTP Bearer scheme.
#[must_use]
pub fn github_git_user() -> &'static str {
    "x-access-token"
}

/// `VERCTL_DEFAULT_BRANCH` only.
///
/// `GITHUB_BASE_REF` is a candidate for `off_default_history` only. It never
/// names a branch to rewrite `origin/HEAD` with.
#[must_use]
pub fn configured_default_branch() -> Option<String> {
    env::var("VERCTL_DEFAULT_BRANCH")
        .ok()
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
}

/// Point `origin/HEAD` at `origin/<branch>`. Fetch that one ref only
/// when it is missing. The fetch gets the branch's history instead of a
/// depth-1 tip, because `off_default_history` walks parents.
///
/// An empty `branch`, no repository, and no `origin` remote are each a no-op.
///
/// # Errors
///
/// Returns an error when:
///
/// - the fetch fails (remote unreachable, credentials rejected, or the branch
///   absent on the remote);
/// - `origin/<branch>` is still missing afterwards;
/// - `origin/HEAD` cannot be updated.
pub fn ensure_origin_head(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
    if branch.is_empty() {
        return Ok(());
    }
    let Some(repo) = repo_covering(root) else {
        return Ok(());
    };
    if !has_origin(&repo) {
        return Ok(());
    }
    let remote_ref = format!("refs/remotes/origin/{branch}");
    if peel_remote(&repo, &remote_ref).is_none() {
        fetch_one_branch(&repo, branch, fetch, Shallow::NoChange)?;
    }
    ensure!(
        peel_remote(&repo, &remote_ref).is_some(),
        "cannot resolve the default branch ({remote_ref} is missing; fetch the default branch)"
    );
    let target = FullName::try_from(remote_ref.as_str())
        .context("point origin/HEAD at the default branch")?;
    let name = FullName::try_from("refs/remotes/origin/HEAD")
        .context("point origin/HEAD at the default branch")?;
    repo.edit_reference(RefEdit::update(
        name,
        Target::Symbolic(target),
        PreviousValue::Any,
        "verctl default branch",
    ))
    .context("point origin/HEAD at the default branch")?;
    Ok(())
}

/// Points at `VERCTL_DEFAULT_BRANCH` only while it is unset: once set,
/// [`ensure_full_history`] has run, and a commit still past the boundary is
/// not on the default branch.
pub(crate) fn shallow_hint() -> &'static str {
    if configured_default_branch().is_some() {
        ""
    } else {
        ", or set VERCTL_DEFAULT_BRANCH so verctl fetches it"
    }
}

/// Fetch the whole history of `origin/<branch>` when the clone is shallow.
///
/// A depth-1 checkout, which is the default of `actions/checkout`, ends at a
/// commit that has no parents. All of these then stop at the boundary:
///
/// - finding the commit that set a version;
/// - finding a tag's commit;
/// - proving HEAD is on the default branch.
///
/// Fetching the default branch without a depth limit removes that boundary for
/// every commit on it, the version commit included.
///
/// A clone that is not shallow, an empty `branch`, no repository, and no
/// `origin` remote are each a no-op. The walks then report the boundary.
///
/// # Errors
///
/// Returns an error when:
///
/// - the shallow boundary cannot be read;
/// - the fetch fails (remote unreachable, credentials rejected, or the branch
///   absent on the remote).
pub fn ensure_full_history(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
    if branch.is_empty() {
        return Ok(());
    }
    let Some(repo) = repo_covering(root) else {
        return Ok(());
    };
    if !has_origin(&repo) || !repo.is_shallow().context("read the shallow boundary")? {
        return Ok(());
    }
    fetch_one_branch(&repo, branch, fetch, Shallow::undo())
}

/// Fetch `origin/<branch>` so a merge-base with HEAD can be computed: when the
/// ref is missing, or when the clone is shallow.
///
/// A pull request checkout from `actions/checkout` contains only the depth-1
/// merge ref, with no `origin/<base>` and a parentless HEAD. Undoing the
/// boundary sends the parents of every commit the clone marks shallow, HEAD
/// included, so the walk from HEAD reaches the base branch.
///
/// A full clone that has the ref, an empty `branch`, no repository, and no
/// `origin` remote are each a no-op.
///
/// # Errors
///
/// Returns an error when:
///
/// - the shallow boundary cannot be read;
/// - the fetch fails (remote unreachable, credentials rejected, or the branch
///   absent on the remote).
pub fn ensure_comparable(root: &Path, branch: &str, fetch: &FetchDefault) -> Result<()> {
    if branch.is_empty() {
        return Ok(());
    }
    let Some(repo) = repo_covering(root) else {
        return Ok(());
    };
    if !has_origin(&repo) {
        return Ok(());
    }
    let shallow = repo.is_shallow().context("read the shallow boundary")?;
    let missing = peel_remote(&repo, &format!("refs/remotes/origin/{branch}")).is_none();
    match (shallow, missing) {
        (true, _) => fetch_one_branch(&repo, branch, fetch, Shallow::undo()),
        (false, true) => fetch_one_branch(&repo, branch, fetch, Shallow::NoChange),
        (false, false) => Ok(()),
    }
}

/// Materialize the repository tree at release tag `tag` into `dir`, returning
/// the path inside `dir` that corresponds to `root`.
///
/// Looks up `refs/tags/<tag>` locally first. When absent and the repository
/// has an `origin` remote, fetches `refs/tags/<tag>` alone through `fetch`
/// (depth 1 on a shallow clone, `NoChange` on a full clone so full history is
/// preserved). Regular files keep their executable bit and symlinks are
/// skipped, matching [`crate::MergeBase::write_to`].
///
/// # Errors
///
/// Returns an error when `root` is outside a git repository, when `tag` is
/// empty or exists neither locally nor on `origin`, or when the tree cannot be
/// read or written.
pub fn extract_tag_tree(
    root: &Path,
    tag: &str,
    dir: &Path,
    fetch: &FetchDefault,
) -> Result<PathBuf> {
    use std::os::unix::fs::PermissionsExt as _;

    ensure!(!tag.is_empty(), "baseline tag name must not be empty");
    let repo =
        discover(root).context("extracting a baseline release tag needs a git repository")?;
    let mut commit_id = peel_tag_commit(&repo, tag)?;
    if commit_id.is_none() && has_origin(&repo) {
        let shallow = if repo.is_shallow().context("read the shallow boundary")? {
            Shallow::DepthAtRemote(NonZeroU32::MIN)
        } else {
            Shallow::NoChange
        };
        let spec = format!("+refs/tags/{tag}:refs/tags/{tag}");
        fetch_one_ref(&repo, &spec, fetch, shallow, "fetch the baseline tag")?;
        commit_id = peel_tag_commit(&repo, tag)?;
    }
    let Some(commit_id) = commit_id else {
        bail!(
            "baseline tag {tag} was not found locally or on origin; verctl semver needs the release tag to build locked rustdoc JSON"
        );
    };
    let tree = repo
        .find_commit(commit_id)
        .with_context(|| format!("read commit {commit_id} for tag {tag}"))?
        .tree()
        .with_context(|| format!("read tree for tag {tag}"))?;
    let files = files_of(&tree)?;
    for (rel, (oid, kind)) in files {
        let mode = match kind {
            EntryKind::Blob => 0o644,
            EntryKind::BlobExecutable => 0o755,
            EntryKind::Link | EntryKind::Tree | EntryKind::Commit => continue,
        };
        let path = dir.join(&rel);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
        }
        let blob = repo
            .find_blob(oid)
            .with_context(|| format!("read blob {rel} at tag {tag}"))?;
        fs::write(&path, &blob.data).with_context(|| format!("write {}", path.display()))?;
        fs::set_permissions(&path, Permissions::from_mode(mode))
            .with_context(|| format!("chmod {}", path.display()))?;
    }
    let prefix = project_prefix(&repo, root);
    Ok(if prefix.as_os_str().is_empty() {
        dir.to_path_buf()
    } else {
        dir.join(prefix)
    })
}

fn peel_tag_commit(repo: &gix::Repository, tag: &str) -> Result<Option<gix::ObjectId>> {
    let full = format!("refs/tags/{tag}");
    let Some(mut reference) = repo
        .try_find_reference(&full)
        .with_context(|| format!("look up {full}"))?
    else {
        return Ok(None);
    };
    let commit = reference
        .peel_to_commit()
        .with_context(|| format!("tag {tag} does not point to a commit"))?;
    Ok(Some(commit.id().detach()))
}

/// Fetches `branch` alone into `origin/<branch>`, through a remote that carries
/// only that refspec and no tags, so the configured `origin` refspecs cannot
/// widen the fetch. `shallow` controls what happens to a shallow clone's
/// boundary.
fn fetch_one_branch(
    repo: &gix::Repository,
    branch: &str,
    fetch: &FetchDefault,
    shallow: Shallow,
) -> Result<()> {
    let spec = format!("+refs/heads/{branch}:refs/remotes/origin/{branch}");
    fetch_one_ref(repo, &spec, fetch, shallow, "fetch the default branch")
}

fn fetch_one_ref(
    repo: &gix::Repository,
    spec: &str,
    fetch: &FetchDefault,
    shallow: Shallow,
    context: &str,
) -> Result<()> {
    let url = match fetch {
        FetchDefault::Origin => origin_url_of(repo)?,
        FetchDefault::GitHub {
            repository,
            token: _,
        } => github_https_url(repository),
    };
    let remote = repo
        .remote_at(url.as_str())
        .with_context(|| context.to_owned())?
        .with_fetch_tags(Tags::None)
        .with_refspecs([spec], Direction::Fetch)
        .with_context(|| context.to_owned())?;
    let connection = remote
        .connect(Direction::Fetch)
        .with_context(|| format!("git fetch {spec}"))?;
    let interrupt = AtomicBool::new(false);
    match fetch {
        FetchDefault::Origin => connection
            .prepare_fetch(Discard, ref_map::Options::default())
            .with_context(|| format!("git fetch {spec}"))?
            .with_shallow(shallow)
            .receive(Discard, &interrupt),
        FetchDefault::GitHub {
            token,
            repository: _,
        } => connection
            .with_credentials(github_credentials(token))
            .prepare_fetch(Discard, ref_map::Options::default())
            .with_context(|| format!("git fetch {spec}"))?
            .with_shallow(shallow)
            .receive(Discard, &interrupt),
    }
    .with_context(|| format!("git fetch {spec}"))?;
    Ok(())
}

/// Answers every credential request with `x-access-token` and `token`, kept in
/// memory: the token never reaches a URL, a config file, or a helper program.
fn github_credentials(token: &str) -> impl FnMut(Action) -> gix::Result<Option<Outcome>> + '_ {
    move |action| match action {
        Action::Get(context) => Ok(Some(Outcome {
            identity: Account {
                username: github_git_user().to_owned(),
                password: token.to_owned(),
                oauth_refresh_token: None,
            },
            next: context.into(),
        })),
        Action::Store(_) | Action::Erase(_) => Ok(None),
    }
}

pub(crate) fn prove_default_history(root: &Path, candidates: &[String]) -> Result<Option<String>> {
    let repo = repo_covering(root).with_context(|| {
        format!(
            "release cannot prove HEAD is on the default branch: no git repository covers {}",
            root.display()
        )
    })?;
    let head = repo
        .head_commit()
        .context("release cannot prove HEAD is on the default branch: HEAD has no commit")?
        .id()
        .detach();
    let upstream = default_upstream_commit(&repo, candidates)?.context(
        "release cannot prove HEAD is on the default branch: there is no `origin` remote; add it and fetch the default branch",
    )?;
    if head == upstream {
        return Ok(None);
    }
    match repo.merge_base(head, upstream) {
        Ok(Some(base)) if base == head => Ok(None),
        Ok(Some(_) | None) => Ok(Some(format!(
            "HEAD {head} is not an ancestor of the default branch at {upstream}"
        ))),
        Err(error) => Err(error).context(
            "release cannot prove HEAD is on the default branch (need a full fetch, not a shallow clone)",
        ),
    }
}