Skip to main content

git2db/
manager.rs

1//! Git repository manager with thread-safe operations
2//!
3//! This module provides centralized Git management following hyprstream's patterns
4//! for thread safety and connection pooling.
5
6use anyhow::{bail, Result};
7use dashmap::DashMap;
8use git2::{build::RepoBuilder, Repository, Signature};
9use hyprstream_containedfs::contained_join;
10use once_cell::sync::OnceCell;
11use parking_lot::RwLock;
12use std::collections::HashMap;
13use std::path::{Path, PathBuf};
14use std::sync::Arc;
15use std::time::{Duration, Instant};
16use tokio::sync::Semaphore;
17use tracing::{debug, info, trace};
18
19/// Ensures libgit2's secondary subsystems (attr cache, ODB cache, config file
20/// locator, etc.) are fully initialized before any concurrent use begins.
21///
22/// git2-rs wraps `git_libgit2_init()` in a `std::sync::Once`, but internal
23/// libgit2 subsystems have their own deferred initialization that races when
24/// multiple threads call their first git2 operation concurrently. Calling a
25/// benign operation here — before the `spawn_blocking` thread pool fans out —
26/// serializes all secondary initialization.
27static LIBGIT2_INIT: OnceCell<()> = OnceCell::new();
28
29fn ensure_libgit2_initialized() {
30    LIBGIT2_INIT.get_or_init(|| {
31        // Triggers git_libgit2_init() + all secondary global init via git2-rs.
32        // open_default() reads system + global git config, initializing those caches.
33        let _ = git2::Config::open_default();
34    });
35}
36
37use crate::clone_options::{CloneOptions, SubmoduleMode};
38use crate::config::Git2DBConfig;
39use crate::errors::{Git2DBError, Git2DBResult};
40use crate::repository::{CacheStats, RepositoryCache};
41use crate::transport_registry::TransportRegistry;
42
43// Import storage driver system
44use crate::storage::DriverRegistry;
45
46/// Global GitManager instance - singleton pattern from hyprstream
47static GLOBAL_GIT_MANAGER: OnceCell<GitManager> = OnceCell::new();
48
49/// Cache entry for repository with TTL tracking
50struct CacheEntry {
51    cache: RepositoryCache,
52    last_accessed: parking_lot::Mutex<Instant>,
53}
54
55impl CacheEntry {
56    fn new(cache: RepositoryCache) -> Self {
57        Self {
58            cache,
59            last_accessed: parking_lot::Mutex::new(Instant::now()),
60        }
61    }
62
63    fn touch(&self) {
64        *self.last_accessed.lock() = Instant::now();
65    }
66
67    fn last_accessed(&self) -> Instant {
68        *self.last_accessed.lock()
69    }
70
71    fn is_expired(&self, ttl: Duration) -> bool {
72        self.last_accessed().elapsed() > ttl
73    }
74}
75
76/// Centralized Git manager with thread-safe operations
77pub struct GitManager {
78    config: Git2DBConfig,
79    /// Cached repositories with metadata (DashMap for lock-free concurrent access)
80    repo_cache: Arc<DashMap<PathBuf, CacheEntry>>,
81    /// Semaphore for limiting concurrent operations
82    operation_semaphore: Arc<Semaphore>,
83    /// Active operation tracking
84    active_operations: Arc<RwLock<HashMap<String, Instant>>>,
85    /// Thread-safe transport registry for URL schemes
86    transport_registry: Arc<TransportRegistry>,
87    /// Storage driver registry (Docker's graphdriver pattern)
88    driver_registry: Arc<DriverRegistry>,
89    /// Background cleanup thread handle (kept alive for the lifetime of GitManager).
90    ///
91    /// Using std::thread instead of tokio::spawn so the cleanup loop is not coupled
92    /// to any particular tokio runtime — tests create and destroy runtimes freely,
93    /// and a tokio task would be cancelled when its originating runtime shuts down.
94    #[allow(dead_code)]
95    cleanup_handle: Option<std::thread::JoinHandle<()>>,
96}
97
98impl GitManager {
99    /// Create a new GitManager with the given configuration
100    pub fn new(config: Git2DBConfig) -> Self {
101        // Eagerly initialize libgit2 secondary subsystems before any concurrent use.
102        ensure_libgit2_initialized();
103
104        let repo_cache = Arc::new(DashMap::new());
105
106        let cleanup_handle = if config.performance.auto_cleanup {
107            Some(Self::start_cleanup_task(
108                repo_cache.clone(),
109                Duration::from_secs(config.performance.repo_cache_ttl_secs),
110                config.performance.max_repo_cache,
111                Duration::from_secs(config.performance.cleanup_interval_secs),
112            ))
113        } else {
114            None
115        };
116
117        // Create driver registry (Docker pattern)
118        let driver_registry = Arc::new(DriverRegistry::new());
119
120        Self {
121            operation_semaphore: Arc::new(Semaphore::new(config.performance.max_concurrent_ops)),
122            config,
123            repo_cache,
124            active_operations: Arc::new(RwLock::new(HashMap::new())),
125            transport_registry: Arc::new(TransportRegistry::new()),
126            driver_registry,
127            cleanup_handle,
128        }
129    }
130
131    /// Start background cleanup thread for expired cache entries.
132    ///
133    /// Uses std::thread (not tokio::spawn) so the cleanup loop survives across
134    /// tokio runtime lifetimes — important for tests that create and destroy
135    /// runtimes while the global GitManager singleton stays alive.
136    fn start_cleanup_task(
137        cache: Arc<DashMap<PathBuf, CacheEntry>>,
138        ttl: Duration,
139        max_size: usize,
140        interval: Duration,
141    ) -> std::thread::JoinHandle<()> {
142        std::thread::spawn(move || {
143            loop {
144                std::thread::sleep(interval);
145
146                // Remove expired entries
147                let expired: Vec<PathBuf> = cache
148                    .iter()
149                    .filter_map(|entry| {
150                        if entry.is_expired(ttl) {
151                            Some(entry.key().clone())
152                        } else {
153                            None
154                        }
155                    })
156                    .collect();
157
158                for path in &expired {
159                    cache.remove(path);
160                }
161
162                if !expired.is_empty() {
163                    debug!(
164                        "Cleaned up {} expired repository cache entries",
165                        expired.len()
166                    );
167                }
168
169                // Evict oldest if over max size
170                while cache.len() > max_size {
171                    if let Some(oldest) = cache
172                        .iter()
173                        .min_by_key(|entry| entry.last_accessed())
174                        .map(|entry| entry.key().clone())
175                    {
176                        cache.remove(&oldest);
177                        debug!("Evicted repository from cache (size limit): {:?}", oldest);
178                    } else {
179                        break;
180                    }
181                }
182            }
183        })
184    }
185
186    /// Initialize the global GitManager with a custom configuration
187    ///
188    /// This must be called before the first call to `global()`.
189    /// Subsequent calls will return an error to avoid silent configuration changes.
190    ///
191    /// Returns Ok(()) if initialization succeeded, Err if it failed or already initialized.
192    ///
193    /// # Example
194    ///
195    /// ```rust,no_run
196    /// use git2db::config::Git2DBConfig;
197    /// use git2db::GitManager;
198    ///
199    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
200    /// let config = Git2DBConfig::default();
201    /// GitManager::init_with_config(config)?;
202    /// # Ok(())
203    /// # }
204    /// ```
205    pub fn init_with_config(config: Git2DBConfig) -> Result<(), crate::errors::Git2DBError> {
206        // Use OnceCell::set atomically — no pre-check needed.
207        // A pre-check would be a TOCTOU: two threads could both pass `get().is_some()`
208        // and both call GitManager::new(), racing on set(). The loser's cleanup
209        // thread would be orphaned (harmless — sleeps with a dropped cache Arc) but
210        // the double-init is still a programmer error, so we return an error.
211        GLOBAL_GIT_MANAGER
212            .set(GitManager::new(config))
213            .map(|_| ())
214            .map_err(|_| {
215                crate::errors::Git2DBError::configuration(
216                    "GitManager is already initialized. Cannot reinitialize.",
217                )
218            })
219    }
220
221    /// Get the global GitManager instance
222    ///
223    /// If not already initialized via `init_with_config()`, this will initialize
224    /// it with default configuration.
225    pub fn global() -> &'static GitManager {
226        GLOBAL_GIT_MANAGER.get_or_init(|| {
227            // Load config from environment and config files
228            tracing::info!("Initializing global GitManager...");
229            let config = match Git2DBConfig::load() {
230                Ok(cfg) => {
231                    tracing::info!("Successfully loaded git2db config from environment/file");
232                    cfg
233                }
234                Err(e) => {
235                    tracing::warn!("Failed to load git2db config, using defaults: {}", e);
236                    Git2DBConfig::default()
237                }
238            };
239            GitManager::new(config)
240        })
241    }
242
243    /// Get the configuration for this GitManager
244    pub fn config(&self) -> &Git2DBConfig {
245        &self.config
246    }
247
248    /// Create default clone options based on configuration
249    pub fn default_clone_options(&self) -> CloneOptions {
250        let mut builder = CloneOptions::builder();
251
252        // Set up shallow clone if configured
253        if self.config.repository.prefer_shallow {
254            builder = builder.shallow(true);
255            if let Some(depth) = self.config.repository.shallow_depth {
256                // Shallow depth is small (typically 1-100), safe to convert
257                builder = builder.depth(i32::try_from(depth).unwrap_or(i32::MAX));
258            }
259        }
260
261        // Set up proxy if configured
262        if let Some(proxy_url) = &self.config.network.proxy_url {
263            builder = builder.proxy_url(proxy_url.clone());
264        }
265
266        // Set up timeout (cap at u32::MAX seconds, ~136 years)
267        builder =
268            builder.timeout(u32::try_from(self.config.network.timeout_secs).unwrap_or(u32::MAX));
269
270        // Set up authentication
271        use crate::auth::AuthStrategy;
272        use crate::callback_config::{AuthMode, CallbackConfigBuilder, CertificateConfig};
273
274        let mut callback_builder = CallbackConfigBuilder::new();
275
276        // Add token authentication if configured. The token is only attached
277        // to the default clone path when it is host-scoped (access_token_host
278        // is set): a process-global, host-unscoped token must not be offered
279        // to a caller-selected remote, since that would exfiltrate the
280        // operator's trusted-forge credential (issue #1429 Sol P1).
281        let token_from_config = self.config.network.access_token.clone();
282        let token_from_env = std::env::var("GIT2DB_NETWORK__ACCESS_TOKEN").ok();
283        let token_host = self.config.network.access_token_host.clone();
284        let token = token_from_config.or(token_from_env);
285
286        match (token, &token_host) {
287            (Some(token_value), Some(host)) => {
288                tracing::info!(
289                    "Using host-scoped token authentication bound to {} (token starts with: {})",
290                    host,
291                    &token_value.chars().take(10).collect::<String>()
292                );
293                callback_builder = callback_builder.auth(AuthStrategy::Token {
294                    token: token_value,
295                    host: Some(host.clone()),
296                });
297            }
298            (Some(_token_value), None) => {
299                tracing::warn!(
300                    "Access token configured without access_token_host — not attaching to \
301                     default clone path to prevent credential exfiltration to caller-selected \
302                     remotes. Set network.access_token_host to scope the token."
303                );
304            }
305            (None, _) => {
306                tracing::debug!("No access token configured");
307            }
308        }
309
310        // Ambient credential sources — the SSH agent (`ssh_key_from_agent`),
311        // the git credential helper, and `~/.gitconfig` — are only consulted
312        // when the operator explicitly enables `use_credential_helper`. By
313        // default (issue #1429) the clone path is strict certs + ExplicitOnly
314        // auth: these strategies are added only here, behind the opt-in, and
315        // paired with AllowAmbient so ExplicitOnly does not refuse them at
316        // resolution time. The default secure path uses only the explicit
317        // token above (or anonymous access for public remotes).
318        if self.config.network.use_credential_helper {
319            callback_builder = callback_builder
320                .auth(AuthStrategy::SshAgent {
321                    username: Some("git".to_owned()),
322                })
323                .auth(AuthStrategy::Default)
324                .auth_mode(AuthMode::AllowAmbient);
325        }
326
327        // Strict certificate validation is the builder default; set it
328        // explicitly for clarity. libgit2 validates against the system trust
329        // store and rejects on cert failure.
330        callback_builder = callback_builder.certificates(CertificateConfig::Strict);
331
332        builder = builder.callback_config(callback_builder.build());
333
334        builder.build()
335    }
336
337    /// Check if the global GitManager has been initialized
338    pub fn is_initialized() -> bool {
339        GLOBAL_GIT_MANAGER.get().is_some()
340    }
341
342    /// Validate path for security (prevents directory traversal)
343    pub fn validate_path(&self, base_dir: &Path, path: &Path) -> Result<PathBuf> {
344        if path.is_absolute() {
345            // If absolute, verify it's within base_dir
346            if !path.starts_with(base_dir) {
347                bail!("Repository path outside allowed directory: {:?}", path);
348            }
349            Ok(path.to_path_buf())
350        } else {
351            // If relative, safely join with base_dir
352            contained_join(base_dir, &path.to_string_lossy())
353                .map_err(|e| anyhow::anyhow!("Path traversal attempt detected: {}", e))
354        }
355    }
356
357    /// Get a repository cache handle with intelligent caching
358    ///
359    /// Returns a RepositoryCache that tracks metadata and provides fresh Repository
360    /// instances on each .open() call (for thread safety with git2).
361    pub fn get_repository<P: AsRef<Path>>(&self, path: P) -> Git2DBResult<RepositoryCache> {
362        let path_ref = path.as_ref();
363        let path = path_ref.canonicalize().map_err(|e| {
364            Git2DBError::invalid_path(path_ref, format!("Failed to canonicalize: {e}"))
365        })?;
366
367        // Check cache first (lock-free read with DashMap)
368        if let Some(entry) = self.repo_cache.get(&path) {
369            if !entry.is_expired(Duration::from_secs(
370                self.config.performance.repo_cache_ttl_secs,
371            )) {
372                entry.touch();
373                trace!("Repository cache hit for {:?}", path);
374                return Ok(entry.cache.clone());
375            } else {
376                // Remove expired entry
377                drop(entry); // Release the ref before removing
378                self.repo_cache.remove(&path);
379                debug!("Removed expired repository cache entry for {:?}", path);
380            }
381        }
382
383        // Cache miss - open repository
384        trace!("Repository cache miss for {:?}", path);
385        let repository = Repository::open(&path).map_err(|e| {
386            Git2DBError::repository(&path, format!("Failed to open repository: {e}"))
387        })?;
388
389        let cache = RepositoryCache::new(repository, path.clone());
390        let entry = CacheEntry::new(cache.clone());
391
392        // Evict oldest if cache is full
393        if self.repo_cache.len() >= self.config.performance.max_repo_cache {
394            self.evict_oldest();
395        }
396
397        self.repo_cache.insert(path.clone(), entry);
398        debug!("Added repository to cache: {:?}", path);
399
400        Ok(cache)
401    }
402
403    /// Evict the oldest cache entry
404    fn evict_oldest(&self) {
405        if let Some(oldest) = self
406            .repo_cache
407            .iter()
408            .min_by_key(|entry| entry.last_accessed())
409            .map(|entry| entry.key().clone())
410        {
411            self.repo_cache.remove(&oldest);
412            debug!("Evicted oldest repository from cache: {:?}", oldest);
413        }
414    }
415
416    /// Get repository cache statistics
417    pub fn cache_stats(&self) -> CacheStats {
418        let mut total_accesses = 0;
419        let mut oldest_created = None;
420        let mut newest_created = None;
421        let mut oldest_accessed = None;
422        let mut newest_accessed = None;
423
424        for entry in self.repo_cache.iter() {
425            total_accesses += entry.cache.access_count();
426            let created = entry.cache.created_at();
427            let accessed = entry.last_accessed();
428
429            oldest_created = Some(oldest_created.map_or(created, |old: Instant| old.min(created)));
430            newest_created = Some(newest_created.map_or(created, |new: Instant| new.max(created)));
431            oldest_accessed =
432                Some(oldest_accessed.map_or(accessed, |old: Instant| old.min(accessed)));
433            newest_accessed =
434                Some(newest_accessed.map_or(accessed, |new: Instant| new.max(accessed)));
435        }
436
437        CacheStats {
438            total_entries: self.repo_cache.len(),
439            total_accesses,
440            oldest_created: oldest_created.unwrap_or_else(Instant::now),
441            newest_created: newest_created.unwrap_or_else(Instant::now),
442            oldest_accessed: oldest_accessed.unwrap_or_else(Instant::now),
443            newest_accessed: newest_accessed.unwrap_or_else(Instant::now),
444        }
445    }
446
447    /// Clear the entire repository cache
448    pub fn clear_cache(&self) {
449        let count = self.repo_cache.len();
450        self.repo_cache.clear();
451        debug!("Cleared {} repository cache entries", count);
452    }
453
454    /// Manually trigger cache cleanup (remove expired entries)
455    pub fn cleanup_cache(&self) {
456        let ttl = Duration::from_secs(self.config.performance.repo_cache_ttl_secs);
457        let expired: Vec<PathBuf> = self
458            .repo_cache
459            .iter()
460            .filter_map(|entry| {
461                if entry.is_expired(ttl) {
462                    Some(entry.key().clone())
463                } else {
464                    None
465                }
466            })
467            .collect();
468
469        for path in &expired {
470            self.repo_cache.remove(path);
471        }
472
473        debug!(
474            "Manually cleaned up {} expired cache entries",
475            expired.len()
476        );
477    }
478
479    /// Clone a repository with Send-safe async support
480    ///
481    /// Uses spawn_blocking internally to handle git2 operations safely.
482    ///
483    /// # Example
484    ///
485    /// ```rust,ignore
486    /// use git2db::clone_options::CloneOptions;
487    /// use git2db::callback_config::{CallbackConfigBuilder, ProgressConfig};
488    /// use git2db::auth::AuthStrategy;
489    ///
490    /// let options = CloneOptions::builder()
491    ///     .callback_config(
492    ///         CallbackConfigBuilder::new()
493    ///             .auth(AuthStrategy::SshAgent { username: Some("git".to_owned()) })
494    ///             .progress(ProgressConfig::Stdout)
495    ///             .build()
496    ///     )
497    ///     .shallow(true)
498    ///     .depth(1)
499    ///     .build();
500    ///
501    /// let repo = manager.clone_repository(url, path, Some(options)).await?;
502    /// ```
503    pub async fn clone_repository(
504        &self,
505        url: &str,
506        target_path: &Path,
507        options: Option<CloneOptions>,
508    ) -> Git2DBResult<Repository> {
509        use tokio::task::spawn_blocking;
510
511        // Convert inputs to owned types for spawn_blocking
512        let url = url.to_owned();
513        let target_path = target_path.to_path_buf();
514        let mut options = options.unwrap_or_else(|| self.default_clone_options());
515
516        // Refuse to even start the network operation if an `Untrusted` clone
517        // is misconfigured with ambient auth or an unscoped token — see
518        // `CloneOptions::validate_trust` (issue #1430).
519        options.validate_trust()?;
520
521        // libgit2's local transport rejects shallow fetch over `file://` —
522        // disable it here so callers that default to prefer_shallow (the
523        // global config default) don't get an opaque failure when cloning a
524        // local repository (e.g. RPC registration in local-file test
525        // harnesses, or same-host repo mirroring).
526        if options.shallow && url.starts_with("file://") {
527            debug!(
528                "Disabling shallow clone for local file:// transport: {}",
529                url
530            );
531            options.shallow = false;
532            options.depth = None;
533        }
534
535        // Acquire operation permit
536        let _permit = self
537            .operation_semaphore
538            .acquire()
539            .await
540            .map_err(|e| Git2DBError::internal(format!("Failed to acquire semaphore: {e}")))?;
541
542        // Track operation
543        let operation_id = format!("clone_{}", target_path.display());
544        {
545            let mut ops = self.active_operations.write();
546            ops.insert(operation_id.clone(), Instant::now());
547        }
548
549        info!("Cloning repository from {} to {:?}", url, target_path);
550
551        // Validate path - use absolute paths directly, validate relative paths
552        let validated_path = if target_path.is_absolute() {
553            // Already absolute - use directly after basic validation
554            target_path.clone()
555        } else {
556            // Relative path - join with current dir and validate
557            let current_dir = std::env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
558            contained_join(&current_dir, &target_path.to_string_lossy()).map_err(|e| {
559                Git2DBError::invalid_path(&target_path, format!("Path validation failed: {e}"))
560            })?
561        };
562
563        // Create parent directory if needed
564        if let Some(parent) = validated_path.parent() {
565            tokio::fs::create_dir_all(parent).await.map_err(|e| {
566                Git2DBError::repository(
567                    &validated_path,
568                    format!("Failed to create parent directory: {e}"),
569                )
570            })?;
571        }
572
573        // Perform the clone in a blocking task
574        let repo = spawn_blocking(move || -> Git2DBResult<Repository> {
575            // Convert to git2 options inside spawn_blocking
576            let mut git2_options = options.to_git2_options();
577
578            // Configure builder with options
579            let mut builder = RepoBuilder::new();
580
581            // Apply fetch options
582            builder.fetch_options(git2_options.create_fetch_options()?);
583
584            // Apply checkout options
585            builder.with_checkout(git2_options.create_checkout_builder());
586
587            // Apply branch if specified
588            if let Some(branch) = &git2_options.branch {
589                builder.branch(branch);
590            }
591
592            debug!("Cloning from URL: {}", url);
593
594            // Perform clone
595            let repo = builder.clone(&url, &validated_path).map_err(|e| {
596                Git2DBError::repository(&validated_path, format!("Failed to clone repository: {e}"))
597            })?;
598
599            info!("Successfully cloned repository to {:?}", validated_path);
600
601            // Submodule handling. `submodule_mode` here is the value already
602            // resolved by `CloneOptions::effective_submodule_mode` — the
603            // `CloneTrust::Untrusted` clamp has already forced it to
604            // `Disabled` for an untrusted clone by the time it reaches here,
605            // so this is the ONLY place a fresh clone's submodules are
606            // touched. A `.gitmodules` submodule URL is taken verbatim from
607            // the just-cloned repository's own content, so initializing it
608            // under `Disabled` would fetch from an attacker-chosen remote for
609            // an untrusted repo (issue #1430).
610            if git2_options.submodule_mode == SubmoduleMode::Enabled {
611                init_submodules(&repo)?;
612            } else {
613                debug!(
614                    "Skipping submodule initialization for {:?} (SubmoduleMode::Disabled)",
615                    validated_path
616                );
617            }
618
619            Ok(repo)
620        })
621        .await
622        .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))??;
623
624        // Clean up operation tracking
625        {
626            let mut ops = self.active_operations.write();
627            ops.remove(&operation_id);
628        }
629
630        Ok(repo)
631    }
632
633    /// Create a signature for commits
634    pub fn create_signature(
635        &self,
636        name: Option<&str>,
637        email: Option<&str>,
638    ) -> Git2DBResult<Signature<'static>> {
639        let sig_name = name.unwrap_or(&self.config.signature.name);
640        let sig_email = email.unwrap_or(&self.config.signature.email);
641
642        Signature::now(sig_name, sig_email)
643            .map_err(|e| Git2DBError::internal(format!("Failed to create signature: {e}")))
644    }
645
646    /// Remove a worktree with cleanup
647    pub fn remove_worktree(
648        &self,
649        base_repo_path: &Path,
650        worktree_name: &str,
651        base_dir: Option<&Path>,
652    ) -> Git2DBResult<()> {
653        let base_repo_path = if let Some(base) = base_dir {
654            self.validate_path(base, base_repo_path)
655                .map_err(|e| Git2DBError::internal(format!("Invalid base repo path: {e}")))?
656        } else {
657            base_repo_path.to_path_buf()
658        };
659
660        debug!("Removing worktree '{}'", worktree_name);
661
662        let repo_cache = self.get_repository(&base_repo_path)?;
663        let repo = repo_cache.open()?;
664
665        // Find and prune worktree
666        let wt = repo.find_worktree(worktree_name).map_err(|e| {
667            Git2DBError::repository(&base_repo_path, format!("Failed to find worktree: {e}"))
668        })?;
669
670        // Configure prune options:
671        // - valid(true): Allow pruning even if worktree is valid (not orphaned)
672        // - working_tree(true): Also remove the working directory contents
673        let mut opts = git2::WorktreePruneOptions::new();
674        opts.valid(true);
675        opts.working_tree(true);
676
677        wt.prune(Some(&mut opts)).map_err(|e| {
678            Git2DBError::repository(&base_repo_path, format!("Failed to prune worktree: {e}"))
679        })?;
680
681        info!("Successfully removed worktree '{}'", worktree_name);
682        Ok(())
683    }
684
685    /// List all worktrees for a repository
686    pub fn list_worktrees(&self, repo_path: &Path) -> Git2DBResult<Vec<String>> {
687        let repo_cache = self.get_repository(repo_path)?;
688        let repo = repo_cache.open()?;
689
690        let worktrees = repo.worktrees().map_err(|e| {
691            Git2DBError::repository(repo_path, format!("Failed to list worktrees: {e}"))
692        })?;
693
694        Ok(worktrees
695            .into_iter()
696            .flatten()
697            .map(std::borrow::ToOwned::to_owned)
698            .collect())
699    }
700
701    /// Get statistics about cached paths
702    /// Get active operations
703    pub fn active_operations(&self) -> Vec<(String, Duration)> {
704        let ops = self.active_operations.read();
705        let now = Instant::now();
706
707        ops.iter()
708            .map(|(id, start)| (id.clone(), now.duration_since(*start)))
709            .collect()
710    }
711
712    /// Register a custom transport for a URL scheme
713    ///
714    /// This allows integration with custom git transports like gittorrent://,
715    /// ipfs://, s3://, or any other custom protocol using a thread-safe registry.
716    ///
717    /// # Example
718    ///
719    /// ```no_run
720    /// use git2db::GitManager;
721    /// # use std::sync::Arc;
722    /// # struct MyTransportFactory;
723    /// # impl git2db::TransportFactory for MyTransportFactory {
724    /// #     fn create_transport(&self, url: &str) -> anyhow::Result<Box<dyn git2::transport::SmartSubtransport>> {
725    /// #         unimplemented!()
726    /// #     }
727    /// #     fn supports_url(&self, url: &str) -> bool { url.starts_with("custom://") }
728    /// # }
729    ///
730    /// let manager = GitManager::new(Default::default());
731    /// let factory = Arc::new(MyTransportFactory);
732    /// manager.register_transport("custom", factory).unwrap();
733    /// ```
734    pub fn register_transport(
735        &self,
736        scheme: &str,
737        factory: Arc<dyn crate::transport::TransportFactory>,
738    ) -> Result<(), Git2DBError> {
739        let scheme = scheme.to_owned();
740        self.transport_registry
741            .register_transport(scheme.clone(), factory.clone())?;
742        info!(
743            "Successfully registered custom transport for scheme: {}",
744            scheme
745        );
746        Ok(())
747    }
748
749    /// Unregister a custom transport
750    ///
751    /// Returns the factory if it was registered, None otherwise.
752    /// Uses reference counting for thread-safe cleanup.
753    pub fn unregister_transport(
754        &self,
755        scheme: &str,
756    ) -> Option<Arc<dyn crate::transport::TransportFactory>> {
757        let result = self.transport_registry.unregister_transport(scheme);
758        if result.is_some() {
759            info!(
760                "Successfully unregistered custom transport for scheme: {}",
761                scheme
762            );
763        }
764        result
765    }
766
767    /// Check if a custom transport is registered for a given scheme
768    pub fn has_transport(&self, scheme: &str) -> bool {
769        self.transport_registry.has_transport(scheme)
770    }
771
772    /// Get a list of all registered transport schemes
773    pub fn registered_transports(&self) -> Vec<String> {
774        self.transport_registry.registered_schemes()
775    }
776
777    /// Get transport registry statistics
778    pub fn transport_stats(&self) -> crate::transport_registry::RegistryStats {
779        self.transport_registry.stats()
780    }
781
782    // ===== Worktree Management =====
783
784    /// Get the driver registry
785    pub fn driver_registry(&self) -> &Arc<DriverRegistry> {
786        &self.driver_registry
787    }
788}
789
790/// Initialize and update every submodule declared by `repo`'s `.gitmodules`.
791///
792/// Equivalent to `git submodule init && git submodule update`. Mirrors
793/// `Git2DB::init_submodules` (registry.rs), which performs the same operation
794/// for the registry's own tracked-repos-as-submodules; this free function is
795/// the equivalent for an arbitrary freshly-cloned repository.
796///
797/// Callers MUST gate this behind [`crate::clone_options::SubmoduleMode`] —
798/// a submodule's URL is taken verbatim from the repository's own
799/// `.gitmodules` content, so calling this against an untrusted repository
800/// means fetching from an attacker-chosen remote. See issue #1430.
801fn init_submodules(repo: &Repository) -> Git2DBResult<()> {
802    let submodules = repo
803        .submodules()
804        .map_err(|e| Git2DBError::submodule("*", format!("Failed to list submodules: {e}")))?;
805
806    if submodules.is_empty() {
807        debug!("No submodules found in cloned repository");
808        return Ok(());
809    }
810
811    info!("Initializing {} submodule(s)", submodules.len());
812
813    for mut submodule in submodules {
814        let name = submodule.name().unwrap_or("unknown").to_owned();
815
816        debug!("Initializing submodule: {}", name);
817        submodule
818            .init(false)
819            .map_err(|e| Git2DBError::submodule(&name, format!("Failed to init: {e}")))?;
820
821        let mut update_opts = git2::SubmoduleUpdateOptions::new();
822        submodule
823            .update(true, Some(&mut update_opts))
824            .map_err(|e| Git2DBError::submodule(&name, format!("Failed to update: {e}")))?;
825
826        info!("Initialized submodule: {}", name);
827    }
828
829    Ok(())
830}
831
832#[cfg(test)]
833mod tests {
834    use super::*;
835    use tempfile::TempDir;
836
837    /// Helper to create a test config without async cleanup
838    fn test_config() -> Git2DBConfig {
839        let mut config = Git2DBConfig::default();
840        config.performance.auto_cleanup = false; // Disable async task spawning
841        config
842    }
843
844    #[test]
845    fn test_global_manager_singleton() {
846        // Initialize with test config first to avoid Tokio requirement
847        let _ = GitManager::init_with_config(test_config());
848
849        let manager1 = GitManager::global();
850        let manager2 = GitManager::global();
851
852        // Should be the same instance
853        assert!(std::ptr::eq(manager1, manager2));
854    }
855
856    #[test]
857    fn test_cache_functionality() -> crate::Git2DBResult<()> {
858        let config = test_config();
859        let manager = GitManager::new(config);
860
861        // Initially empty
862        let stats = manager.cache_stats();
863        assert_eq!(stats.total_entries, 0);
864
865        // Create a temp dir with an actual git repository
866        let temp_dir = TempDir::new()?;
867        let test_path = temp_dir.path();
868        git2::Repository::init(test_path)?;
869        let cache1 = manager.get_repository(test_path)?;
870        let cache2 = manager.get_repository(test_path)?;
871
872        // Should have one entry
873        let stats = manager.cache_stats();
874        assert_eq!(stats.total_entries, 1);
875
876        // Should be the same cache entry (compare by path)
877        assert_eq!(cache1.path(), cache2.path());
878
879        // Cleanup
880        manager.clear_cache();
881        Ok(())
882    }
883
884    #[test]
885    fn test_path_validation() -> crate::Git2DBResult<()> {
886        let config = test_config();
887        let manager = GitManager::new(config);
888
889        // Use an actual temp directory for base_dir
890        let temp_dir = TempDir::new()?;
891        let base_dir = temp_dir.path();
892
893        // Valid relative path
894        let result = manager.validate_path(base_dir, Path::new("valid/file.txt"));
895        assert!(result.is_ok());
896
897        // Absolute path within base
898        let absolute_path = base_dir.join("file.txt");
899        let result = manager.validate_path(base_dir, &absolute_path);
900        assert!(result.is_ok());
901
902        // Absolute path outside base should fail
903        let result = manager.validate_path(base_dir, Path::new("/etc/passwd"));
904        assert!(result.is_err());
905        Ok(())
906    }
907
908    #[tokio::test]
909    async fn test_concurrent_operations() -> crate::Git2DBResult<()> {
910        let config = test_config();
911        let manager = Arc::new(GitManager::new(config));
912
913        let mut handles = Vec::new();
914        let mut temp_dirs = Vec::new();
915
916        for _ in 0..5 {
917            let dir = TempDir::new()?;
918            git2::Repository::init(dir.path())?;
919            temp_dirs.push(dir);
920        }
921
922        // Create concurrent repository operations
923        // Iterate by reference to keep temp_dirs alive
924        for temp_dir in &temp_dirs {
925            let manager_clone = manager.clone();
926            let path = temp_dir.path().to_path_buf();
927
928            let handle = tokio::spawn(async move {
929                let result = manager_clone.get_repository(&path);
930                result.map(|_| ())
931            });
932            handles.push(handle);
933        }
934
935        // All should succeed without conflicts
936        for handle in handles {
937            let result = handle
938                .await
939                .map_err(|e| crate::Git2DBError::internal(format!("Task join error: {e}")))?;
940            assert!(result.is_ok());
941        }
942
943        // temp_dirs dropped here, after all operations complete
944        Ok(())
945    }
946
947    #[test]
948    fn test_cache_operations() -> crate::Git2DBResult<()> {
949        let manager = GitManager::new(test_config());
950
951        // Initially empty
952        let stats = manager.cache_stats();
953        assert_eq!(stats.total_entries, 0);
954
955        // Access some paths (this would happen through get_repository in practice)
956        let temp_dir = TempDir::new()?;
957        Repository::init(temp_dir.path())?;
958        manager.get_repository(temp_dir.path())?;
959
960        // Cache should have one entry
961        let stats = manager.cache_stats();
962        assert_eq!(stats.total_entries, 1);
963
964        // Clear cache
965        manager.clear_cache();
966        let stats = manager.cache_stats();
967        assert_eq!(stats.total_entries, 0);
968        Ok(())
969    }
970
971    #[test]
972    fn test_signature_creation() -> crate::Git2DBResult<()> {
973        let manager = GitManager::new(test_config());
974
975        // Default signature
976        let sig = manager.create_signature(None, None)?;
977        assert_eq!(
978            sig.name()
979                .ok_or_else(|| crate::Git2DBError::internal("no name"))?,
980            "git2db"
981        );
982        assert_eq!(
983            sig.email()
984                .ok_or_else(|| crate::Git2DBError::internal("no email"))?,
985            "git2db@local"
986        );
987
988        // Custom signature
989        let custom_sig = manager.create_signature(Some("Test User"), Some("test@example.com"))?;
990        assert_eq!(
991            custom_sig
992                .name()
993                .ok_or_else(|| crate::Git2DBError::internal("no name"))?,
994            "Test User"
995        );
996        assert_eq!(
997            custom_sig
998                .email()
999                .ok_or_else(|| crate::Git2DBError::internal("no email"))?,
1000            "test@example.com"
1001        );
1002        Ok(())
1003    }
1004}