use crate::error::ObjectError;
use std::cell::OnceCell;
use std::collections::{HashSet, VecDeque};
use std::ops::ControlFlow;
use std::path::Path;
use std::time::SystemTime;
use crate::error::{Error, Result};
use crate::objects::{parse_commit, parse_tag, ObjectId, ObjectKind, OidHashSet, TreeRefIter};
use crate::odb::store::PrunableObjectStore;
use crate::odb::{Odb, PruneTarget};
use crate::refs::store::{Expected, RawRef, RefUpdate, RefUpdateFlags};
use crate::refs::{self, Ref};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PruneStats {
pub pruned: usize,
pub kept: usize,
}
pub fn prune_loose_unreachable(
odb: &Odb,
reachable_roots: &[ObjectId],
keep_newer_than: Option<SystemTime>,
) -> Result<PruneStats> {
prune_loose_unreachable_with_dry_run(odb, reachable_roots, keep_newer_than, false)
}
pub fn prune_loose_unreachable_with_dry_run(
odb: &Odb,
reachable_roots: &[ObjectId],
keep_newer_than: Option<SystemTime>,
dry_run: bool,
) -> Result<PruneStats> {
let shallow = odb
.config_git_dir()
.map(crate::shallow::load_shallow_boundaries)
.unwrap_or_default();
prune_loose_unreachable_with(
odb,
&LazyReachable::new(odb, reachable_roots, &shallow),
keep_newer_than,
dry_run,
)
}
pub(crate) fn prune_loose_unreachable_with(
odb: &Odb,
reachable: &LazyReachable<'_>,
keep_newer_than: Option<SystemTime>,
dry_run: bool,
) -> Result<PruneStats> {
match odb.prune_target()? {
PruneTarget::Files => prune_files_unreachable(odb, reachable, keep_newer_than, dry_run),
PruneTarget::Store(store) => {
prune_store_unreachable(odb, store, reachable, keep_newer_than, dry_run)
}
}
}
const PRUNE_REMOVE_BATCH: usize = 1024;
fn prune_store_unreachable(
odb: &Odb,
store: &dyn PrunableObjectStore,
reachable: &LazyReachable<'_>,
keep_newer_than: Option<SystemTime>,
dry_run: bool,
) -> Result<PruneStats> {
let mut stats = PruneStats::default();
let mut listed = Vec::new();
store.for_each_object(&mut |oid| {
listed.push(*oid);
ControlFlow::Continue(())
})?;
let mut candidates = Vec::with_capacity(listed.len());
for oid in listed {
let too_new = match keep_newer_than {
None => false,
Some(cutoff) => store
.object_mtime(&oid)?
.is_none_or(|mtime| mtime >= cutoff),
};
if too_new {
stats.kept += 1;
} else {
candidates.push(oid);
}
}
if candidates.is_empty() {
reachable.require_roots_exist()?;
return Ok(stats);
}
let reachable = reachable.get()?;
let (kept, unreachable): (Vec<_>, Vec<_>) = candidates
.into_iter()
.partition(|oid| reachable.contains(oid));
stats.kept += kept.len();
if dry_run {
stats.pruned += unreachable.len();
return Ok(stats);
}
for batch in unreachable.chunks(PRUNE_REMOVE_BATCH) {
stats.pruned += store.remove(batch)?;
}
store.flush()?;
if !unreachable.is_empty() {
odb.forget_session_reads();
}
Ok(stats)
}
fn prune_files_unreachable(
odb: &Odb,
reachable: &LazyReachable<'_>,
keep_newer_than: Option<SystemTime>,
dry_run: bool,
) -> Result<PruneStats> {
let mut stats = PruneStats::default();
let candidates: Vec<_> = odb
.enumerate_local_loose_objects()?
.into_iter()
.filter(|(_, path)| {
let too_new = keep_newer_than.is_some_and(|cutoff| {
std::fs::metadata(path)
.and_then(|m| m.modified())
.is_ok_and(|mtime| mtime >= cutoff)
});
if too_new {
stats.kept += 1;
}
!too_new
})
.collect();
if candidates.is_empty() {
reachable.require_roots_exist()?;
return Ok(stats);
}
let reachable = reachable.get()?;
for (oid, path) in candidates {
if reachable.contains(&oid) {
stats.kept += 1;
continue;
}
if dry_run {
stats.pruned += 1;
continue;
}
match std::fs::remove_file(&path) {
Ok(()) => stats.pruned += 1,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => stats.pruned += 1,
Err(e) => return Err(e.into()),
}
}
Ok(stats)
}
pub(crate) fn collect_referenced_object_roots(git_dir: &Path) -> Result<Vec<ObjectId>> {
let mut roots = HashSet::new();
for (_, oid) in refs::list_refs(git_dir, "refs/")? {
roots.insert(oid);
}
let head_path = git_dir.join("HEAD");
if head_path.is_file() {
match refs::read_ref_file(&head_path)? {
Ref::Direct(oid) => {
roots.insert(oid);
}
Ref::Symbolic(_) => {}
}
}
Ok(roots.into_iter().collect())
}
pub(crate) struct LazyReachable<'a> {
odb: &'a Odb,
roots: &'a [ObjectId],
shallow: &'a HashSet<ObjectId>,
closure: OnceCell<OidHashSet>,
promised: OnceCell<HashSet<ObjectId>>,
}
impl<'a> LazyReachable<'a> {
pub fn new(odb: &'a Odb, roots: &'a [ObjectId], shallow: &'a HashSet<ObjectId>) -> Self {
Self {
odb,
roots,
shallow,
closure: OnceCell::new(),
promised: OnceCell::new(),
}
}
pub(crate) fn get(&self) -> Result<&OidHashSet> {
if let Some(closure) = self.closure.get() {
return Ok(closure);
}
let closure = reachable_closure(self.odb, self.roots, self.shallow, self.promised()?)?;
Ok(self.closure.get_or_init(|| closure))
}
pub(crate) fn require_roots_exist(&self) -> Result<()> {
if self.closure.get().is_some() {
return Ok(());
}
match require_objects_exist(self.odb, self.roots, &HashSet::new()) {
Err(Error::Object(ObjectError::NotFound { .. })) => {
require_objects_exist(self.odb, self.roots, self.promised()?)
}
result => result,
}
}
pub(crate) fn promised(&self) -> Result<&HashSet<ObjectId>> {
if let Some(promised) = self.promised.get() {
return Ok(promised);
}
let promised = crate::promisor::maintenance_promise_boundary(self.odb)?;
Ok(self.promised.get_or_init(|| promised))
}
}
pub(crate) const S_IFMT: u32 = 0o170000;
pub(crate) const S_IFDIR: u32 = 0o040000;
fn reachable_closure(
odb: &Odb,
roots: &[ObjectId],
shallow: &HashSet<ObjectId>,
promised: &HashSet<ObjectId>,
) -> Result<OidHashSet> {
let mut seen: OidHashSet = promised.iter().copied().collect();
let mut queue: VecDeque<ObjectId> = VecDeque::new();
let oid_len = odb.hash_algo().len();
let mut blobs: Vec<ObjectId> = Vec::new();
let alternates = crate::alternate_boundary::AlternateSources::load(odb)?;
for &root in roots {
if seen.insert(root) && !alternates.contains(&root) {
queue.push_back(root);
}
}
while let Some(oid) = queue.pop_front() {
if alternates.contains(&oid) {
continue;
}
let obj = odb
.try_read_once(&oid)?
.ok_or_else(|| Error::Object(ObjectError::NotFound { name: oid.to_hex() }))?;
match obj.kind {
ObjectKind::Commit => {
let commit = parse_commit(&obj.data)?;
if !shallow.contains(&oid) {
for parent in commit.parents {
if seen.insert(parent) && !alternates.contains(&parent) {
queue.push_back(parent);
}
}
}
if seen.insert(commit.tree) && !alternates.contains(&commit.tree) {
queue.push_back(commit.tree);
}
}
ObjectKind::Tree => {
for entry in TreeRefIter::with_oid_len(&obj.data, oid_len) {
let entry = entry?;
if entry.mode == 0o160000 {
continue;
}
if !seen.insert(entry.oid) {
continue;
}
if alternates.contains(&entry.oid) {
continue;
}
if entry.mode & S_IFMT == S_IFDIR {
queue.push_back(entry.oid);
} else {
blobs.push(entry.oid);
}
}
}
ObjectKind::Tag => {
let tag = parse_tag(&obj.data)?;
if seen.insert(tag.object) && !alternates.contains(&tag.object) {
queue.push_back(tag.object);
}
}
ObjectKind::Blob => {}
}
}
require_objects_exist(odb, &blobs, promised)?;
Ok(seen)
}
fn require_objects_exist(odb: &Odb, oids: &[ObjectId], promised: &HashSet<ObjectId>) -> Result<()> {
let indexes = odb.local_pack_indexes().unwrap_or_default();
for oid in oids {
if promised.contains(oid) {
continue;
}
let packed = indexes.iter().any(|idx| idx.find_position(oid).is_some());
if !packed && !odb.contains(oid)? {
return Err(Error::Object(ObjectError::NotFound { name: oid.to_hex() }));
}
}
Ok(())
}
pub fn remote_default_branch_local(remote_git_dir: &Path) -> Result<Option<String>> {
let remote_odb =
Odb::new(&remote_git_dir.join("objects")).with_config_git_dir(remote_git_dir.to_path_buf());
let entries = crate::remote::list_refs_from_git_dir(
remote_git_dir,
Some(&remote_odb),
&crate::remote::ListRefsOptions {
symrefs: true,
..Default::default()
},
)?;
for entry in &entries {
if entry.name == "HEAD" {
return Ok(entry
.symref_target
.as_ref()
.map(|t| t.strip_prefix("refs/heads/").unwrap_or(t).to_owned()));
}
}
Ok(None)
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RefTransactionItem {
pub name: String,
pub new_oid: Option<ObjectId>,
pub expected_old: Option<ObjectId>,
}
pub fn update_refs(git_dir: &Path, updates: &[RefTransactionItem]) -> Result<()> {
if updates.is_empty() {
return Ok(());
}
let store_updates: Vec<RefUpdate> = updates
.iter()
.map(ref_transaction_item_to_store_update)
.collect();
refs::commit_ref_store_batch(git_dir, &store_updates)
}
fn ref_transaction_item_to_store_update(item: &RefTransactionItem) -> RefUpdate {
let mut flags = RefUpdateFlags::default();
if item.name == "HEAD" {
flags.no_deref = true;
}
RefUpdate {
name: crate::refs::store::RefName::from_trusted(item.name.clone()),
new_value: item.new_oid.map(RawRef::Direct),
expected: match item.expected_old {
Some(oid) => Expected::Oid(oid),
None => Expected::Any,
},
reflog: None,
flags,
}
}
#[cfg(test)]
mod update_refs_tests {
use super::*;
use crate::error::Error;
use crate::error::RefError;
use crate::refs::store::RefStoreError;
use crate::repo::init_repository;
use tempfile::TempDir;
fn sample_oid(hex: &str) -> ObjectId {
hex.parse().expect("oid")
}
#[test]
fn rejects_duplicate_ref_names_in_batch() {
let tmp = TempDir::new().expect("tempdir");
let repo = init_repository(
tmp.path(),
false,
"main",
None,
crate::RefStorageFormat::Files,
)
.expect("init");
let oid = sample_oid("67bf698f3ab735e92fb011a99cff3497c44d30c1");
let items = vec![
RefTransactionItem {
name: "refs/heads/dup".to_owned(),
new_oid: Some(oid),
expected_old: None,
},
RefTransactionItem {
name: "refs/heads/dup".to_owned(),
new_oid: Some(oid),
expected_old: None,
},
];
let err = update_refs(&repo.git_dir(), &items).expect_err("duplicate");
match &err {
Error::Ref(RefError::Store(RefStoreError::DuplicateUpdate { name })) => {
assert_eq!(name, "refs/heads/dup");
}
other => panic!("expected DuplicateUpdate, got {other}"),
}
}
#[test]
fn update_refs_typed_errors() {
let tmp = TempDir::new().expect("tempdir");
let repo = init_repository(
tmp.path(),
false,
"main",
None,
crate::RefStorageFormat::Files,
)
.expect("init");
let git_dir = repo.git_dir();
let c1 = refs::test_commit(&git_dir, "c1");
let c2 = refs::test_commit(&git_dir, "c2");
refs::write_ref(&git_dir, "refs/heads/cas", &c2).expect("seed");
let err = update_refs(
&git_dir,
&[RefTransactionItem {
name: "refs/heads/cas".to_owned(),
new_oid: Some(c1),
expected_old: Some(c1),
}],
)
.expect_err("stale cas");
match &err {
Error::Ref(RefError::Store(RefStoreError::ExpectedMismatch { name, .. })) => {
assert_eq!(name, "refs/heads/cas");
}
other => panic!("expected ExpectedMismatch, got {other}"),
}
}
#[test]
fn reftable_cas_rechecked_under_stack_lock() {
let tmp = TempDir::new().expect("tempdir");
let repo = init_repository(
tmp.path(),
false,
"main",
None,
crate::RefStorageFormat::Reftable,
)
.expect("init");
let git_dir = repo.git_dir();
let c1 = refs::test_commit(&git_dir, "c1");
let c2 = refs::test_commit(&git_dir, "c2");
crate::refs::write_ref(&git_dir, "refs/heads/locked-cas", &c1).expect("seed");
crate::refs::write_ref(&git_dir, "refs/heads/locked-cas", &c2).expect("advance");
let err = update_refs(
&git_dir,
&[RefTransactionItem {
name: "refs/heads/locked-cas".to_owned(),
new_oid: Some(c1),
expected_old: Some(c1),
}],
)
.expect_err("stale cas");
assert!(
matches!(
err,
Error::Ref(RefError::Store(RefStoreError::ExpectedMismatch { .. }))
),
"{err}"
);
assert_eq!(
crate::refs::resolve_ref(&git_dir, "refs/heads/locked-cas").unwrap(),
c2
);
}
#[cfg_attr(
not(feature = "full-tests"),
ignore = "starts system git or is heavy; run with --features full-tests"
)]
#[test]
fn apply_cas_rejects_after_concurrent_packed_delete() {
let _pause_serial = refs::inject::pause_injection_test_scope();
use std::path::Path;
use std::process::Command;
use std::sync::Arc;
use std::thread;
let _pause_scope = refs::inject::ref_store_batch_pause_test_scope();
fn git(dir: &Path, args: &[&str]) {
let out = Command::new("git")
.current_dir(dir)
.args(args)
.env("GIT_AUTHOR_NAME", "T")
.env("GIT_AUTHOR_EMAIL", "t@example.com")
.env("GIT_COMMITTER_NAME", "T")
.env("GIT_COMMITTER_EMAIL", "t@example.com")
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("GIT_CONFIG_SYSTEM", "/dev/null")
.output()
.expect("git");
assert!(
out.status.success(),
"git {:?}: {}",
args,
String::from_utf8_lossy(&out.stderr)
);
}
fn rev_parse(repo: &Path, refname: &str) -> ObjectId {
let hex = Command::new("git")
.current_dir(repo)
.args(["rev-parse", refname])
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("GIT_CONFIG_SYSTEM", "/dev/null")
.output()
.expect("rev-parse")
.stdout;
String::from_utf8(hex)
.expect("utf8")
.trim()
.parse()
.expect("oid")
}
let tmp = TempDir::new().expect("tempdir");
let repo = tmp.path().join("repo");
std::fs::create_dir_all(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main", "."]);
let git_dir = repo.join(".git");
std::fs::write(repo.join("f.txt"), "one\n").unwrap();
git(&repo, &["add", "f.txt"]);
git(&repo, &["commit", "-q", "-m", "c1"]);
let c1 = rev_parse(&repo, "HEAD");
std::fs::write(repo.join("f.txt"), "two\n").unwrap();
git(&repo, &["add", "f.txt"]);
git(&repo, &["commit", "-q", "-m", "c2"]);
let c2 = rev_parse(&repo, "HEAD");
for name in ["refs/heads/first", "refs/heads/middle", "refs/heads/last"] {
git(&repo, &["update-ref", name, &c1.to_hex()]);
}
git(&repo, &["pack-refs", "--all"]);
for name in ["first", "middle", "last"] {
let _ = std::fs::remove_file(git_dir.join(format!("refs/heads/{name}")));
}
let gate = refs::inject::ref_store_batch_pause_gate();
refs::inject::set_ref_store_batch_pause_after_apply(0, &git_dir, Some(Arc::clone(&gate)));
let updates = vec![
RefTransactionItem {
name: "refs/heads/first".to_owned(),
new_oid: Some(c2),
expected_old: Some(c1),
},
RefTransactionItem {
name: "refs/heads/middle".to_owned(),
new_oid: Some(c2),
expected_old: Some(c1),
},
RefTransactionItem {
name: "refs/heads/last".to_owned(),
new_oid: Some(c2),
expected_old: Some(c1),
},
];
let git_dir_thread = git_dir.clone();
let updates_thread = updates.clone();
let worker = thread::spawn(move || update_refs(&git_dir_thread, &updates_thread));
let mut paused = gate.wait.lock().expect("lock");
while !*paused {
paused = gate.cv.wait(paused).expect("wait");
}
git(
&repo,
&["update-ref", "-d", "refs/heads/last", &c1.to_hex()],
);
*paused = false;
gate.cv.notify_all();
drop(paused);
let err = worker.join().expect("join").expect_err("stale CAS");
match &err {
Error::Ref(RefError::Store(RefStoreError::ExpectedMismatch { name, .. })) => {
assert_eq!(name, "refs/heads/last");
}
other => panic!("expected ExpectedMismatch for last ref, got {other}"),
}
assert!(crate::refs::resolve_ref(&git_dir, "refs/heads/last").is_err());
assert_eq!(
crate::refs::resolve_ref(&git_dir, "refs/heads/first").expect("first"),
c2
);
refs::inject::set_ref_store_batch_pause_after_apply(0, &git_dir, None);
}
#[cfg_attr(
not(feature = "full-tests"),
ignore = "starts system git or is heavy; run with --features full-tests"
)]
#[test]
fn unconditional_create_rejects_after_concurrent_packed_parent() {
let _pause_serial = refs::inject::pause_injection_test_scope();
use std::path::Path;
use std::process::Command;
use std::sync::Arc;
use std::thread;
let _pause_scope = refs::inject::ref_store_batch_pause_test_scope();
fn git(dir: &Path, args: &[&str]) {
let out = Command::new("git")
.current_dir(dir)
.args(args)
.env("GIT_AUTHOR_NAME", "T")
.env("GIT_AUTHOR_EMAIL", "t@example.com")
.env("GIT_COMMITTER_NAME", "T")
.env("GIT_COMMITTER_EMAIL", "t@example.com")
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("GIT_CONFIG_SYSTEM", "/dev/null")
.output()
.expect("git");
assert!(
out.status.success(),
"git {:?}: {}",
args,
String::from_utf8_lossy(&out.stderr)
);
}
fn rev_parse(repo: &Path, refname: &str) -> ObjectId {
let hex = Command::new("git")
.current_dir(repo)
.args(["rev-parse", refname])
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.env("GIT_CONFIG_SYSTEM", "/dev/null")
.output()
.expect("rev-parse")
.stdout;
String::from_utf8(hex)
.expect("utf8")
.trim()
.parse()
.expect("oid")
}
let tmp = TempDir::new().expect("tempdir");
let repo = tmp.path().join("repo");
std::fs::create_dir_all(&repo).unwrap();
git(&repo, &["init", "-q", "-b", "main", "."]);
let git_dir = repo.join(".git");
std::fs::write(repo.join("f.txt"), "one\n").unwrap();
git(&repo, &["add", "f.txt"]);
git(&repo, &["commit", "-q", "-m", "c1"]);
let c1 = rev_parse(&repo, "HEAD");
let gate = refs::inject::ref_store_batch_pause_gate();
refs::inject::set_ref_store_batch_pause_after_apply(0, &git_dir, Some(Arc::clone(&gate)));
let updates = vec![
RefTransactionItem {
name: "refs/heads/one".to_owned(),
new_oid: Some(c1),
expected_old: None,
},
RefTransactionItem {
name: "refs/heads/two".to_owned(),
new_oid: Some(c1),
expected_old: None,
},
RefTransactionItem {
name: "refs/heads/conflict/child".to_owned(),
new_oid: Some(c1),
expected_old: None,
},
];
let git_dir_thread = git_dir.clone();
let updates_thread = updates.clone();
let worker = thread::spawn(move || update_refs(&git_dir_thread, &updates_thread));
let mut paused = gate.wait.lock().expect("lock");
while !*paused {
paused = gate.cv.wait(paused).expect("wait");
}
git(&repo, &["update-ref", "refs/heads/conflict", &c1.to_hex()]);
git(&repo, &["pack-refs", "--all"]);
*paused = false;
gate.cv.notify_all();
drop(paused);
let err = worker
.join()
.expect("join")
.expect_err("namespace conflict on child");
assert!(
err.to_string().contains("namespace conflict")
|| err.to_string().contains("cannot lock ref"),
"{err}"
);
assert!(crate::refs::resolve_ref(&git_dir, "refs/heads/conflict").is_ok());
assert!(crate::refs::resolve_ref(&git_dir, "refs/heads/conflict/child").is_err());
refs::inject::set_ref_store_batch_pause_after_apply(0, &git_dir, None);
}
}
#[cfg(test)]
mod prune_walk_tests {
use super::*;
use crate::maintenance::{repack, RepackOptions};
use crate::repo::init_repository;
use tempfile::TempDir;
#[test]
fn promise_boundary_is_shared_and_missing_local_objects_still_fail() {
let tmp = TempDir::new().expect("tempdir");
let repo = init_repository(
tmp.path(),
true,
"main",
None,
crate::RefStorageFormat::Files,
)
.expect("init");
let missing = ObjectId::from_hex("1234567890123456789012345678901234567890").expect("oid");
let mut tree = b"100644 promised\0".to_vec();
tree.extend_from_slice(missing.as_bytes());
let tree = repo.odb().write(ObjectKind::Tree, &tree).expect("tree");
crate::promisor::write_promisor_marker(repo.git_dir(), &HashSet::from([missing]))
.expect("marker");
let roots = [tree];
let shallow = HashSet::new();
let reachable = LazyReachable::new(repo.odb(), &roots, &shallow);
assert!(reachable.get().expect("closure").contains(&missing));
crate::promisor::write_promisor_marker(repo.git_dir(), &HashSet::new())
.expect("clear marker");
assert!(reachable
.promised()
.expect("cached promises")
.contains(&missing));
let next = LazyReachable::new(repo.odb(), &roots, &shallow);
assert!(matches!(
next.get(),
Err(Error::Object(ObjectError::NotFound { .. }))
));
}
#[test]
fn prune_checks_packed_blobs_without_per_object_lookups() {
let tmp = TempDir::new().expect("tempdir");
let repo = init_repository(
tmp.path(),
false,
"main",
None,
crate::RefStorageFormat::Files,
)
.expect("init");
let odb = repo.odb();
let mut tree = Vec::new();
for i in 0..50 {
let blob = odb
.write(ObjectKind::Blob, format!("blob {i}\n").as_bytes())
.expect("blob");
tree.extend_from_slice(format!("100644 f{i:02}\0").as_bytes());
tree.extend_from_slice(blob.as_bytes());
}
let tree = odb.write(ObjectKind::Tree, &tree).expect("tree");
let commit = format!(
"tree {tree}\nauthor A <a@example.com> 1 +0000\ncommitter A <a@example.com> 1 +0000\n\nm\n"
);
let commit = odb
.write(ObjectKind::Commit, commit.as_bytes())
.expect("commit");
std::fs::write(
repo.git_dir().join("refs/heads/main"),
format!("{}\n", commit.to_hex()),
)
.expect("ref");
repack(
&repo,
&RepackOptions::default(),
&mut crate::progress::NullProgress,
&crate::progress::CancelToken::never(),
)
.expect("repack");
assert!(odb
.enumerate_local_loose_objects()
.expect("loose")
.is_empty());
odb.reset_exists_probe();
let stats = prune_loose_unreachable(odb, &[commit], None).expect("prune");
assert_eq!(stats, PruneStats::default());
assert_eq!(
odb.exists_probe_count(),
0,
"packed blobs must be checked against the pack indexes, not one lookup each"
);
}
}