Skip to main content

git2db/storage/
driver.rs

1//! Core driver trait and types
2
3use crate::errors::{Git2DBError, Git2DBResult};
4use crate::references::GitRef;
5use crate::references::IntoGitRef;
6use crate::repository_handle::RepositoryStatus;
7use async_trait::async_trait;
8use git2::{Oid, Signature};
9use inventory;
10use once_cell::sync::OnceCell;
11use parking_lot::Mutex;
12use std::fmt;
13use std::future::Future;
14use std::path::{Path, PathBuf};
15use std::pin::Pin;
16use std::sync::Arc;
17
18/// Storage driver selection
19#[derive(Debug, Clone, PartialEq, Eq)]
20pub enum StorageDriver {
21    Overlay2,
22    Reflink,
23    Vfs,
24}
25
26impl fmt::Display for StorageDriver {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        match self {
29            Self::Overlay2 => write!(f, "overlay2"),
30            Self::Reflink => write!(f, "reflink"),
31            Self::Vfs => write!(f, "vfs"),
32        }
33    }
34}
35
36impl std::str::FromStr for StorageDriver {
37    type Err = DriverError;
38
39    fn from_str(s: &str) -> Result<Self, Self::Err> {
40        match s.to_lowercase().as_str() {
41            "overlay2" | "overlayfs" => Ok(Self::Overlay2),
42            "reflink" => Ok(Self::Reflink),
43            "vfs" | "none" => Ok(Self::Vfs),
44            _ => Err(DriverError::UnknownDriver(s.to_owned())),
45        }
46    }
47}
48
49/// Options for creating a worktree with a driver
50pub struct DriverOpts {
51    /// Base repository path (lower layer for CoW drivers)
52    pub base_repo: PathBuf,
53
54    /// Target worktree path (where to mount/create)
55    pub worktree_path: PathBuf,
56
57    /// Git ref specification (branch, commit SHA, tag, HEAD~3, etc.)
58    /// Examples: "main", "a1b2c3d4", "v1.0.0", "HEAD~3", "origin/main"
59    pub ref_spec: String,
60
61    /// Optional progress reporter for smudge/checkout progress
62    pub progress: Option<Arc<dyn crate::callback_config::ProgressReporter>>,
63
64    /// Optional pathspec filter for selective checkout.
65    ///
66    /// When set, only files matching these path prefixes are materialized in the
67    /// worktree. Excluded entries get the `SKIP_WORKTREE` index bit so they won't
68    /// be re-materialized by subsequent `checkout_head()` calls.
69    ///
70    /// Example: `vec!["backends/cuda130/".into(), "manifest.toml".into()]`
71    pub checkout_paths: Option<Vec<String>>,
72}
73
74impl Clone for DriverOpts {
75    fn clone(&self) -> Self {
76        Self {
77            base_repo: self.base_repo.clone(),
78            worktree_path: self.worktree_path.clone(),
79            ref_spec: self.ref_spec.clone(),
80            progress: self.progress.clone(),
81            checkout_paths: self.checkout_paths.clone(),
82        }
83    }
84}
85
86impl fmt::Debug for DriverOpts {
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        f.debug_struct("DriverOpts")
89            .field("base_repo", &self.base_repo)
90            .field("worktree_path", &self.worktree_path)
91            .field("ref_spec", &self.ref_spec)
92            .field("progress", &self.progress.as_ref().map(|_| "<reporter>"))
93            .field("checkout_paths", &self.checkout_paths)
94            .finish()
95    }
96}
97
98/// Driver-specific errors
99#[derive(Debug, thiserror::Error)]
100pub enum DriverError {
101    #[error("Unknown driver: {0}")]
102    UnknownDriver(String),
103
104    #[error("Driver not available: {0}")]
105    NotAvailable(String),
106
107    #[error("Driver operation failed: {0}")]
108    OperationFailed(String),
109
110    #[error("Git2DB error: {0}")]
111    Git2DB(#[from] Git2DBError),
112}
113
114/// Driver factory for plugin discovery
115///
116/// This struct represents a factory for creating storage drivers that can be
117/// dynamically discovered at runtime using the inventory crate. It separates
118/// const-compatible registration from runtime driver creation.
119#[derive(Clone)]
120pub struct DriverFactory {
121    /// Driver name for identification
122    name: &'static str,
123
124    /// Factory function to create the driver (returns Box for const compatibility)
125    factory: fn() -> Box<dyn Driver>,
126}
127
128impl DriverFactory {
129    /// Create a new driver factory with const-compatible registration
130    pub const fn new(name: &'static str, factory: fn() -> Box<dyn Driver>) -> Self {
131        Self { name, factory }
132    }
133
134    /// Get the driver instance (wrapped in Arc for sharing)
135    pub fn get_driver(&self) -> Arc<dyn Driver> {
136        // Create Box<dyn Driver> and then convert to Arc<dyn Driver>
137        // The Box can be safely coerced to the trait object
138        let boxed: Box<dyn Driver> = (self.factory)();
139        Arc::from(boxed)
140    }
141
142    /// Get the driver name
143    pub fn name(&self) -> &'static str {
144        self.name
145    }
146}
147
148// Inventory registration for driver factories
149inventory::collect!(DriverFactory);
150
151/// Storage driver trait (Docker's graphdriver interface)
152///
153/// All storage drivers must implement this trait to provide worktree
154/// creation with optional storage optimization.
155#[async_trait]
156pub trait Driver: Send + Sync {
157    /// Get driver name (e.g., "overlay2", "vfs")
158    fn name(&self) -> &'static str;
159
160    /// Check if this driver is available on the current system
161    fn is_available(&self) -> bool;
162
163    /// Create a worktree using this driver
164    ///
165    /// This creates a git worktree, potentially with storage optimization
166    /// layers underneath (overlayfs, reflinks, etc.).
167    async fn create_worktree(&self, opts: &DriverOpts) -> Git2DBResult<WorktreeHandle>;
168
169    /// Get all worktrees managed by this driver for the given repository
170    ///
171    /// Returns all existing worktrees for this repository that were created
172    /// by this storage driver, maintaining storage optimization context.
173    async fn get_worktrees(&self, base_repo: &Path) -> Git2DBResult<Vec<WorktreeHandle>>;
174
175    /// Get specific worktree by branch name (if it exists)
176    ///
177    /// Returns the worktree handle if it exists and is managed by this driver,
178    /// or None if the worktree doesn't exist or isn't managed by this driver.
179    async fn get_worktree(
180        &self,
181        base_repo: &Path,
182        branch: &str,
183    ) -> Git2DBResult<Option<WorktreeHandle>>;
184}
185
186/// Async cleanup function type
187pub type AsyncCleanupFn =
188    Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = Git2DBResult<()>> + Send>> + Send>;
189
190/// Handle to a created worktree
191///
192/// Provides access to the worktree and handles cleanup on drop.
193/// Implements git repository operations and worktree management.
194pub struct WorktreeHandle {
195    /// Path to the worktree
196    pub path: PathBuf,
197
198    /// Driver that created this worktree
199    pub driver_name: String,
200
201    /// Async cleanup function, wrapped in Arc<Mutex> for Sync
202    cleanup: Option<Arc<Mutex<Option<AsyncCleanupFn>>>>,
203
204    /// Cached repository instance (to avoid reopening)
205    repo: Option<git2::Repository>,
206
207    /// Lazy-initialized contained filesystem for this worktree
208    contained_fs: OnceCell<Arc<dyn hyprstream_containedfs::ContainedFs>>,
209}
210
211impl WorktreeHandle {
212    /// Create a new worktree handle
213    pub fn new(path: PathBuf, driver_name: String) -> Self {
214        Self {
215            path,
216            driver_name,
217            cleanup: None,
218            repo: None,
219            contained_fs: OnceCell::new(),
220        }
221    }
222
223    /// Create with async cleanup function
224    pub fn with_cleanup<F, Fut>(path: PathBuf, driver_name: String, cleanup: F) -> Self
225    where
226        F: FnOnce() -> Fut + Send + 'static,
227        Fut: Future<Output = Git2DBResult<()>> + Send + 'static,
228    {
229        let cleanup_fn: AsyncCleanupFn = Box::new(move || Box::pin(cleanup()));
230        Self {
231            path,
232            driver_name,
233            cleanup: Some(Arc::new(Mutex::new(Some(cleanup_fn)))),
234            repo: None,
235            contained_fs: OnceCell::new(),
236        }
237    }
238
239    /// Open the worktree as a git repository
240    pub fn open_repository(&self) -> Git2DBResult<git2::Repository> {
241        git2::Repository::open(&self.path).map_err(|e| {
242            Git2DBError::internal(format!(
243                "Failed to open worktree at {}: {}",
244                self.path.display(),
245                e
246            ))
247        })
248    }
249
250    /// Get the driver name
251    pub fn driver_name(&self) -> &str {
252        &self.driver_name
253    }
254
255    /// Get the worktree path
256    pub fn path(&self) -> &Path {
257        &self.path
258    }
259
260    /// Get a contained filesystem for this worktree (lazy-initialized).
261    ///
262    /// Returns a kernel-enforced (Linux) or canonicalize-based (other) filesystem
263    /// rooted at this worktree's path.
264    pub fn fs(
265        &self,
266    ) -> Result<&Arc<dyn hyprstream_containedfs::ContainedFs>, hyprstream_containedfs::FsError>
267    {
268        self.contained_fs
269            .get_or_try_init(|| hyprstream_containedfs::open(&self.path))
270    }
271
272    /// Get the git repository with lazy loading and caching
273    pub fn get_repository(&mut self) -> Git2DBResult<&mut git2::Repository> {
274        if self.repo.is_none() {
275            self.repo = Some(self.open_repository()?);
276        }
277        self.repo
278            .as_mut()
279            .ok_or_else(|| Git2DBError::internal("Repository not initialized"))
280    }
281
282    /// Get the current HEAD reference
283    pub fn head(&mut self) -> Git2DBResult<git2::Reference<'_>> {
284        let repo = self.get_repository()?;
285        let head = repo.head()?;
286        Ok(head)
287    }
288
289    /// Get the current commit
290    pub fn head_commit(&mut self) -> Git2DBResult<git2::Commit<'_>> {
291        let repo = self.get_repository()?;
292        let head = repo.head()?;
293        let commit = head.peel_to_commit()?;
294        Ok(commit)
295    }
296
297    /// Check if the worktree is valid and accessible
298    pub fn is_valid(&self) -> bool {
299        self.path.exists() && self.path.join(".git").exists() && self.open_repository().is_ok()
300    }
301
302    /// Check if the worktree has uncommitted changes
303    pub fn is_dirty(&mut self) -> Git2DBResult<bool> {
304        let repo = self.get_repository()?;
305        let mut opts = git2::StatusOptions::new();
306        // Show working directory and staging area
307        opts.include_untracked(true);
308        opts.include_unmodified(true);
309        let statuses = repo.statuses(Some(&mut opts))?;
310        Ok(!statuses.is_empty())
311    }
312
313    /// Get basic worktree metadata
314    pub fn metadata(&mut self) -> WorktreeMetadata {
315        WorktreeMetadata {
316            path: self.path.clone(),
317            driver_name: self.driver_name.clone(),
318            is_valid: self.is_valid(),
319            is_dirty: self.is_dirty().unwrap_or(false),
320            created_at: chrono::Utc::now(), // This should be actual creation time
321        }
322    }
323
324    /// Async cleanup method
325    pub async fn cleanup(&mut self) -> Git2DBResult<()> {
326        if let Some(cleanup_arc) = self.cleanup.take() {
327            let cleanup_fn = cleanup_arc.lock().take();
328
329            if let Some(cleanup_fn) = cleanup_fn {
330                cleanup_fn().await?;
331            }
332        }
333        Ok(())
334    }
335
336    /// Commit staged changes with default signature
337    ///
338    /// Similar to `git commit -m "<message>"`
339    /// This operation is performed on the worktree's checked-out files.
340    ///
341    /// # Examples
342    ///
343    /// ```rust,ignore
344    /// # async fn example(worktree: git2db::storage::WorktreeHandle) -> Result<(), Box<dyn std::error::Error>> {
345    /// // Stage changes
346    /// worktree.staging().add("README.md")?;
347    ///
348    /// // Commit changes
349    /// let oid = worktree.commit("Update docs").await?;
350    /// # Ok(())
351    /// # }
352    /// ```
353    pub async fn commit(&mut self, message: &str) -> Git2DBResult<Oid> {
354        // Get default signature from the global GitManager
355        let git_manager = crate::manager::GitManager::global();
356        let sig = git_manager.create_signature(None, None)?;
357
358        self.commit_as(&sig, message).await
359    }
360
361    /// Commit staged changes with a specific author/committer
362    ///
363    /// Similar to `git commit -m "<message>" --author="<name> <email>"`
364    ///
365    /// # Examples
366    ///
367    /// ```rust,ignore
368    /// # async fn example(worktree: git2db::storage::WorktreeHandle) -> Result<(), Box<dyn std::error::Error>> {
369    /// use git2::Signature;
370    ///
371    /// // Stage changes
372    /// worktree.staging().add("README.md")?;
373    ///
374    /// // Create custom signature
375    /// let sig = Signature::now("Alice", "alice@example.com")?;
376    ///
377    /// // Commit as specific user
378    /// let oid = worktree.commit_as(&sig, "Update docs").await?;
379    /// # Ok(())
380    /// # }
381    /// ```
382    pub async fn commit_as(
383        &mut self,
384        signature: &Signature<'_>,
385        message: &str,
386    ) -> Git2DBResult<Oid> {
387        let repo = self.open_repository()?;
388
389        // Get the current index
390        let mut index = repo
391            .index()
392            .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?;
393
394        // Write index to tree
395        let tree_oid = index
396            .write_tree()
397            .map_err(|e| Git2DBError::internal(format!("Failed to write tree: {e}")))?;
398
399        let tree = repo
400            .find_tree(tree_oid)
401            .map_err(|e| Git2DBError::internal(format!("Failed to find tree: {e}")))?;
402
403        // Get parent commit (if any)
404        let parent_commits = if let Ok(head) = repo.head() {
405            vec![head.peel_to_commit().map_err(|e| {
406                Git2DBError::reference("HEAD", format!("Failed to get HEAD commit: {e}"))
407            })?]
408        } else {
409            vec![]
410        };
411
412        let parent_refs: Vec<&git2::Commit> = parent_commits.iter().collect();
413
414        // Create the commit
415        let commit_oid = repo
416            .commit(
417                Some("HEAD"),
418                signature,
419                signature,
420                message,
421                &tree,
422                &parent_refs,
423            )
424            .map_err(|e| Git2DBError::internal(format!("Failed to create commit: {e}")))?;
425
426        Ok(commit_oid)
427    }
428
429    /// Amend the last commit
430    ///
431    /// Similar to `git commit --amend`
432    ///
433    /// # Examples
434    ///
435    /// ```rust,ignore
436    /// # async fn example(worktree: git2db::storage::WorktreeHandle) -> Result<(), Box<dyn std::error::Error>> {
437    /// // Stage additional changes
438    /// worktree.staging().add("forgotten_file.rs")?;
439    ///
440    /// // Amend previous commit
441    /// let oid = worktree.amend(Some("Updated commit message")).await?;
442    /// # Ok(())
443    /// # }
444    /// ```
445    pub async fn amend(&mut self, message: Option<&str>) -> Git2DBResult<Oid> {
446        let repo = self.open_repository()?;
447
448        // Get HEAD commit
449        let head = repo
450            .head()
451            .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?;
452
453        let head_commit = head.peel_to_commit().map_err(|e| {
454            Git2DBError::reference("HEAD", format!("Failed to get HEAD commit: {e}"))
455        })?;
456
457        // Get current index
458        let mut index = repo
459            .index()
460            .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?;
461
462        // Write index to tree
463        let tree_oid = index
464            .write_tree()
465            .map_err(|e| Git2DBError::internal(format!("Failed to write tree: {e}")))?;
466
467        let tree = repo
468            .find_tree(tree_oid)
469            .map_err(|e| Git2DBError::internal(format!("Failed to find tree: {e}")))?;
470
471        let commit_message = message.unwrap_or_else(|| head_commit.message().unwrap_or(""));
472
473        // Create amended commit
474        let commit_oid = repo
475            .commit(
476                Some("HEAD"),
477                &head_commit.author(),
478                &head_commit.committer(),
479                commit_message,
480                &tree,
481                &[&head_commit],
482            )
483            .map_err(|e| Git2DBError::internal(format!("Failed to amend commit: {e}")))?;
484
485        Ok(commit_oid)
486    }
487
488    /// Merge a branch into the current worktree
489    ///
490    /// Similar to `git merge <branch>` with various merge options
491    ///
492    /// # Examples
493    ///
494    /// ```rust,ignore
495    /// # async fn example(worktree: git2db::storage::WorktreeHandle) -> Result<(), Box<dyn std::error::Error>> {
496    /// // Merge a feature branch
497    /// let merge_oid = worktree.merge("feature-branch", false, false).await?;
498    /// println!("Merged commit: {}", merge_oid);
499    /// # Ok(())
500    /// # }
501    /// ```
502    pub async fn merge(&mut self, branch: &str, ff_only: bool, no_ff: bool) -> Git2DBResult<Oid> {
503        let repo = self.open_repository()?;
504
505        // Resolve branch reference
506        let branch_ref = repo
507            .find_reference(&format!("refs/heads/{branch}"))
508            .or_else(|_| repo.find_reference(&format!("refs/remotes/origin/{branch}")))
509            .or_else(|_| repo.find_reference(branch))
510            .map_err(|e| Git2DBError::reference(branch, format!("Branch not found: {e}")))?;
511
512        let branch_commit = branch_ref.peel_to_commit().map_err(|e| {
513            Git2DBError::reference(branch, format!("Failed to resolve commit: {e}"))
514        })?;
515
516        let annotated_commit = repo
517            .find_annotated_commit(branch_commit.id())
518            .map_err(|e| {
519                Git2DBError::internal(format!("Failed to create annotated commit: {e}"))
520            })?;
521
522        // Perform merge analysis
523        let (merge_analysis, _) = repo
524            .merge_analysis(&[&annotated_commit])
525            .map_err(|e| Git2DBError::internal(format!("Merge analysis failed: {e}")))?;
526
527        // Already up-to-date
528        if merge_analysis.is_up_to_date() {
529            return Ok(branch_commit.id());
530        }
531
532        // Check fast-forward constraints
533        if ff_only && !merge_analysis.is_fast_forward() {
534            return Err(Git2DBError::merge_conflict(
535                "Cannot fast-forward - branches have diverged",
536            ));
537        }
538
539        // Fast-forward merge (if possible and not --no-ff)
540        if merge_analysis.is_fast_forward() && !no_ff {
541            let mut head_ref = repo
542                .head()
543                .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?;
544
545            head_ref
546                .set_target(branch_commit.id(), "Fast-forward merge")
547                .map_err(|e| Git2DBError::internal(format!("Failed to update HEAD: {e}")))?;
548
549            repo.checkout_head(Some(git2::build::CheckoutBuilder::default().force()))
550                .map_err(|e| Git2DBError::internal(format!("Checkout failed: {e}")))?;
551
552            return Ok(branch_commit.id());
553        }
554
555        // Regular merge (create merge commit)
556        repo.merge(&[&annotated_commit], None, None)
557            .map_err(|e| Git2DBError::internal(format!("Merge failed: {e}")))?;
558
559        // Check for conflicts
560        if repo
561            .index()
562            .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?
563            .has_conflicts()
564        {
565            return Err(Git2DBError::merge_conflict(
566                "Merge conflicts detected - please resolve manually",
567            ));
568        }
569
570        // Create merge commit
571        let sig = crate::manager::GitManager::global().create_signature(None, None)?;
572
573        let tree_id = repo
574            .index()
575            .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?
576            .write_tree()
577            .map_err(|e| Git2DBError::internal(format!("Failed to write tree: {e}")))?;
578
579        let tree = repo
580            .find_tree(tree_id)
581            .map_err(|e| Git2DBError::internal(format!("Failed to find tree: {e}")))?;
582
583        let parent = repo
584            .head()
585            .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?
586            .peel_to_commit()
587            .map_err(|e| Git2DBError::internal(format!("Failed to resolve HEAD commit: {e}")))?;
588
589        let merge_oid = repo
590            .commit(
591                Some("HEAD"),
592                &sig,
593                &sig,
594                &format!("Merge branch '{branch}'"),
595                &tree,
596                &[&parent, &branch_commit],
597            )
598            .map_err(|e| Git2DBError::internal(format!("Failed to create merge commit: {e}")))?;
599
600        repo.cleanup_state()
601            .map_err(|e| Git2DBError::internal(format!("Failed to cleanup merge state: {e}")))?;
602
603        Ok(merge_oid)
604    }
605
606    /// Get the current status of the worktree
607    ///
608    /// Returns branch information, modified files, repository state, and ahead/behind counts
609    /// compared to the upstream tracking branch (if configured).
610    ///
611    /// The `ahead` and `behind` fields indicate how many commits the local branch is ahead
612    /// or behind its upstream tracking branch. If no upstream is configured, both will be 0.
613    ///
614    /// # Examples
615    ///
616    /// ```rust,ignore
617    /// # async fn example(worktree: git2db::storage::WorktreeHandle) -> Result<(), Box<dyn std::error::Error>> {
618    /// let status = worktree.status().await?;
619    /// println!("Current branch: {:?}", status.branch);
620    /// println!("Modified files: {:?}", status.modified_files);
621    /// println!("Is clean: {}", status.is_clean);
622    /// println!("Ahead: {} commits", status.ahead);
623    /// println!("Behind: {} commits", status.behind);
624    /// # Ok(())
625    /// # }
626    /// ```
627    pub async fn status(&mut self) -> Git2DBResult<RepositoryStatus> {
628        let repo = self.open_repository()?;
629
630        let head = repo.head().ok();
631        let branch = head
632            .as_ref()
633            .and_then(|h| h.shorthand())
634            .map(std::borrow::ToOwned::to_owned);
635        let head_oid = head.as_ref().and_then(git2::Reference::target);
636
637        let statuses = repo
638            .statuses(None)
639            .map_err(|e| Git2DBError::internal(format!("Failed to get repository status: {e}")))?;
640
641        let is_clean = statuses.is_empty();
642        let modified_files: Vec<PathBuf> = statuses
643            .iter()
644            .filter_map(|entry| entry.path().map(PathBuf::from))
645            .collect();
646
647        // Calculate ahead/behind counts if we have a branch with upstream
648        let (ahead, behind) = if let (Some(branch_name), Some(local_oid)) = (&branch, head_oid) {
649            // Try to find the local branch to get its upstream
650            if let Ok(local_branch) = repo.find_branch(branch_name, git2::BranchType::Local) {
651                // Get the upstream tracking branch
652                if let Ok(upstream_branch) = local_branch.upstream() {
653                    if let Some(upstream_oid) = upstream_branch.get().target() {
654                        // Calculate ahead/behind using git2's graph_ahead_behind
655                        match repo.graph_ahead_behind(local_oid, upstream_oid) {
656                            Ok((a, b)) => (a, b),
657                            Err(_) => {
658                                // If calculation fails (e.g., no common ancestor), return zeros
659                                (0, 0)
660                            }
661                        }
662                    } else {
663                        (0, 0)
664                    }
665                } else {
666                    // No upstream tracking branch configured
667                    (0, 0)
668                }
669            } else {
670                // Couldn't find the branch (shouldn't happen, but handle gracefully)
671                (0, 0)
672            }
673        } else {
674            // No branch or no HEAD OID (detached HEAD or empty repo)
675            (0, 0)
676        };
677
678        Ok(RepositoryStatus {
679            branch,
680            head: head_oid,
681            ahead,
682            behind,
683            is_clean,
684            modified_files,
685        })
686    }
687
688    /// Checkout a specific reference (branch, tag, or commit)
689    ///
690    /// Accepts strings, GitRef enums, or direct Oids for type safety.
691    ///
692    /// # Examples
693    ///
694    /// ```rust,ignore
695    /// # async fn example(worktree: git2db::storage::WorktreeHandle) -> Result<(), Box<dyn std::error::Error>> {
696    /// // String reference
697    /// worktree.checkout("main").await?;
698    ///
699    /// // Explicit GitRef
700    /// worktree.checkout(git2db::GitRef::Branch("develop".into())).await?;
701    ///
702    /// // Direct Oid (type-safe)
703    /// let oid = git2::Oid::from_str("abc123...")?;
704    /// worktree.checkout(oid).await?;
705    /// # Ok(())
706    /// # }
707    /// ```
708    pub async fn checkout(&mut self, reference: impl IntoGitRef) -> Git2DBResult<()> {
709        let repo = self.open_repository()?;
710        let git_ref = reference.into_git_ref();
711
712        // Resolve the reference to an OID
713        let oid = match git_ref {
714            GitRef::DefaultBranch => {
715                let head = repo.head().map_err(|e| {
716                    Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}"))
717                })?;
718                head.target().ok_or_else(|| {
719                    Git2DBError::reference("HEAD", "HEAD is not a direct reference")
720                })?
721            }
722            GitRef::Branch(ref branch_name) => {
723                let branch = repo
724                    .find_branch(branch_name, git2::BranchType::Local)
725                    .or_else(|_| repo.find_branch(branch_name, git2::BranchType::Remote))
726                    .map_err(|e| {
727                        Git2DBError::reference(branch_name, format!("Branch not found: {e}"))
728                    })?;
729                branch
730                    .get()
731                    .target()
732                    .ok_or_else(|| Git2DBError::reference(branch_name, "Branch has no target"))?
733            }
734            GitRef::Tag(ref tag_name) => {
735                let reference = repo
736                    .find_reference(&format!("refs/tags/{tag_name}"))
737                    .map_err(|e| Git2DBError::reference(tag_name, format!("Tag not found: {e}")))?;
738                reference
739                    .target()
740                    .ok_or_else(|| Git2DBError::reference(tag_name, "Tag has no target"))?
741            }
742            GitRef::Commit(oid) => oid,
743            GitRef::Revspec(ref spec) => {
744                let obj = repo.revparse_single(spec).map_err(|e| {
745                    Git2DBError::reference(spec, format!("Failed to resolve revspec: {e}"))
746                })?;
747                obj.id()
748            }
749        };
750
751        // Checkout the commit
752        let commit = repo
753            .find_commit(oid)
754            .map_err(|e| Git2DBError::internal(format!("Failed to find commit: {e}")))?;
755
756        repo.checkout_tree(commit.as_object(), None)
757            .map_err(|e| Git2DBError::internal(format!("Failed to checkout tree: {e}")))?;
758
759        // Update HEAD
760        repo.set_head_detached(oid)
761            .map_err(|e| Git2DBError::internal(format!("Failed to update HEAD: {e}")))?;
762
763        Ok(())
764    }
765
766    /// Fetch from a remote
767    ///
768    /// # Examples
769    ///
770    /// ```rust,ignore
771    /// # async fn example(worktree: git2db::storage::WorktreeHandle) -> Result<(), Box<dyn std::error::Error>> {
772    /// // Fetch from default remote (origin)
773    /// worktree.fetch(None).await?;
774    ///
775    /// // Fetch from specific remote
776    /// worktree.fetch(Some("upstream")).await?;
777    /// # Ok(())
778    /// # }
779    /// ```
780    pub async fn fetch(&mut self, remote: Option<&str>) -> Git2DBResult<()> {
781        let repo = self.open_repository()?;
782        let remote_name = remote.unwrap_or("origin");
783
784        let mut remote_obj = repo
785            .find_remote(remote_name)
786            .map_err(|e| Git2DBError::reference(remote_name, format!("Remote not found: {e}")))?;
787
788        remote_obj.fetch(&[] as &[&str], None, None).map_err(|e| {
789            Git2DBError::network(format!("Failed to fetch from {remote_name}: {e}"))
790        })?;
791
792        Ok(())
793    }
794
795    /// Pull updates from remote (fetch + merge)
796    ///
797    /// Updates the current branch with changes from the remote tracking branch.
798    ///
799    /// # Examples
800    ///
801    /// ```rust,ignore
802    /// # async fn example(worktree: git2db::storage::WorktreeHandle) -> Result<(), Box<dyn std::error::Error>> {
803    /// // Pull from default remote (origin)
804    /// worktree.pull(None).await?;
805    ///
806    /// // Pull from specific remote
807    /// worktree.pull(Some("upstream")).await?;
808    /// # Ok(())
809    /// # }
810    /// ```
811    pub async fn pull(&mut self, remote: Option<&str>) -> Git2DBResult<()> {
812        // First fetch from remote
813        self.fetch(remote).await?;
814
815        let repo = self.open_repository()?;
816        let remote_name = remote.unwrap_or("origin");
817
818        // Get current branch
819        let head = repo
820            .head()
821            .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?;
822        let current_branch = head
823            .shorthand()
824            .ok_or_else(|| Git2DBError::reference("HEAD", "HEAD is detached"))?;
825
826        // Get tracking branch (e.g., origin/main)
827        let tracking_ref = format!("refs/remotes/{remote_name}/{current_branch}");
828        let tracking_commit = repo
829            .find_reference(&tracking_ref)
830            .and_then(|r| r.peel_to_commit())
831            .map_err(|e| {
832                Git2DBError::internal(format!(
833                    "Failed to find tracking branch {tracking_ref}: {e}"
834                ))
835            })?;
836
837        let annotated_commit = repo.find_annotated_commit(tracking_commit.id())?;
838
839        // Check if we can fast-forward
840        let (merge_analysis, _) = repo.merge_analysis(&[&annotated_commit])?;
841
842        if merge_analysis.is_up_to_date() {
843            return Ok(());
844        }
845
846        if merge_analysis.is_fast_forward() {
847            // Fast-forward
848            let commit_id = annotated_commit.id();
849            let commit = repo
850                .find_commit(commit_id)
851                .map_err(|e| Git2DBError::internal(format!("Failed to find commit: {e}")))?;
852            repo.checkout_tree(commit.as_object(), None)
853                .map_err(|e| Git2DBError::internal(format!("Failed to checkout tree: {e}")))?;
854
855            let mut head_ref = repo
856                .head()
857                .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?;
858
859            head_ref
860                .set_target(tracking_commit.id(), "Fast-forward pull")
861                .map_err(|e| Git2DBError::internal(format!("Failed to update HEAD: {e}")))?;
862        } else {
863            // Merge (create merge commit)
864            repo.merge(&[&annotated_commit], None, None)
865                .map_err(|e| Git2DBError::internal(format!("Merge failed: {e}")))?;
866
867            // Check for conflicts
868            if repo
869                .index()
870                .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?
871                .has_conflicts()
872            {
873                return Err(Git2DBError::merge_conflict(
874                    "Pull conflicts detected - please resolve manually",
875                ));
876            }
877
878            // Create merge commit
879            let sig = crate::manager::GitManager::global().create_signature(None, None)?;
880
881            let tree_id = repo
882                .index()
883                .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?
884                .write_tree()
885                .map_err(|e| Git2DBError::internal(format!("Failed to write tree: {e}")))?;
886
887            let tree = repo
888                .find_tree(tree_id)
889                .map_err(|e| Git2DBError::internal(format!("Failed to find tree: {e}")))?;
890
891            let parent = repo
892                .head()
893                .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?
894                .peel_to_commit()
895                .map_err(|e| {
896                    Git2DBError::internal(format!("Failed to resolve HEAD commit: {e}"))
897                })?;
898
899            repo.commit(
900                Some("HEAD"),
901                &sig,
902                &sig,
903                &format!("Pull branch '{current_branch}' from {remote_name}"),
904                &tree,
905                &[&parent, &tracking_commit],
906            )
907            .map_err(|e| Git2DBError::internal(format!("Failed to create merge commit: {e}")))?;
908        }
909
910        repo.cleanup_state()
911            .map_err(|e| Git2DBError::internal(format!("Failed to cleanup merge state: {e}")))?;
912
913        Ok(())
914    }
915
916    /// Push changes to remote
917    ///
918    /// # Examples
919    ///
920    /// ```rust,ignore
921    /// # async fn example(worktree: git2db::storage::WorktreeHandle) -> Result<(), Box<dyn std::error::Error>> {
922    /// // Push to default remote (origin)
923    /// worktree.push(None).await?;
924    ///
925    /// // Push to specific remote
926    /// worktree.push(Some("upstream")).await?;
927    /// # Ok(())
928    /// # }
929    /// ```
930    pub async fn push(&mut self, remote: Option<&str>) -> Git2DBResult<()> {
931        let repo = self.open_repository()?;
932        let remote_name = remote.unwrap_or("origin");
933
934        let mut remote_obj = repo
935            .find_remote(remote_name)
936            .map_err(|e| Git2DBError::reference(remote_name, format!("Remote not found: {e}")))?;
937
938        remote_obj
939            .push(&[] as &[&str], None)
940            .map_err(|e| Git2DBError::network(format!("Failed to push to {remote_name}: {e}")))?;
941
942        Ok(())
943    }
944
945    /// Update to latest from tracking remote
946    ///
947    /// Equivalent to `git pull --ff-only` - only fast-forwards, no merges
948    ///
949    /// # Examples
950    ///
951    /// ```rust,ignore
952    /// # async fn example(worktree: git2db::storage::WorktreeHandle) -> Result<(), Box<dyn std::error::Error>> {
953    /// // Update from default remote (origin)
954    /// worktree.update().await?;
955    ///
956    /// // Update from specific remote
957    /// worktree.update_with_remote("upstream").await?;
958    /// # Ok(())
959    /// # }
960    /// ```
961    pub async fn update(&mut self) -> Git2DBResult<()> {
962        self.fetch(None).await?;
963
964        let repo = self.open_repository()?;
965
966        // Get current branch
967        let head = repo
968            .head()
969            .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?;
970        let current_branch = head
971            .shorthand()
972            .ok_or_else(|| Git2DBError::reference("HEAD", "HEAD is detached"))?;
973
974        // Get tracking branch
975        let tracking_ref = format!("refs/remotes/origin/{current_branch}");
976        let tracking_commit = repo
977            .find_reference(&tracking_ref)
978            .and_then(|r| r.peel_to_commit())
979            .map_err(|e| {
980                Git2DBError::internal(format!(
981                    "Failed to find tracking branch {tracking_ref}: {e}"
982                ))
983            })?;
984
985        let annotated_commit = repo.find_annotated_commit(tracking_commit.id())?;
986
987        // Check if we can fast-forward
988        let (merge_analysis, _) = repo.merge_analysis(&[&annotated_commit])?;
989
990        if merge_analysis.is_up_to_date() {
991            return Ok(());
992        }
993
994        if merge_analysis.is_fast_forward() {
995            // Fast-forward only
996            let commit_id = annotated_commit.id();
997            let commit = repo
998                .find_commit(commit_id)
999                .map_err(|e| Git2DBError::internal(format!("Failed to find commit: {e}")))?;
1000            repo.checkout_tree(commit.as_object(), None)
1001                .map_err(|e| Git2DBError::internal(format!("Failed to checkout tree: {e}")))?;
1002
1003            let mut head_ref = repo
1004                .head()
1005                .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?;
1006
1007            head_ref
1008                .set_target(tracking_commit.id(), "Fast-forward update")
1009                .map_err(|e| Git2DBError::internal(format!("Failed to update HEAD: {e}")))?;
1010        } else {
1011            return Err(Git2DBError::merge_conflict(
1012                "Cannot update - branches have diverged. Use `pull()` to merge.",
1013            ));
1014        }
1015
1016        repo.cleanup_state()
1017            .map_err(|e| Git2DBError::internal(format!("Failed to cleanup merge state: {e}")))?;
1018
1019        Ok(())
1020    }
1021
1022    /// Update from a specific remote
1023    pub async fn update_with_remote(&mut self, remote: &str) -> Git2DBResult<()> {
1024        self.fetch(Some(remote)).await?;
1025
1026        let repo = self.open_repository()?;
1027
1028        // Get current branch
1029        let head = repo
1030            .head()
1031            .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?;
1032        let current_branch = head
1033            .shorthand()
1034            .ok_or_else(|| Git2DBError::reference("HEAD", "HEAD is detached"))?;
1035
1036        // Get tracking branch
1037        let tracking_ref = format!("refs/remotes/{remote}/{current_branch}");
1038        let tracking_commit = repo
1039            .find_reference(&tracking_ref)
1040            .and_then(|r| r.peel_to_commit())
1041            .map_err(|e| {
1042                Git2DBError::internal(format!(
1043                    "Failed to find tracking branch {tracking_ref}: {e}"
1044                ))
1045            })?;
1046
1047        let annotated_commit = repo.find_annotated_commit(tracking_commit.id())?;
1048
1049        // Check if we can fast-forward
1050        let (merge_analysis, _) = repo.merge_analysis(&[&annotated_commit])?;
1051
1052        if merge_analysis.is_up_to_date() {
1053            return Ok(());
1054        }
1055
1056        if merge_analysis.is_fast_forward() {
1057            // Fast-forward only
1058            let commit_id = annotated_commit.id();
1059            let commit = repo
1060                .find_commit(commit_id)
1061                .map_err(|e| Git2DBError::internal(format!("Failed to find commit: {e}")))?;
1062            repo.checkout_tree(commit.as_object(), None)
1063                .map_err(|e| Git2DBError::internal(format!("Failed to checkout tree: {e}")))?;
1064
1065            let mut head_ref = repo
1066                .head()
1067                .map_err(|e| Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}")))?;
1068
1069            head_ref
1070                .set_target(
1071                    tracking_commit.id(),
1072                    &format!("Fast-forward update from {remote}"),
1073                )
1074                .map_err(|e| Git2DBError::internal(format!("Failed to update HEAD: {e}")))?;
1075        } else {
1076            return Err(Git2DBError::merge_conflict(format!(
1077                "Cannot update from {remote} - branches have diverged. Use `pull()` to merge."
1078            )));
1079        }
1080
1081        repo.cleanup_state()
1082            .map_err(|e| Git2DBError::internal(format!("Failed to cleanup merge state: {e}")))?;
1083
1084        Ok(())
1085    }
1086}
1087
1088/// Worktree metadata for inspection and debugging
1089#[derive(Debug, Clone)]
1090pub struct WorktreeMetadata {
1091    pub path: PathBuf,
1092    pub driver_name: String,
1093    pub is_valid: bool,
1094    pub is_dirty: bool,
1095    pub created_at: chrono::DateTime<chrono::Utc>,
1096}
1097
1098impl Drop for WorktreeHandle {
1099    fn drop(&mut self) {
1100        if self.cleanup.is_some() {
1101            tracing::warn!(
1102                "WorktreeHandle at {} dropped without calling cleanup() - \
1103                 resources may leak (overlayfs mounts, temporary directories)",
1104                self.path.display()
1105            );
1106        }
1107    }
1108}
1109
1110impl fmt::Debug for WorktreeHandle {
1111    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1112        f.debug_struct("WorktreeHandle")
1113            .field("path", &self.path)
1114            .field("driver_name", &self.driver_name)
1115            .finish()
1116    }
1117}