use std::path::{Path, PathBuf};
use std::sync::Arc;
use crate::commit_graph_file::CommitGraphChain;
use crate::commit_graph_write::collect_reachable_commit_infos;
use crate::config::ConfigSet;
use crate::error::Result;
use crate::fsck::reachability_roots;
use crate::gc::prune_loose_unreachable;
use crate::objects::HashAlgo;
use crate::odb::store::{ObjectStore, PrunableObjectStore, WritableObjectStore};
use crate::repo::error::FilesOnlyOperation;
use crate::repo::Repository;
use crate::repo::RepositoryError;
use super::{Odb, PrimaryStore};
pub(crate) enum PruneTarget<'a> {
Files,
Store(&'a dyn PrunableObjectStore),
}
#[derive(Debug, Clone, Default)]
pub struct OdbBuilder {
read_sources: Vec<Arc<dyn ObjectStore>>,
alternates: Option<bool>,
commit_graph: Option<Arc<CommitGraphChain>>,
}
impl OdbBuilder {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn push_read_source(mut self, store: Arc<dyn ObjectStore>) -> Self {
self.read_sources.push(store);
self
}
#[must_use]
pub fn commit_graph(mut self, chain: Arc<CommitGraphChain>) -> Self {
self.commit_graph = Some(chain);
self
}
#[must_use]
pub fn alternates(mut self, enabled: bool) -> Self {
self.alternates = Some(enabled);
self
}
pub(crate) fn injected_hash_algos(&self) -> impl Iterator<Item = HashAlgo> + '_ {
self.read_sources
.iter()
.map(|store| store.hash_algo())
.chain(self.commit_graph.iter().map(|chain| chain.hash_algo()))
}
pub(crate) fn build(
self,
objects_dir: &Path,
primary: Option<Arc<dyn WritableObjectStore>>,
) -> Odb {
let mut odb = Odb::new(objects_dir);
odb.alternates_enabled = self.alternates.unwrap_or(primary.is_none());
if let Some(store) = primary {
odb.primary = PrimaryStore::Custom(store);
}
odb.extra_read_sources = self.read_sources;
odb.attached_commit_graph = self.commit_graph;
odb
}
}
impl Odb {
#[must_use]
pub fn uses_files_primary(&self) -> bool {
matches!(self.primary, PrimaryStore::Files(_))
}
#[must_use]
pub fn files_objects_dir(&self) -> Option<&Path> {
match self.primary {
PrimaryStore::Files(_) => Some(&self.objects_dir),
PrimaryStore::Custom(_) => None,
}
}
pub fn primary_writable(&self) -> Result<Arc<dyn WritableObjectStore>> {
match &self.primary {
PrimaryStore::Custom(primary) => Ok(Arc::clone(primary)),
PrimaryStore::Files(_) => Ok(self.primary()? as Arc<dyn WritableObjectStore>),
}
}
pub(crate) fn prune_target(&self) -> Result<PruneTarget<'_>> {
let PrimaryStore::Custom(primary) = &self.primary else {
return Ok(PruneTarget::Files);
};
primary
.as_prunable()
.map(PruneTarget::Store)
.ok_or_else(|| {
RepositoryError::UnsupportedObjectStore {
operation: FilesOnlyOperation::Prune,
}
.into()
})
}
pub fn gc(&self) -> Result<()> {
self.prune_target()?;
let Some(git_dir) = self.config_git_dir() else {
return Err(RepositoryError::UnsupportedObjectStore {
operation: FilesOnlyOperation::Gc,
}
.into());
};
let environment = self
.shared_environment
.as_deref()
.cloned()
.unwrap_or_else(crate::environment::Environment::empty);
let mut opts = crate::environment::RepositoryOptions::with_environment(environment);
if let PrimaryStore::Custom(primary) = &self.primary {
let mut builder = OdbBuilder::new().alternates(self.alternates_enabled);
for source in &self.extra_read_sources {
builder = builder.push_read_source(Arc::clone(source));
}
opts = opts
.with_object_store(Arc::clone(primary))
.with_odb_builder(builder);
if let Some(caches) = &self.shared_config_state {
let ref_store = caches.open_ref_store(git_dir, &opts.environment)?;
opts = opts.with_ref_store(ref_store);
}
}
let repo = if git_dir.file_name().is_some_and(|n| n == ".git") {
let wt = git_dir
.parent()
.ok_or(RepositoryError::UnsupportedObjectStore {
operation: FilesOnlyOperation::Gc,
})?;
Repository::open(git_dir, &opts.with_work_tree(wt))?
} else {
Repository::open(git_dir, &opts)?
};
crate::maintenance::refuse_precious_objects(&repo, "gc")?;
let roots = reachability_roots(&repo)?;
prune_loose_unreachable(self, &roots, None)?;
Ok(())
}
pub fn write_commit_graph(&self) -> Result<()> {
self.primary
.require_files_primary(FilesOnlyOperation::CommitGraphWrite)?;
let Some(git_dir) = self.config_git_dir() else {
return Err(RepositoryError::UnsupportedObjectStore {
operation: FilesOnlyOperation::CommitGraphWrite,
}
.into());
};
let Some(objects_dir) = self.files_objects_dir() else {
return Err(RepositoryError::UnsupportedObjectStore {
operation: FilesOnlyOperation::CommitGraphWrite,
}
.into());
};
let config = ConfigSet::load(
&crate::environment::Environment::empty(),
Some(git_dir),
&crate::config::LoadConfigOptions::standard(
&crate::environment::Environment::empty(),
Some(git_dir),
),
)
.unwrap_or_default();
let skip = crate::maintenance::CommitGraphSkipReason::detect(git_dir, || {
let enabled = config.bool_with_default("core.useReplaceRefs", true);
Ok(enabled && !crate::refs::list_refs(git_dir, "refs/replace/")?.is_empty())
})?;
if skip.is_some() {
crate::commit_graph_write::remove_commit_graph_files(objects_dir)?;
return Ok(());
}
let commits = collect_reachable_commit_infos(git_dir, self)?;
if commits.is_empty() {
return Ok(());
}
let existing = CommitGraphChain::try_load(objects_dir).ok().flatten();
let built = crate::maintenance::build_commit_graph_for_commits(
self,
&commits,
&config,
true,
existing.as_ref(),
)?;
crate::commit_graph_write::atomic_replace_commit_graph(objects_dir, &built.bytes)?;
let _ = crate::commit_graph_write::remove_commit_graph_chain_dir(objects_dir);
Ok(())
}
#[must_use]
pub fn with_resolved_work_tree(mut self, work_tree: Option<PathBuf>) -> Self {
self.work_tree = work_tree;
self
}
}