use std::collections::{HashMap, HashSet};
use std::os::fd::BorrowedFd;
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 {
self.sweep_static_deltas(&HashSet::from([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 repo = self.clone();
let doomed_deltas: HashSet<Checksum> = doomed
.iter()
.filter(|o| o.ty == ObjectType::Commit)
.map(|o| o.checksum)
.chain(opts.delete_commit)
.collect();
let (pruned_objects, freed_bytes) =
ostrya_rt::unblock(move || sweep_blocking(&repo, &sweep, &doomed)).await?;
if !opts.no_prune {
self.sweep_static_deltas(&doomed_deltas).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 mode = self.mode();
let commit = *commit;
let sweep = *sweep;
let repo = self.clone();
ostrya_rt::unblock(move || {
if sweep.tombstones {
write_tombstone(repo.objects_fd(), &commit, sweep.mode, sweep.fsync)?;
}
let commit_path = loose_path(&commit, ObjectType::Commit, mode);
unlink_optional(repo.objects_fd(), &commit_path)?;
let meta_path = loose_path(&commit, ObjectType::CommitMeta, mode);
unlink_optional(repo.objects_fd(), &meta_path)?;
let partial = crate::pull::partial_path(&commit);
unlink_optional(repo.repo_fd(), &partial)?;
Ok(())
})
.await
}
async fn sweep_static_deltas(&self, targets: &HashSet<Checksum>) -> Result<()> {
if targets.is_empty() {
return Ok(());
}
let targets = targets.clone();
let repo = self.clone();
ostrya_rt::unblock(move || {
let repo_fd = repo.repo_fd();
for dir in crate::delta::list_delta_dirs(repo_fd)? {
if targets.contains(&dir.to) {
crate::delta::remove_delta_dir(repo_fd, &dir)?;
}
}
Ok(())
})
.await
}
}
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;
for name in doomed {
let path = name.loose_path(sweep.mode);
let size = match rustix::fs::statat(objects_fd, path.as_str(), AtFlags::SYMLINK_NOFOLLOW) {
Ok(stat) => stat.st_size.max(0) as u64,
Err(Errno::NOENT) => continue,
Err(e) => return Err(Error::Io(e.into())),
};
if !sweep.no_prune {
if sweep.tombstones && name.ty == ObjectType::Commit {
write_tombstone(objects_fd, &name.checksum, sweep.mode, sweep.fsync)?;
}
unlink_optional(objects_fd, &path)?;
if name.ty == ObjectType::Commit {
let partial = crate::pull::partial_path(&name.checksum);
unlink_optional(repo.repo_fd(), &partial)?;
}
}
if !counted(name.ty, sweep.commit_only) {
continue;
}
count += 1;
freed += size;
}
Ok((count, freed))
}
fn unlink_optional(dir: BorrowedFd<'_>, path: &str) -> Result<()> {
match rustix::fs::unlinkat(dir, path, AtFlags::empty()) {
Ok(()) | Err(Errno::NOENT) => Ok(()),
Err(e) => Err(Error::Io(e.into())),
}
}