use std::collections::{BTreeSet, HashMap, HashSet};
use std::os::fd::{AsFd, BorrowedFd, OwnedFd};
use std::sync::Arc;
use ostrya_core::{Checksum, ObjectName, ObjectType, RepoMode, loose_path};
use rustix::fs::AtFlags;
use rustix::io::Errno;
use crate::error::{Error, Result};
use crate::lock::LockKind;
use crate::repo::Repo;
use crate::tombstone::write_tombstone;
use crate::traverse::{ListedRef, ParentBound, RefSpace, WeakBounds};
pub type WeakRefFilterFn = Arc<dyn Fn(&str, &Checksum) -> bool + Send + Sync>;
#[derive(Clone, Default)]
pub struct WeakRefFilter(Option<WeakRefFilterFn>);
impl WeakRefFilter {
pub fn new<F>(f: F) -> WeakRefFilter
where
F: Fn(&str, &Checksum) -> bool + Send + Sync + 'static,
{
WeakRefFilter(Some(Arc::new(f)))
}
pub fn from_fn(f: WeakRefFilterFn) -> WeakRefFilter {
WeakRefFilter(Some(f))
}
pub(crate) fn is_set(&self) -> bool {
self.0.is_some()
}
pub(crate) fn is_strong(&self, name: &str, target: &Checksum) -> bool {
match &self.0 {
Some(f) => f(name, target),
None => true,
}
}
}
impl std::fmt::Debug for WeakRefFilter {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self.0 {
Some(_) => f.write_str("WeakRefFilter(set)"),
None => f.write_str("WeakRefFilter(unset)"),
}
}
}
#[derive(Debug, Clone)]
pub struct PruneOptions {
pub refs_only: bool,
pub depth: i32,
pub no_prune: bool,
pub delete_commit: Option<Checksum>,
pub keep_younger_than: Option<u64>,
pub only_branch: Vec<String>,
pub retain_branch_depth: Vec<(String, i32)>,
pub commit_only: bool,
pub static_deltas_only: bool,
pub gc_root_metadata_keys: Vec<String>,
pub traverse_parent: bool,
pub weak_ref_filter: WeakRefFilter,
}
impl Default for PruneOptions {
fn default() -> Self {
PruneOptions {
refs_only: false,
depth: -1,
no_prune: false,
delete_commit: None,
keep_younger_than: None,
only_branch: Vec::new(),
retain_branch_depth: Vec::new(),
commit_only: false,
static_deltas_only: false,
gc_root_metadata_keys: Vec::new(),
traverse_parent: true,
weak_ref_filter: WeakRefFilter::default(),
}
}
}
impl PruneOptions {
pub fn new() -> PruneOptions {
PruneOptions::default()
}
pub fn gc_roots<I, S>(keys: I) -> PruneOptions
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
PruneOptions {
refs_only: true,
gc_root_metadata_keys: keys.into_iter().map(Into::into).collect(),
traverse_parent: false,
..PruneOptions::default()
}
}
fn global_bound(&self) -> ParentBound {
match self.keep_younger_than {
Some(since) => ParentBound::Since(since),
None => ParentBound::depth(self.depth),
}
}
fn roots_on_refs_alone(&self) -> bool {
self.refs_only
|| self.keep_younger_than.is_some()
|| !self.only_branch.is_empty()
|| !self.retain_branch_depth.is_empty()
}
fn ref_bound(&self, name: &str) -> ParentBound {
let entry = self
.retain_branch_depth
.iter()
.rev()
.find(|(branch, _)| branch == name)
.map(|(_, depth)| *depth);
match entry {
Some(depth) if depth != 0 => ParentBound::depth(depth),
entry => {
let named = entry.is_some() || self.only_branch.iter().any(|value| value == name);
if self.only_branch.is_empty() || named {
self.global_bound()
} else {
ParentBound::Depth(-1)
}
}
}
}
}
fn counted(ty: ObjectType, commit_only: bool) -> bool {
if commit_only {
ty == ObjectType::Commit
} else {
!matches!(ty, ObjectType::CommitMeta | ObjectType::TombstoneCommit)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PruneStats {
pub total_objects: usize,
pub pruned_objects: usize,
pub freed_bytes: u64,
pub deleted_refs: Vec<String>,
}
#[derive(Debug, Clone, Copy)]
struct Sweep {
mode: RepoMode,
no_prune: bool,
tombstones: bool,
fsync: bool,
commit_only: bool,
}
impl Repo {
pub async fn prune(&self, opts: &PruneOptions) -> Result<PruneStats> {
let mode = self.mode();
if opts.static_deltas_only && opts.delete_commit.is_none() {
return Err(Error::InvalidFormat(
"static_deltas_only requires delete_commit".into(),
));
}
if opts.weak_ref_filter.is_set() && !opts.refs_only {
return Err(Error::InvalidFormat(
"weak_ref_filter requires refs_only".into(),
));
}
let _lock = self.lock_repo(LockKind::Exclusive).await?;
let Some(delta_target) = opts.delete_commit else {
return self.prune_objects(opts, mode).await;
};
if opts.static_deltas_only {
let commit_only = opts.commit_only;
let total_objects = self
.count_objects(move |ty| counted(ty, commit_only))
.await?;
if !opts.no_prune {
let repo = self.clone();
ostrya_rt::unblock(move || {
crate::delta::prune_delta_dirs(repo.repo_fd(), |to| *to == delta_target)
})
.await?;
}
return Ok(PruneStats {
total_objects,
pruned_objects: 0,
freed_bytes: 0,
deleted_refs: Vec::new(),
});
}
self.prune_objects(opts, mode).await
}
async fn prune_objects(&self, opts: &PruneOptions, mode: RepoMode) -> Result<PruneStats> {
if let Some(commit) = opts.delete_commit {
self.refuse_referenced_commit(&commit).await?;
}
let named_refs = self.list_all_refs().await?;
for value in &opts.only_branch {
self.resolve_rev(value, false).await?;
}
let filtering = opts.weak_ref_filter.is_set();
let mut roots: Vec<(Checksum, ParentBound)> = Vec::new();
let mut ref_targets: HashSet<Checksum> = HashSet::new();
let mut weak_refs: Vec<(String, Checksum)> = Vec::new();
let mut weak_roots: HashMap<Checksum, WeakBounds> = HashMap::new();
for ListedRef {
space,
name,
addressable,
checksum,
} in named_refs
{
let bound = opts.ref_bound(&name);
let weak = filtering
&& matches!(space, RefSpace::Heads | RefSpace::Remotes)
&& addressable
&& !opts.weak_ref_filter.is_strong(&name, &checksum);
if weak {
weak_roots.entry(checksum).or_default().add(bound);
weak_refs.push((name, checksum));
continue;
}
roots.push((checksum, bound));
ref_targets.insert(checksum);
}
let mut all_objects = self.list_objects().await?;
if let Some(commit) = opts.delete_commit {
all_objects.remove(&ObjectName::new(commit, ObjectType::Commit));
all_objects.remove(&ObjectName::new(commit, ObjectType::CommitMeta));
}
let global_bound = opts.global_bound();
if !opts.roots_on_refs_alone() {
roots.extend(
all_objects
.iter()
.filter(|o| o.ty == ObjectType::Commit)
.map(|o| (o.checksum, global_bound)),
);
}
let gc = crate::traverse::GcRoots {
metadata_keys: opts.gc_root_metadata_keys.clone(),
traverse_parent: opts.traverse_parent,
traverse_tree: !opts.commit_only,
weak_roots,
};
let mut keep = self
.traverse_reachable_gc(roots, global_bound, &gc, &ref_targets, opts.delete_commit)
.await?;
let kept_commits: Vec<Checksum> = keep
.iter()
.filter(|name| name.ty == ObjectType::Commit)
.map(|name| name.checksum)
.collect();
for checksum in kept_commits {
keep.insert(ObjectName::new(checksum, ObjectType::CommitMeta));
}
let mut doomed: Vec<ObjectName> =
Vec::with_capacity(all_objects.len().saturating_sub(keep.len()));
doomed.extend(
all_objects
.iter()
.filter(|o| o.ty != ObjectType::TombstoneCommit && !keep.contains(o))
.filter(|o| {
!opts.commit_only || matches!(o.ty, ObjectType::Commit | ObjectType::CommitMeta)
})
.copied(),
);
let total_objects = all_objects
.iter()
.filter(|o| counted(o.ty, opts.commit_only))
.count();
let sweep = Sweep {
mode,
no_prune: opts.no_prune,
tombstones: opts.delete_commit.is_some() || self.config().tombstone_commits()?,
fsync: self.config().fsync()?,
commit_only: opts.commit_only,
};
let mut doomed_refs = weak_refs;
doomed_refs
.retain(|(_, target)| !keep.contains(&ObjectName::new(*target, ObjectType::Commit)));
let mut deleted_refs: Vec<String> = if opts.no_prune {
doomed_refs.into_iter().map(|(name, _)| name).collect()
} else {
let repo = self.clone();
let fsync = sweep.fsync;
ostrya_rt::unblock(move || {
crate::refs::delete_matching_refs_blocking(repo.repo_fd(), doomed_refs, fsync)
})
.await?
};
deleted_refs.sort();
if !opts.no_prune
&& let Some(commit) = opts.delete_commit
{
self.delete_commit_object(&commit, &sweep).await?;
}
let present_commits: HashSet<Checksum> = if opts.no_prune {
HashSet::new()
} else {
all_objects
.iter()
.filter(|o| o.ty == ObjectType::Commit && keep.contains(o))
.map(|o| o.checksum)
.collect()
};
drop(all_objects);
drop(keep);
let repo = self.clone();
let (pruned_objects, freed_bytes) =
ostrya_rt::unblock(move || sweep_blocking(&repo, &sweep, &doomed)).await?;
if !opts.no_prune {
let repo = self.clone();
ostrya_rt::unblock(move || {
let repo_fd = repo.repo_fd();
crate::delta::prune_delta_dirs(repo_fd, |to| !present_commits.contains(to))?;
sweep_orphan_markers_blocking(repo_fd, &present_commits)
})
.await?;
}
Ok(PruneStats {
total_objects,
pruned_objects,
freed_bytes,
deleted_refs,
})
}
async fn refuse_referenced_commit(&self, commit: &Checksum) -> Result<()> {
let referenced = self.list_all_ref_targets().await?;
if referenced.contains(commit) {
return Err(Error::InvalidFormat(format!(
"cannot delete commit {commit}: it is the target of a ref"
)));
}
Ok(())
}
async fn delete_commit_object(&self, commit: &Checksum, sweep: &Sweep) -> Result<()> {
self.refuse_referenced_commit(commit).await?;
let commit = *commit;
let sweep = *sweep;
let repo = self.clone();
ostrya_rt::unblock(move || {
let objects_fd = repo.objects_fd();
let tmp = tombstone_tmp(&repo, &sweep)?;
let mut touched = BTreeSet::new();
remove_commit(
tmp.as_ref().map(AsFd::as_fd),
objects_fd,
&sweep,
&commit,
true,
&mut touched,
)?;
if sweep.fsync {
sync_dirs(objects_fd, &touched)?;
}
Ok(())
})
.await
}
}
fn sweep_orphan_markers_blocking(
repo_fd: BorrowedFd<'_>,
present: &HashSet<Checksum>,
) -> Result<()> {
use rustix::fs::{Dir, Mode, OFlags, openat};
let io_err = |e: Errno| Error::Io(e.into());
let state = match openat(
repo_fd,
"state",
OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
Mode::empty(),
) {
Ok(fd) => fd,
Err(Errno::NOENT) => return Ok(()),
Err(e) => return Err(io_err(e)),
};
let mut orphans = Vec::new();
for entry in Dir::new(state).map_err(io_err)? {
let entry = entry.map_err(io_err)?;
let Ok(name) = entry.file_name().to_str() else {
continue;
};
let Some(hex) = name.strip_suffix(".commitpartial") else {
continue;
};
let Ok(commit) = Checksum::from_hex_lower(hex) else {
continue;
};
if !present.contains(&commit) {
orphans.push(commit);
}
}
for commit in orphans {
let partial = crate::pull::partial_path(&commit);
match rustix::fs::unlinkat(repo_fd, partial.as_str(), AtFlags::empty()) {
Ok(()) | Err(Errno::NOENT | Errno::ISDIR) => {}
Err(e) => return Err(io_err(e)),
}
}
Ok(())
}
fn tombstone_tmp(repo: &Repo, sweep: &Sweep) -> Result<Option<OwnedFd>> {
if !sweep.tombstones {
return Ok(None);
}
Ok(Some(crate::staging::open_tmp_dir(
repo.repo_fd(),
sweep.mode,
)?))
}
fn remove_commit(
tmp_fd: Option<BorrowedFd<'_>>,
objects_fd: BorrowedFd<'_>,
sweep: &Sweep,
commit: &Checksum,
meta: bool,
touched: &mut BTreeSet<String>,
) -> Result<()> {
if let Some(tmp_fd) = tmp_fd {
write_tombstone(tmp_fd, objects_fd, commit, sweep.mode, sweep.fsync)?;
}
let commit_path = loose_path(commit, ObjectType::Commit, sweep.mode);
let mut unlinked = unlink_optional(objects_fd, &commit_path)?;
if meta {
let meta_path = loose_path(commit, ObjectType::CommitMeta, sweep.mode);
unlinked |= unlink_optional(objects_fd, &meta_path)?;
}
if unlinked {
touched.insert(objects_fanout(commit));
}
Ok(())
}
fn objects_fanout(checksum: &Checksum) -> String {
checksum.to_hex()[..2].to_owned()
}
fn sync_dirs(objects_fd: BorrowedFd<'_>, dirs: &BTreeSet<String>) -> Result<()> {
for dir in dirs {
crate::refs::sync_dir(objects_fd, dir)?;
}
Ok(())
}
fn object_size(objects_fd: BorrowedFd<'_>, path: &str) -> Result<Option<u64>> {
match rustix::fs::statat(objects_fd, path, AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat) => Ok(Some(stat.st_size.max(0) as u64)),
Err(Errno::NOENT) => Ok(None),
Err(e) => Err(Error::Io(e.into())),
}
}
fn sweep_blocking(repo: &Repo, sweep: &Sweep, doomed: &[ObjectName]) -> Result<(usize, u64)> {
let objects_fd = repo.objects_fd();
let mut count = 0usize;
let mut freed = 0u64;
let mut tally = |ty: ObjectType, size: u64| {
if counted(ty, sweep.commit_only) {
count += 1;
freed += size;
}
};
let doomed_meta: HashSet<Checksum> = doomed
.iter()
.filter(|o| o.ty == ObjectType::CommitMeta)
.map(|o| o.checksum)
.collect();
let mut touched = BTreeSet::new();
let mut removed_commits = HashSet::new();
let tmp = if sweep.no_prune || !doomed.iter().any(|o| o.ty == ObjectType::Commit) {
None
} else {
tombstone_tmp(repo, sweep)?
};
for name in doomed.iter().filter(|o| o.ty == ObjectType::Commit) {
let Some(size) = object_size(objects_fd, &name.loose_path(sweep.mode))? else {
continue;
};
if !sweep.no_prune {
let meta = doomed_meta.contains(&name.checksum);
remove_commit(
tmp.as_ref().map(AsFd::as_fd),
objects_fd,
sweep,
&name.checksum,
meta,
&mut touched,
)?;
}
removed_commits.insert(name.checksum);
tally(name.ty, size);
}
for name in doomed
.iter()
.filter(|o| o.ty == ObjectType::CommitMeta && !removed_commits.contains(&o.checksum))
{
let path = name.loose_path(sweep.mode);
let Some(size) = object_size(objects_fd, &path)? else {
continue;
};
if !sweep.no_prune && unlink_optional(objects_fd, &path)? {
touched.insert(objects_fanout(&name.checksum));
}
tally(name.ty, size);
}
if sweep.fsync && !sweep.no_prune {
sync_dirs(objects_fd, &touched)?;
}
for name in doomed
.iter()
.filter(|o| !matches!(o.ty, ObjectType::Commit | ObjectType::CommitMeta))
{
let path = name.loose_path(sweep.mode);
let Some(size) = object_size(objects_fd, &path)? else {
continue;
};
if !sweep.no_prune {
unlink_optional(objects_fd, &path)?;
}
tally(name.ty, size);
}
Ok((count, freed))
}
fn unlink_optional(dir: BorrowedFd<'_>, path: &str) -> Result<bool> {
match rustix::fs::unlinkat(dir, path, AtFlags::empty()) {
Ok(()) => Ok(true),
Err(Errno::NOENT) => Ok(false),
Err(e) => Err(Error::Io(e.into())),
}
}