Skip to main content

workon/
fetch.rs

1//! Prune-fetch helpers for keeping remote-tracking refs in sync.
2//!
3//! "Gone" upstream detection in `prune --gone` relies on `Branch::upstream()` returning
4//! `Err` for a branch whose tracking ref was deleted on the remote. That only happens
5//! after a *prune-fetch* — a fetch that also removes stale `refs/remotes/<remote>/*`
6//! entries. Nothing in the codebase performed such a fetch before this module.
7//!
8//! Two public functions are provided:
9//!
10//! - [`remotes_tracked_by_worktrees`] — discover which remotes are relevant (deduplicated
11//!   list of `branch.<name>.remote` values across all worktrees).
12//! - [`prune_fetch`] — run the equivalent of `git fetch --prune <remote>` for a single
13//!   remote, deleting stale remote-tracking refs and then fetching.
14
15use git2::{FetchOptions, FetchPrune};
16
17use crate::error::Result;
18use crate::get_remote_callbacks::get_remote_callbacks;
19use crate::worktree::WorktreeDescriptor;
20
21/// Returns the deduplicated list of remote names tracked by the given worktrees.
22///
23/// For each worktree with a local branch that has an upstream configured, reads
24/// `branch.<name>.remote` from git config. Results are deduplicated and returned in
25/// stable (first-seen) order. Worktrees with detached HEAD or no upstream are
26/// silently skipped.
27///
28/// Accepts any iterator of worktree references, so callers can pass a full
29/// `&[WorktreeDescriptor]` or a filtered subset of borrowed descriptors.
30pub fn remotes_tracked_by_worktrees<'a>(
31    repo: &git2::Repository,
32    worktrees: impl IntoIterator<Item = &'a WorktreeDescriptor>,
33) -> Result<Vec<String>> {
34    let config = repo.config()?;
35    let mut remotes: Vec<String> = Vec::new();
36
37    for wt in worktrees {
38        let branch_name = match wt.branch()? {
39            Some(name) => name,
40            None => continue, // detached HEAD
41        };
42
43        let remote_key = format!("branch.{}.remote", branch_name);
44        if let Ok(remote) = config.get_string(&remote_key) {
45            if !remotes.contains(&remote) {
46                remotes.push(remote);
47            }
48        }
49    }
50
51    Ok(remotes)
52}
53
54/// Prune-fetch from a single remote: remove stale remote-tracking refs, then fetch.
55///
56/// Equivalent to `git fetch --prune <remote>`. After this call, any
57/// `refs/remotes/<remote>/<branch>` ref that no longer exists on the remote is
58/// deleted locally, making `Branch::upstream()` correctly return `Err` (i.e. "gone")
59/// for branches that were deleted upstream.
60///
61/// Returns `Err` on auth failure, network error, or unknown remote. Callers that
62/// want warn-and-continue behaviour should catch the error and proceed without
63/// aborting the rest of the prune.
64pub fn prune_fetch(repo: &git2::Repository, remote_name: &str) -> Result<()> {
65    let mut remote = repo.find_remote(remote_name)?;
66
67    // Stash the URL before we borrow remote mutably.
68    // url() returns Result<&str, _> in this git2 version; ignore errors (URL may be absent).
69    let remote_url = remote.url().ok().map(str::to_owned);
70    let auth = get_remote_callbacks(repo, remote_url.as_deref())?;
71
72    let mut fetch_opts = FetchOptions::new();
73    fetch_opts.prune(FetchPrune::On); // equivalent to --prune: delete stale tracking refs
74    fetch_opts.remote_callbacks(auth.callbacks());
75
76    // Empty refspec slice = use the remote's configured refspecs (same as `git fetch origin`).
77    remote.fetch(&[] as &[&str], Some(&mut fetch_opts), None)?;
78
79    Ok(())
80}