Skip to main content

git2db/
repo_accessor.rs

1//! Shared repository access trait for managers
2//!
3//! Provides common functionality for managers that need to access repositories
4//! tracked by the registry.
5
6use crate::errors::{Git2DBError, Git2DBResult};
7use crate::registry::{Git2DB, RepoId};
8use git2::Repository;
9use std::path::PathBuf;
10
11/// Trait for types that need to access repositories through the registry
12///
13/// This trait provides default implementations for common operations like
14/// getting the repository path and opening the repository.
15pub trait RepositoryAccessor {
16    /// Get the registry reference
17    fn registry(&self) -> &Git2DB;
18
19    /// Get the repository ID
20    fn repo_id(&self) -> &RepoId;
21
22    /// Get the repository worktree path
23    fn repo_path(&self) -> Git2DBResult<PathBuf> {
24        self.registry()
25            .get_worktree_path(self.repo_id())
26            .ok_or_else(|| {
27                Git2DBError::invalid_repository(
28                    self.repo_id().to_string(),
29                    "Repository not found in registry",
30                )
31            })
32    }
33
34    /// Open the git repository (async, uses spawn_blocking)
35    ///
36    /// Opens a fresh Repository instance. Note that git2::Repository is not
37    /// thread-safe, so each call creates a new instance.
38    ///
39    /// This method uses `spawn_blocking` to avoid blocking the async executor,
40    /// following the pattern from CLAUDE.md for libgit2 operations.
41    ///
42    /// Returns an `impl Future + Send` to explicitly ensure Send-safety.
43    fn open_repo(&self) -> impl std::future::Future<Output = Git2DBResult<Repository>> + Send + '_
44    where
45        Self: Sync,
46    {
47        async move {
48            let path = self.repo_path()?;
49
50            tokio::task::spawn_blocking(move || {
51                Repository::open(&path).map_err(|e| {
52                    Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
53                })
54            })
55            .await
56            .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
57        }
58    }
59}