Skip to main content

git2db/
repository_handle.rs

1//! Repository handle for git-native operations
2//!
3//! Provides a scoped view into a tracked repository with familiar git operations
4
5use crate::branch::BranchManager;
6use crate::errors::{Git2DBError, Git2DBResult};
7use crate::references::GitRef;
8use crate::registry::{Git2DB, RepoId, TrackedRepository};
9use crate::remote::RemoteManager;
10use crate::stage::StageManager;
11use crate::storage::{DriverOpts, WorktreeHandle};
12use git2::{Oid, Repository, Signature};
13use std::path::{Path, PathBuf};
14use std::sync::Arc;
15use tracing::info;
16
17/// Handle to a tracked repository
18///
19/// Provides git-native operations on a repository tracked in the registry.
20/// This handle borrows from the Git2DB registry and provides a scoped interface.
21pub struct RepositoryHandle<'a> {
22    registry: &'a Git2DB,
23    repo_id: RepoId,
24}
25
26impl<'a> RepositoryHandle<'a> {
27    /// Create a new repository handle
28    pub(crate) fn new(registry: &'a Git2DB, repo_id: RepoId) -> Self {
29        Self { registry, repo_id }
30    }
31
32    /// Get the repository ID
33    pub fn id(&self) -> &RepoId {
34        &self.repo_id
35    }
36
37    /// Get the repository metadata
38    pub fn metadata(&self) -> Git2DBResult<&TrackedRepository> {
39        self.registry.get_by_id(&self.repo_id).ok_or_else(|| {
40            Git2DBError::invalid_repository(
41                self.repo_id.to_string(),
42                "Repository not found in registry",
43            )
44        })
45    }
46
47    /// Get the repository name (if set)
48    pub fn name(&self) -> Git2DBResult<Option<&str>> {
49        Ok(self.metadata()?.name.as_deref())
50    }
51
52    /// Get the worktree path where files are checked out
53    pub fn worktree(&self) -> Git2DBResult<&Path> {
54        Ok(&self.metadata()?.worktree_path)
55    }
56
57    /// Get the primary URL
58    pub fn url(&self) -> Git2DBResult<&str> {
59        Ok(&self.metadata()?.url)
60    }
61
62    /// Get the tracking ref (branch, tag, or commit)
63    pub fn tracking_ref(&self) -> Git2DBResult<&GitRef> {
64        Ok(&self.metadata()?.tracking_ref)
65    }
66
67    /// Resolve a working tree path suitable for git operations.
68    ///
69    /// For bare repositories (e.g. cloned models stored as `name.git`),
70    /// `worktree()` returns the bare repo path, which cannot be used for
71    /// operations requiring a working tree (status, staging, etc.).
72    /// This method finds the actual worktree for the tracking ref.
73    pub async fn resolve_worktree_path(&self) -> Git2DBResult<PathBuf> {
74        let base_path = self.worktree()?.to_path_buf();
75
76        // Detect bare repo: path ends in .git or has HEAD but no .git subdir
77        let is_bare = base_path.extension().is_some_and(|ext| ext == "git")
78            || (base_path.join("HEAD").exists() && !base_path.join(".git").exists());
79
80        if !is_bare {
81            return Ok(base_path);
82        }
83
84        // Try the tracking ref's worktree
85        let tracked = self.metadata()?;
86        if let GitRef::Branch(ref branch) = tracked.tracking_ref {
87            if let Ok(Some(wt)) = self.get_worktree(branch).await {
88                return Ok(wt.path().to_path_buf());
89            }
90        }
91
92        // Fallback: try any available worktree
93        if let Ok(worktrees) = self.get_worktrees().await {
94            if let Some(wt) = worktrees.into_iter().next() {
95                return Ok(wt.path().to_path_buf());
96            }
97        }
98
99        Err(Git2DBError::repository(
100            &base_path,
101            "No worktrees found for bare repository",
102        ))
103    }
104
105    /// Get the current OID (commit hash)
106    pub fn current_oid(&self) -> Git2DBResult<Option<Oid>> {
107        match &self.metadata()?.current_oid {
108            Some(oid_str) => Ok(Some(Oid::from_str(oid_str).map_err(|e| {
109                Git2DBError::internal(format!("Invalid OID in metadata: {e}"))
110            })?)),
111            None => Ok(None),
112        }
113    }
114
115    /// Open the underlying git repository
116    pub fn open_repo(&self) -> Git2DBResult<Repository> {
117        let path = self.worktree()?;
118        Repository::open(path)
119            .map_err(|e| Git2DBError::repository(path, format!("Failed to open repository: {e}")))
120    }
121
122    /// Checkout a specific reference (branch, tag, or commit)
123    ///
124    /// Accepts strings, GitRef enums, or direct Oids for type safety.
125    ///
126    /// # Examples
127    ///
128    /// ```rust,ignore
129    /// # async fn example(repo: git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
130    /// // String reference
131    /// repo.checkout("main").await?;
132    ///
133    /// // Explicit GitRef
134    /// repo.checkout(git2db::GitRef::Branch("develop".into())).await?;
135    ///
136    /// // Direct Oid (type-safe)
137    /// let oid = git2::Oid::from_str("abc123...")?;
138    /// repo.checkout(oid).await?;
139    /// # Ok(())
140    /// # }
141    /// ```
142    /// Get remote manager for this repository
143    ///
144    /// Provides git-native remote operations like `git remote`.
145    ///
146    /// # Examples
147    ///
148    /// ```rust,ignore
149    /// # async fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
150    /// // Add remotes
151    /// repo.remote().add("origin", "https://github.com/user/repo.git").await?;
152    /// repo.remote().add("p2p", "gittorrent://peer/repo").await?;
153    ///
154    /// // List remotes
155    /// for remote in repo.remote().list().await? {
156    ///     println!("{}: {}", remote.name, remote.url);
157    /// }
158    /// # Ok(())
159    /// # }
160    /// ```
161    pub fn remote(&self) -> RemoteManager<'a> {
162        RemoteManager::new(self.registry, self.repo_id.clone())
163    }
164
165    /// Get branch manager for this repository
166    ///
167    /// Provides git-native branch operations like `git branch`.
168    ///
169    /// # Examples
170    ///
171    /// ```rust,no_run
172    /// # async fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
173    /// // List branches
174    /// for branch in repo.branch().list().await? {
175    ///     println!("{} {}", if branch.is_head { "*" } else { " " }, branch.name);
176    /// }
177    ///
178    /// // Get current branch
179    /// if let Some(current) = repo.branch().current().await? {
180    ///     println!("On branch: {}", current.name);
181    /// }
182    ///
183    /// // Create and checkout
184    /// repo.branch().create("feature", Some("main")).await?;
185    /// repo.branch().checkout("feature").await?;
186    /// # Ok(())
187    /// # }
188    /// ```
189    pub fn branch(&self) -> BranchManager<'a> {
190        BranchManager::new(self.registry, self.repo_id.clone())
191    }
192
193    /// Get staging area manager for this repository
194    ///
195    /// Provides git-native staging operations like `git add` and `git rm`.
196    ///
197    /// # Examples
198    ///
199    /// ```rust,no_run
200    /// # async fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
201    /// // Add files to staging area
202    /// repo.staging().add("src/main.rs").await?;
203    /// repo.staging().add_all().await?;
204    ///
205    /// // Check staged files
206    /// for file in repo.staging().staged_files().await? {
207    ///     println!("Staged: {:?}", file.path);
208    /// }
209    /// # Ok(())
210    /// # }
211    /// ```
212    pub fn staging(&self) -> StageManager<'a> {
213        StageManager::new(self.registry, self.repo_id.clone())
214    }
215
216    /// Commit staged changes with default signature
217    ///
218    /// Similar to `git commit -m "<message>"`
219    ///
220    /// This method commits all staged changes using the default signature from
221    /// GitManager configuration. The signature is created from git config or
222    /// the Git2DB configuration.
223    ///
224    /// # Examples
225    ///
226    /// ```rust,no_run
227    /// # async fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
228    /// // Stage changes
229    /// repo.staging().add_all().await?;
230    ///
231    /// // Commit with default signature
232    /// let oid = repo.commit("Update documentation").await?;
233    /// println!("Committed: {}", oid);
234    /// # Ok(())
235    /// # }
236    /// ```
237    ///
238    /// # Errors
239    ///
240    /// This method will return an error if:
241    /// - There are no staged changes
242    /// - The repository cannot be opened
243    /// - The signature cannot be created (check git config)
244    /// - The commit cannot be created
245    pub async fn commit(&self, message: &str) -> Git2DBResult<Oid> {
246        // Get default signature from the global GitManager
247        let git_manager = crate::manager::GitManager::global();
248        let sig = git_manager.create_signature(None, None)?;
249
250        self.commit_as(&sig, message).await
251    }
252
253    /// Commit staged changes with a specific author/committer
254    ///
255    /// Similar to `git commit -m "<message>" --author="<name> <email>"`
256    ///
257    /// This method commits all staged changes using the provided signature.
258    /// Both author and committer will be set to the provided signature.
259    ///
260    /// # Examples
261    ///
262    /// ```rust,no_run
263    /// # async fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
264    /// use git2::Signature;
265    ///
266    /// // Stage changes
267    /// repo.staging().add("README.md").await?;
268    ///
269    /// // Create custom signature
270    /// let sig = Signature::now("Alice", "alice@example.com")?;
271    ///
272    /// // Commit as specific user
273    /// let oid = repo.commit_as(&sig, "Update docs").await?;
274    /// # Ok(())
275    /// # }
276    /// ```
277    ///
278    /// # Errors
279    ///
280    /// This method will return an error if:
281    /// - There are no staged changes
282    /// - The repository cannot be opened
283    /// - The commit cannot be created
284    pub async fn commit_as(&self, signature: &Signature<'_>, message: &str) -> Git2DBResult<Oid> {
285        let repo_path = self.worktree()?.to_path_buf();
286        let message = message.to_owned();
287        // Clone signature data to move into the blocking task
288        // Note: Signature has a lifetime, so we need to extract the data
289        let sig_name = signature.name().unwrap_or("Unknown").to_owned();
290        let sig_email = signature
291            .email()
292            .unwrap_or("unknown@example.com")
293            .to_owned();
294        // Preserve the original timestamp from the signature
295        let sig_time = signature.when();
296        let sig_time_seconds = sig_time.seconds();
297        let sig_time_offset = sig_time.offset_minutes();
298
299        tracing::info!(message = %message, author = %sig_name, "Creating commit");
300
301        tokio::task::spawn_blocking(move || -> Git2DBResult<Oid> {
302            let repo = Repository::open(&repo_path).map_err(|e| {
303                Git2DBError::repository(&repo_path, format!("Failed to open repository: {e}"))
304            })?;
305
306            // Get the current index
307            let mut index = repo
308                .index()
309                .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?;
310
311            // Write index to tree
312            let tree_oid = index
313                .write_tree()
314                .map_err(|e| Git2DBError::internal(format!("Failed to write tree: {e}")))?;
315
316            let tree = repo
317                .find_tree(tree_oid)
318                .map_err(|e| Git2DBError::internal(format!("Failed to find tree: {e}")))?;
319
320            // Get parent commit (if any)
321            let parent_commits = if let Ok(head) = repo.head() {
322                vec![head.peel_to_commit().map_err(|e| {
323                    Git2DBError::reference("HEAD", format!("Failed to get HEAD commit: {e}"))
324                })?]
325            } else {
326                vec![]
327            };
328
329            let parent_refs: Vec<&git2::Commit> = parent_commits.iter().collect();
330
331            // Check for empty commits (nothing staged that differs from parent)
332            if let Some(parent) = parent_refs.first() {
333                if parent.tree_id() == tree_oid {
334                    return Err(Git2DBError::invalid_operation(
335                        "Nothing to commit: no changes staged",
336                    ));
337                }
338            }
339
340            // Recreate signature in the blocking task, preserving the original timestamp
341            let time = git2::Time::new(sig_time_seconds, sig_time_offset);
342            let sig = Signature::new(&sig_name, &sig_email, &time)
343                .map_err(|e| Git2DBError::internal(format!("Failed to create signature: {e}")))?;
344
345            // Create the commit
346            let commit_oid = repo
347                .commit(Some("HEAD"), &sig, &sig, &message, &tree, &parent_refs)
348                .map_err(|e| Git2DBError::internal(format!("Failed to create commit: {e}")))?;
349
350            Ok(commit_oid)
351        })
352        .await
353        .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
354    }
355
356    /// Get repository status (branch, dirty files, etc.)
357    ///
358    /// Similar to `git status` but returns structured data instead of printing.
359    ///
360    /// # Examples
361    ///
362    /// ```rust,no_run
363    /// # async fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
364    /// let status = repo.status().await?;
365    /// println!("Branch: {:?}", status.branch);
366    /// println!("Clean: {}", status.is_clean);
367    /// if !status.is_clean {
368    ///     for file in &status.modified_files {
369    ///         println!("Modified: {}", file.display());
370    ///     }
371    /// }
372    /// # Ok(())
373    /// # }
374    /// ```
375    ///
376    /// # Errors
377    ///
378    /// This method will return an error if:
379    /// - The repository cannot be opened
380    /// - The status cannot be retrieved
381    pub async fn status(&self) -> Git2DBResult<RepositoryStatus> {
382        let repo_path = self.resolve_worktree_path().await?;
383
384        tokio::task::spawn_blocking(move || {
385            let repo = crate::manager::GitManager::global()
386                .get_repository(&repo_path)
387                .map_err(|e| {
388                    Git2DBError::repository(&repo_path, format!("Failed to get repository: {e}"))
389                })?
390                .open()
391                .map_err(|e| {
392                    Git2DBError::repository(&repo_path, format!("Failed to open repository: {e}"))
393                })?;
394
395            // Get HEAD
396            let head = repo.head().ok();
397            let branch = head.as_ref().and_then(|h| h.shorthand().map(String::from));
398            let head_oid = head.as_ref().and_then(git2::Reference::target);
399
400            // Get statuses
401            let statuses = repo
402                .statuses(None)
403                .map_err(|e| Git2DBError::internal(format!("Failed to get statuses: {e}")))?;
404
405            let is_clean = statuses.is_empty();
406
407            // Collect modified file paths
408            let modified_files: Vec<PathBuf> = statuses
409                .iter()
410                .filter_map(|entry| entry.path().map(PathBuf::from))
411                .collect();
412
413            Ok(RepositoryStatus {
414                branch,
415                head: head_oid,
416                ahead: 0,  // TODO: Implement ahead/behind detection
417                behind: 0, // TODO: Implement ahead/behind detection
418                is_clean,
419                modified_files,
420            })
421        })
422        .await
423        .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
424    }
425
426    /// Merge a branch or reference into the current HEAD
427    ///
428    /// Similar to `git merge <source>`
429    ///
430    /// # Arguments
431    ///
432    /// * `source` - The branch or ref to merge (e.g., "feature-branch", "refs/tags/v1.0")
433    /// * `message` - Optional commit message (defaults to "Merge branch 'source'")
434    ///
435    /// # Examples
436    ///
437    /// ```rust,no_run
438    /// # async fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
439    /// // Merge a branch
440    /// let merge_oid = repo.merge("feature-branch", None).await?;
441    ///
442    /// // Merge with custom message
443    /// let merge_oid = repo.merge("feature-branch", Some("Merge feature-branch")).await?;
444    /// # Ok(())
445    /// # }
446    /// ```
447    ///
448    /// # Errors
449    ///
450    /// This method will return an error if:
451    /// - The repository cannot be opened
452    /// - The source ref cannot be found
453    /// - Merge conflicts are detected
454    /// - The merge commit cannot be created
455    pub async fn merge(&self, source: &str, message: Option<&str>) -> Git2DBResult<Oid> {
456        let repo_path = self.worktree()?.to_path_buf();
457        let source = source.to_owned();
458        let message = message.map(std::borrow::ToOwned::to_owned);
459
460        tokio::task::spawn_blocking(move || {
461            let repo = crate::manager::GitManager::global()
462                .get_repository(&repo_path)
463                .map_err(|e| {
464                    Git2DBError::repository(&repo_path, format!("Failed to get repository: {e}"))
465                })?
466                .open()
467                .map_err(|e| {
468                    Git2DBError::repository(&repo_path, format!("Failed to open repository: {e}"))
469                })?;
470
471            // Get default signature from the global GitManager
472            let git_manager = crate::manager::GitManager::global();
473            let sig = git_manager.create_signature(None, None)?;
474
475            // Find the source ref to merge
476            let (obj, _src_ref) = repo
477                .revparse_ext(&source)
478                .map_err(|e| Git2DBError::reference(&source, format!("Failed to find ref: {e}")))?;
479
480            let source_commit = obj.peel_to_commit().map_err(|e| {
481                Git2DBError::reference(&source, format!("Failed to peel to commit: {e}"))
482            })?;
483
484            // Get annotated commit for merge
485            let source_annotated = repo
486                .find_annotated_commit(source_commit.id())
487                .map_err(|e| {
488                    Git2DBError::internal(format!("Failed to find annotated commit: {e}"))
489                })?;
490
491            // Perform the merge analysis
492            let (analysis, _preference) = repo
493                .merge_analysis(&[&source_annotated])
494                .map_err(|e| Git2DBError::internal(format!("Failed to analyze merge: {e}")))?;
495
496            // Check if up-to-date
497            if analysis.contains(git2::MergeAnalysis::ANALYSIS_UP_TO_DATE) {
498                return Err(Git2DBError::invalid_operation("Already up to date"));
499            }
500
501            // Check if fast-forward
502            if analysis.contains(git2::MergeAnalysis::ANALYSIS_FASTFORWARD) {
503                // Do fast-forward merge
504                let source_obj = source_commit.as_object();
505                repo.checkout_tree(source_obj, None)
506                    .map_err(|e| Git2DBError::internal(format!("Failed to checkout tree: {e}")))?;
507
508                repo.set_head(&format!("refs/heads/{source}"))
509                    .map_err(|e| Git2DBError::internal(format!("Failed to set HEAD: {e}")))?;
510
511                return Ok(source_commit.id());
512            }
513
514            // Normal merge required - commit merge
515            repo.merge(&[&source_annotated], None, None)
516                .map_err(|e| Git2DBError::internal(format!("Failed to perform merge: {e}")))?;
517
518            // Check for conflicts again after merge
519            let mut index = repo
520                .index()
521                .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?;
522
523            if index.has_conflicts() {
524                repo.cleanup_state().map_err(|e| {
525                    Git2DBError::internal(format!("Failed to cleanup merge state: {e}"))
526                })?;
527                return Err(Git2DBError::invalid_operation("Merge conflicts detected"));
528            }
529
530            // Write tree and create merge commit
531            let tree_id = index
532                .write_tree()
533                .map_err(|e| Git2DBError::internal(format!("Failed to write tree: {e}")))?;
534
535            let tree = repo
536                .find_tree(tree_id)
537                .map_err(|e| Git2DBError::internal(format!("Failed to find tree: {e}")))?;
538
539            // Get parent commits
540            let head = repo
541                .head()
542                .map_err(|e| Git2DBError::internal(format!("Failed to get HEAD: {e}")))?
543                .peel_to_commit()
544                .map_err(|e| {
545                    Git2DBError::internal(format!("Failed to resolve HEAD commit: {e}"))
546                })?;
547
548            let merge_msg = message.unwrap_or_else(|| format!("Merge branch '{source}'"));
549
550            // Create merge commit
551            let merge_oid = repo
552                .commit(
553                    Some("HEAD"),
554                    &sig,
555                    &sig,
556                    &merge_msg,
557                    &tree,
558                    &[&head, &source_commit],
559                )
560                .map_err(|e| {
561                    Git2DBError::internal(format!("Failed to create merge commit: {e}"))
562                })?;
563
564            // Cleanup merge state
565            repo.cleanup_state().map_err(|e| {
566                Git2DBError::internal(format!("Failed to cleanup merge state: {e}"))
567            })?;
568
569            Ok(merge_oid)
570        })
571        .await
572        .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
573    }
574
575    /// List all references (branches and tags) with their OIDs
576    ///
577    /// Similar to `git show-ref`
578    ///
579    /// # Examples
580    ///
581    /// ```rust,no_run
582    /// # fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
583    /// for (name, oid) in repo.list_refs()? {
584    ///     println!("{}: {}", name, oid);
585    /// }
586    /// # Ok(())
587    /// # }
588    /// ```
589    pub fn list_refs(&self) -> Git2DBResult<Vec<(String, Oid)>> {
590        let repo = self.open_repo()?;
591        let mut refs = Vec::new();
592
593        for reference in repo
594            .references()
595            .map_err(|e| Git2DBError::internal(format!("Failed to list references: {e}")))?
596        {
597            let r = reference
598                .map_err(|e| Git2DBError::internal(format!("Failed to read reference: {e}")))?;
599
600            if let Some(name) = r.shorthand() {
601                if let Some(oid) = r.target() {
602                    refs.push((name.to_owned(), oid));
603                }
604            }
605        }
606
607        Ok(refs)
608    }
609
610    /// Get the default branch name
611    ///
612    /// Similar to `git symbolic-ref --short HEAD` or detecting main/master
613    ///
614    /// # Examples
615    ///
616    /// ```rust,no_run
617    /// # fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
618    /// let default_branch = repo.default_branch()?;
619    /// println!("Default branch: {}", default_branch);
620    /// # Ok(())
621    /// # }
622    /// ```
623    pub fn default_branch(&self) -> Git2DBResult<String> {
624        let repo = self.open_repo()?;
625
626        // Try to get the symbolic reference HEAD points to
627        if let Ok(head_ref) = repo.head() {
628            if let Some(name) = head_ref.symbolic_target() {
629                // Remove refs/heads/ prefix to get just the branch name
630                if let Some(branch_name) = name.strip_prefix("refs/heads/") {
631                    return Ok(branch_name.to_owned());
632                }
633            }
634        }
635
636        // If HEAD doesn't point to a symbolic ref, try to find the default branch
637        // Check for common default branch names
638        for default_name in ["main", "master"] {
639            if repo
640                .find_branch(default_name, git2::BranchType::Local)
641                .is_ok()
642            {
643                return Ok(default_name.to_owned());
644            }
645        }
646
647        // Fallback: get the first branch
648        let mut branches = repo
649            .branches(Some(git2::BranchType::Local))
650            .map_err(|e| Git2DBError::internal(format!("Failed to list branches: {e}")))?;
651
652        if let Some(Ok((branch, _))) = branches.next() {
653            if let Some(name) = branch
654                .name()
655                .map_err(|e| Git2DBError::internal(format!("Failed to get branch name: {e}")))?
656            {
657                return Ok(name.to_owned());
658            }
659        }
660
661        // Final fallback
662        Ok("main".to_owned())
663    }
664
665    /// Resolve a GitRef to an OID
666    ///
667    /// This is a general-purpose method that can resolve any type of git reference
668    /// to its commit OID.
669    ///
670    /// # Examples
671    ///
672    /// ```rust,no_run
673    /// # async fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
674    /// use git2db::GitRef;
675    ///
676    /// // Resolve branch
677    /// let oid = repo.resolve_git_ref(&GitRef::Branch("main".into())).await?;
678    ///
679    /// // Resolve tag
680    /// let oid = repo.resolve_git_ref(&GitRef::Tag("v1.0.0".into())).await?;
681    ///
682    /// // Resolve commit (returns same OID)
683    /// let oid = repo.resolve_git_ref(&GitRef::Commit(oid)).await?;
684    /// # Ok(())
685    /// # }
686    /// ```
687    pub async fn resolve_git_ref(&self, git_ref: &GitRef) -> Git2DBResult<Oid> {
688        let repo = self.open_repo()?;
689
690        match git_ref {
691            GitRef::DefaultBranch => {
692                let head = repo.head().map_err(|e| {
693                    Git2DBError::reference("HEAD", format!("Failed to get HEAD: {e}"))
694                })?;
695                head.peel_to_commit().map(|c| c.id()).map_err(|e| {
696                    Git2DBError::reference("HEAD", format!("Failed to peel to commit: {e}"))
697                })
698            }
699            GitRef::Branch(branch_name) => {
700                let branch = repo
701                    .find_branch(branch_name, git2::BranchType::Local)
702                    .or_else(|_| repo.find_branch(branch_name, git2::BranchType::Remote))
703                    .map_err(|e| {
704                        Git2DBError::reference(branch_name, format!("Branch not found: {e}"))
705                    })?;
706                branch.get().peel_to_commit().map(|c| c.id()).map_err(|e| {
707                    Git2DBError::reference(branch_name, format!("Failed to peel to commit: {e}"))
708                })
709            }
710            GitRef::Tag(tag_name) => {
711                let reference = repo
712                    .find_reference(&format!("refs/tags/{tag_name}"))
713                    .map_err(|e| Git2DBError::reference(tag_name, format!("Tag not found: {e}")))?;
714                reference.peel_to_commit().map(|c| c.id()).map_err(|e| {
715                    Git2DBError::reference(tag_name, format!("Failed to peel to commit: {e}"))
716                })
717            }
718            GitRef::Commit(oid) => Ok(*oid),
719            GitRef::Revspec(spec) => {
720                let obj = repo.revparse_single(spec).map_err(|e| {
721                    Git2DBError::reference(spec, format!("Failed to resolve revspec: {e}"))
722                })?;
723                obj.peel_to_commit().map(|c| c.id()).map_err(|e| {
724                    Git2DBError::reference(spec, format!("Failed to peel to commit: {e}"))
725                })
726            }
727        }
728    }
729
730    /// Get information about a specific reference
731    ///
732    /// Returns the reference name and target OID if it exists.
733    ///
734    /// # Examples
735    ///
736    /// ```rust,no_run
737    /// # fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
738    /// if let Some((name, oid)) = repo.ref_info("main")? {
739    ///     println!("Branch {}: {}", name, oid);
740    /// }
741    /// # Ok(())
742    /// # }
743    /// ```
744    pub fn ref_info(&self, ref_name: &str) -> Git2DBResult<Option<(String, Oid)>> {
745        let repo = self.open_repo()?;
746
747        // Try as branch first
748        let ref_path = if ref_name.starts_with("refs/") {
749            ref_name.to_owned()
750        } else if repo.find_branch(ref_name, git2::BranchType::Local).is_ok() {
751            format!("refs/heads/{ref_name}")
752        } else if repo
753            .find_reference(&format!("refs/tags/{ref_name}"))
754            .is_ok()
755        {
756            format!("refs/tags/{ref_name}")
757        } else {
758            ref_name.to_owned()
759        };
760
761        // Find and extract data before returning
762        let result = match repo.find_reference(&ref_path) {
763            Ok(reference) => {
764                let name = reference.shorthand().unwrap_or(ref_name).to_owned();
765                let oid_opt = reference.target();
766                (Some(name), oid_opt)
767            }
768            Err(_) => (None, None),
769        };
770
771        match result {
772            (Some(name), Some(oid)) => Ok(Some((name, oid))),
773            _ => Ok(None),
774        }
775    }
776
777    /// Resolve a revspec string to an OID
778    ///
779    /// Similar to `git rev-parse`
780    ///
781    /// # Examples
782    ///
783    /// ```rust,no_run
784    /// # async fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
785    /// // Resolve complex revspecs
786    /// let oid = repo.resolve_revspec("HEAD~3").await?;
787    /// let oid = repo.resolve_revspec("main@{yesterday}").await?;
788    /// # Ok(())
789    /// # }
790    /// ```
791    pub async fn resolve_revspec(&self, spec: &str) -> Git2DBResult<Oid> {
792        let repo = self.open_repo()?;
793        let obj = repo
794            .revparse_single(spec)
795            .map_err(|e| Git2DBError::reference(spec, format!("Failed to resolve revspec: {e}")))?;
796        Ok(obj.id())
797    }
798
799    /// Get all worktrees managed by the storage driver for this repository
800    ///
801    /// Returns all worktrees that were created using storage drivers for this repository.
802    /// This is useful for discovering existing worktrees managed by overlay2, vfs, etc.
803    ///
804    /// # Examples
805    ///
806    /// ```rust,no_run
807    /// # async fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
808    /// // List all worktrees for this repository
809    /// for worktree in repo.get_worktrees().await? {
810    ///     println!("Worktree: {} (driver: {})", worktree.path().display(), worktree.driver_name());
811    /// }
812    /// # Ok(())
813    /// # }
814    /// ```
815    pub async fn get_worktrees(&self) -> Git2DBResult<Vec<WorktreeHandle>> {
816        let tracked_repo = self.metadata()?;
817
818        // Use pre-loaded storage driver from registry
819        let driver = self.registry.storage_driver().clone();
820
821        // Query storage driver directly for worktrees
822        driver.get_worktrees(&tracked_repo.worktree_path).await
823    }
824
825    /// Get a specific worktree by branch name
826    ///
827    /// Returns the worktree if it exists and is managed by the storage driver.
828    /// This is useful for checking if a specific branch worktree exists.
829    ///
830    /// # Examples
831    ///
832    /// ```rust,no_run
833    /// # async fn example(repo: &git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
834    /// // Check if a worktree for a specific branch exists
835    /// if let Some(worktree) = repo.get_worktree("feature-branch").await? {
836    ///     println!("Found worktree at: {}", worktree.path().display());
837    /// }
838    /// # Ok(())
839    /// # }
840    /// ```
841    pub async fn get_worktree(&self, branch: &str) -> Git2DBResult<Option<WorktreeHandle>> {
842        let tracked_repo = self.metadata()?;
843
844        // Use pre-loaded storage driver from registry
845        let driver = self.registry.storage_driver().clone();
846
847        // Query storage driver directly for specific worktree
848        driver
849            .get_worktree(&tracked_repo.worktree_path, branch)
850            .await
851    }
852
853    /// Create a new worktree using the configured storage driver
854    ///
855    /// This creates a new worktree using the storage driver selected in the configuration.
856    /// On Linux, this will typically use overlay2 for ~80% space savings, while on other
857    /// platforms it will use vfs (plain git worktrees).
858    ///
859    /// The worktree will be created at the specified path and checked out to the given branch/ref.
860    ///
861    /// # Examples
862    ///
863    /// ```rust,ignore
864    /// # async fn example(repo: git2db::RepositoryHandle<'_>) -> Result<(), Box<dyn std::error::Error>> {
865    /// // Create a worktree for a feature branch with overlay2 optimization
866    /// let worktree = repo.create_worktree("/tmp/feature-branch", "feature-branch").await?;
867    /// println!("Created worktree at: {}", worktree.path().display());
868    ///
869    /// // Create worktree at custom path
870    /// let worktree = repo.create_worktree("/tmp/custom-path", "main").await?;
871    /// # Ok(())
872    /// # }
873    /// ```
874    ///
875    /// Fetch LFS files for the worktree
876    ///
877    /// This function tries XET first if initialized (faster for XET-enabled repos),
878    /// then falls back to `git lfs pull` if XET fails or isn't available.
879    pub async fn fetch_lfs_files(repo_path: &Path) -> Git2DBResult<()> {
880        if !repo_path.exists() {
881            return Err(Git2DBError::internal(format!(
882                "Worktree path does not exist: {}",
883                repo_path.display()
884            )));
885        }
886
887        let gitattributes_path = repo_path.join(".gitattributes");
888
889        let uses_lfs = if gitattributes_path.exists() {
890            tokio::fs::read_to_string(&gitattributes_path)
891                .await
892                .map(|content| content.contains("filter=lfs"))
893                .unwrap_or(false)
894        } else {
895            false
896        };
897
898        if !uses_lfs {
899            tracing::debug!("Repository does not use Git LFS, skipping LFS fetch");
900            return Ok(());
901        }
902
903        // Try XET first if initialized (faster for XET-enabled repos)
904        #[cfg(feature = "xet-storage")]
905        if crate::xet_filter::is_initialized() {
906            tracing::info!("XET initialized, attempting XET fetch for LFS files...");
907            match Self::try_xet_lfs_fetch(repo_path).await {
908                Ok(stats) => {
909                    if stats.processed > 0 || stats.skipped > 0 {
910                        tracing::info!(
911                            "XET fetch complete: {} processed, {} skipped, {} failed",
912                            stats.processed,
913                            stats.skipped,
914                            stats.failed
915                        );
916                        if stats.failed == 0 {
917                            return Ok(());
918                        }
919                        // Some files failed, fall through to git-lfs for remaining
920                        tracing::warn!("Some files failed via XET, falling back to git-lfs for remaining files");
921                    }
922                }
923                Err(e) => {
924                    tracing::warn!("XET fetch failed: {}. Falling back to git-lfs...", e);
925                }
926            }
927        }
928
929        // Fallback to git lfs pull
930        Self::run_git_lfs_pull(repo_path).await
931    }
932
933    /// Fetch LFS files for a worktree with progress reporting
934    pub async fn fetch_lfs_files_with_progress(
935        repo_path: &Path,
936        progress: Option<Arc<dyn crate::callback_config::ProgressReporter>>,
937    ) -> Git2DBResult<()> {
938        if !repo_path.exists() {
939            return Err(Git2DBError::internal(format!(
940                "Worktree path does not exist: {}",
941                repo_path.display()
942            )));
943        }
944
945        let gitattributes_path = repo_path.join(".gitattributes");
946
947        let uses_lfs = if gitattributes_path.exists() {
948            tokio::fs::read_to_string(&gitattributes_path)
949                .await
950                .map(|content| content.contains("filter=lfs"))
951                .unwrap_or(false)
952        } else {
953            false
954        };
955
956        if !uses_lfs {
957            tracing::debug!("Repository does not use Git LFS, skipping LFS fetch");
958            return Ok(());
959        }
960
961        // Try XET first if initialized (faster for XET-enabled repos)
962        #[cfg(feature = "xet-storage")]
963        if crate::xet_filter::is_initialized() {
964            tracing::info!("XET initialized, attempting XET fetch for LFS files...");
965            match Self::try_xet_lfs_fetch_with_progress(repo_path, progress.as_ref()).await {
966                Ok(stats) => {
967                    if stats.processed > 0 || stats.skipped > 0 {
968                        tracing::info!(
969                            "XET fetch complete: {} processed, {} skipped, {} failed",
970                            stats.processed,
971                            stats.skipped,
972                            stats.failed
973                        );
974                        if stats.failed == 0 {
975                            return Ok(());
976                        }
977                        tracing::warn!("Some files failed via XET, falling back to git-lfs for remaining files");
978                    }
979                }
980                Err(e) => {
981                    tracing::warn!("XET fetch failed: {}. Falling back to git-lfs...", e);
982                }
983            }
984        }
985
986        // Fallback to git lfs pull
987        Self::run_git_lfs_pull(repo_path).await
988    }
989
990    /// Try to fetch LFS files via XET with progress reporting
991    #[cfg(feature = "xet-storage")]
992    async fn try_xet_lfs_fetch_with_progress(
993        repo_path: &Path,
994        progress: Option<&Arc<dyn crate::callback_config::ProgressReporter>>,
995    ) -> Git2DBResult<crate::lfs::ProcessingStats> {
996        use crate::lfs::LfsStorage;
997
998        let config = crate::xet_filter::get_config().ok_or_else(|| {
999            Git2DBError::internal("BUG: XET filter initialized but FILTER_CONFIG was not set")
1000        })?;
1001
1002        let storage = LfsStorage::new(&config)
1003            .await
1004            .map_err(|e| Git2DBError::internal(format!("Failed to create LFS storage: {e}")))?;
1005
1006        storage
1007            .process_worktree_with_progress(repo_path, progress)
1008            .await
1009    }
1010
1011    /// Try to fetch LFS files via XET
1012    #[cfg(feature = "xet-storage")]
1013    async fn try_xet_lfs_fetch(repo_path: &Path) -> Git2DBResult<crate::lfs::ProcessingStats> {
1014        use crate::lfs::LfsStorage;
1015
1016        // Get the current XET config
1017        let config = crate::xet_filter::get_config().ok_or_else(|| {
1018            Git2DBError::internal("BUG: XET filter initialized but FILTER_CONFIG was not set")
1019        })?;
1020
1021        let storage = LfsStorage::new(&config)
1022            .await
1023            .map_err(|e| Git2DBError::internal(format!("Failed to create LFS storage: {e}")))?;
1024
1025        storage.process_worktree(repo_path).await
1026    }
1027
1028    /// Run git lfs pull as fallback
1029    async fn run_git_lfs_pull(repo_path: &Path) -> Git2DBResult<()> {
1030        use tokio::process::Command;
1031
1032        let lfs_available = Command::new("git")
1033            .args(["lfs", "version"])
1034            .output()
1035            .await
1036            .map(|output| output.status.success())
1037            .unwrap_or(false);
1038
1039        if !lfs_available {
1040            tracing::warn!("git-lfs not installed or not in PATH");
1041            return Err(Git2DBError::internal(
1042                "git-lfs not available. Install with: sudo apt install git-lfs",
1043            ));
1044        }
1045
1046        tracing::info!("📥 Downloading LFS files... (this may take a while for large models)");
1047
1048        let mut child = Command::new("git")
1049            .args(["lfs", "pull"])
1050            .current_dir(repo_path)
1051            .stdout(std::process::Stdio::inherit())
1052            .stderr(std::process::Stdio::inherit())
1053            .spawn()
1054            .map_err(|e| {
1055                Git2DBError::internal(format!(
1056                    "Failed to spawn 'git lfs pull': {e}. Is git-lfs installed?"
1057                ))
1058            })?;
1059
1060        let status = child.wait().await.map_err(|e| {
1061            Git2DBError::internal(format!("Failed to wait for 'git lfs pull': {e}"))
1062        })?;
1063
1064        if !status.success() {
1065            let exit_code = status.code().unwrap_or(-1);
1066            tracing::error!("git lfs pull failed with exit code: {}", exit_code);
1067
1068            let error_msg = match exit_code {
1069                128 => "git lfs pull failed (exit code 128): Authentication failed.\n\
1070                     Check your git credentials or LFS endpoint."
1071                    .to_owned(),
1072                1 => "git lfs pull failed (exit code 1): Network error.\n\
1073                     Check network connectivity and LFS endpoint."
1074                    .to_owned(),
1075                _ => format!(
1076                    "git lfs pull failed (exit code {exit_code}): Unknown error.\n\
1077                     Check logs above for details."
1078                ),
1079            };
1080
1081            return Err(Git2DBError::internal(error_msg));
1082        }
1083
1084        tracing::info!("Successfully fetched LFS files via git-lfs");
1085        Ok(())
1086    }
1087
1088    /// Create a worktree with pathspec-filtered checkout.
1089    ///
1090    /// Only files matching `checkout_paths` prefixes are materialized.
1091    /// Excluded entries get skip-worktree index bits to prevent re-materialization.
1092    ///
1093    /// # Arguments
1094    /// * `worktree_path` - Where to create the worktree (empty = auto-derive)
1095    /// * `branch` - Git ref to checkout
1096    /// * `checkout_paths` - Path prefixes to materialize (e.g., `["backends/cuda130/", "manifest.toml"]`)
1097    pub async fn create_filtered_worktree(
1098        &self,
1099        worktree_path: &Path,
1100        branch: &str,
1101        checkout_paths: Vec<String>,
1102    ) -> Git2DBResult<WorktreeHandle> {
1103        if checkout_paths.is_empty() {
1104            return Err(Git2DBError::configuration(
1105                "checkout_paths must not be empty; use create_worktree() for a full checkout",
1106            ));
1107        }
1108
1109        let tracked_repo = self.metadata()?;
1110
1111        let worktree_path = if worktree_path.as_os_str().is_empty() {
1112            let worktrees_dir = tracked_repo
1113                .worktree_path
1114                .parent()
1115                .ok_or_else(|| Git2DBError::internal("Invalid base repository path"))?
1116                .join("worktrees");
1117            worktrees_dir.join(branch)
1118        } else {
1119            worktree_path.to_path_buf()
1120        };
1121
1122        let driver = self.registry.storage_driver().clone();
1123
1124        info!(
1125            "Creating filtered worktree with {} driver: base={}, path={}, ref={}, paths={:?}",
1126            driver.name(),
1127            tracked_repo.worktree_path.display(),
1128            worktree_path.display(),
1129            branch,
1130            checkout_paths
1131        );
1132
1133        let opts = DriverOpts {
1134            base_repo: tracked_repo.worktree_path.clone(),
1135            worktree_path: worktree_path.clone(),
1136            ref_spec: branch.to_owned(),
1137            progress: None,
1138            checkout_paths: Some(checkout_paths),
1139        };
1140
1141        let result = driver.create_worktree(&opts).await;
1142
1143        match result {
1144            Ok(mut handle) => {
1145                if let Err(e) = Self::fetch_lfs_files(&worktree_path).await {
1146                    tracing::error!(
1147                        "Failed to fetch LFS files for filtered worktree at {}: {}",
1148                        worktree_path.display(),
1149                        e
1150                    );
1151                    tracing::info!("Rolling back worktree creation due to LFS fetch failure");
1152                    if let Err(cleanup_err) = handle.cleanup().await {
1153                        tracing::error!(
1154                            "Failed to cleanup worktree during rollback: {}",
1155                            cleanup_err
1156                        );
1157                    }
1158                    return Err(Git2DBError::internal(format!(
1159                        "Worktree creation failed: LFS fetch error: {e}. Worktree has been rolled back."
1160                    )));
1161                }
1162                Ok(handle)
1163            }
1164            Err(e) => {
1165                tracing::error!(
1166                    "Failed to create filtered worktree at {}: {}",
1167                    worktree_path.display(),
1168                    e
1169                );
1170                if worktree_path.exists() {
1171                    tracing::info!(
1172                        "Cleaning up partial worktree at {}",
1173                        worktree_path.display()
1174                    );
1175                    tokio::fs::remove_dir_all(worktree_path)
1176                        .await
1177                        .unwrap_or_else(|cleanup_err| {
1178                            tracing::warn!("Failed to cleanup partial worktree: {}", cleanup_err);
1179                        });
1180                }
1181                Err(e)
1182            }
1183        }
1184    }
1185
1186    pub async fn create_worktree(
1187        &self,
1188        worktree_path: &Path,
1189        branch: &str,
1190    ) -> Git2DBResult<WorktreeHandle> {
1191        let tracked_repo = self.metadata()?;
1192
1193        // When path is empty, derive from worktrees/{branch} (CLI passes "" to mean "use default")
1194        let worktree_path = if worktree_path.as_os_str().is_empty() {
1195            let worktrees_dir = tracked_repo
1196                .worktree_path
1197                .parent()
1198                .ok_or_else(|| Git2DBError::internal("Invalid base repository path"))?
1199                .join("worktrees");
1200            worktrees_dir.join(branch)
1201        } else {
1202            worktree_path.to_path_buf()
1203        };
1204
1205        // Use pre-loaded storage driver from registry
1206        let driver = self.registry.storage_driver().clone();
1207
1208        info!(
1209            "Creating worktree with {} driver: base={}, path={}, ref={}",
1210            driver.name(),
1211            tracked_repo.worktree_path.display(),
1212            worktree_path.display(),
1213            branch
1214        );
1215
1216        // Create driver options
1217        let opts = DriverOpts {
1218            base_repo: tracked_repo.worktree_path.clone(),
1219            worktree_path: worktree_path.clone(),
1220            ref_spec: branch.to_owned(),
1221            progress: None,
1222            checkout_paths: None,
1223        };
1224
1225        // Create worktree using driver
1226        let result = driver.create_worktree(&opts).await;
1227
1228        match &result {
1229            Ok(_handle) => {
1230                // Already logged above
1231            }
1232            Err(e) => {
1233                tracing::error!(
1234                    "Failed to create worktree at {}: {}",
1235                    worktree_path.display(),
1236                    e
1237                );
1238
1239                // Provide helpful hints
1240                #[cfg(feature = "overlayfs")]
1241                {
1242                    if driver.name() == "overlay2" {
1243                        tracing::error!(
1244                            "Hint: Install fuse-overlayfs:\n  \
1245                             sudo apt install fuse-overlayfs\n  \
1246                             OR try a different driver like 'vfs'"
1247                        );
1248                    }
1249                }
1250            }
1251        }
1252
1253        match result {
1254            Ok(mut handle) => {
1255                if let Err(e) = Self::fetch_lfs_files(&worktree_path).await {
1256                    tracing::error!(
1257                        "Failed to fetch LFS files for worktree at {}: {}",
1258                        worktree_path.display(),
1259                        e
1260                    );
1261                    tracing::info!("Rolling back worktree creation due to LFS fetch failure");
1262
1263                    if let Err(cleanup_err) = handle.cleanup().await {
1264                        tracing::error!(
1265                            "Failed to cleanup worktree during rollback: {}",
1266                            cleanup_err
1267                        );
1268                    }
1269
1270                    return Err(Git2DBError::internal(format!(
1271                        "Worktree creation failed: LFS fetch error: {e}. Worktree has been rolled back."
1272                    )));
1273                }
1274
1275                Ok(handle)
1276            }
1277            Err(e) => {
1278                tracing::error!(
1279                    "Failed to create worktree at {}: {}",
1280                    worktree_path.display(),
1281                    e
1282                );
1283
1284                if worktree_path.exists() {
1285                    tracing::info!(
1286                        "Cleaning up partial worktree at {}",
1287                        worktree_path.display()
1288                    );
1289                    tokio::fs::remove_dir_all(worktree_path)
1290                        .await
1291                        .unwrap_or_else(|cleanup_err| {
1292                            tracing::warn!("Failed to cleanup partial worktree: {}", cleanup_err);
1293                        });
1294                }
1295
1296                Err(e)
1297            }
1298        }
1299    }
1300}
1301
1302/// Repository status information
1303#[derive(Debug, Clone)]
1304pub struct RepositoryStatus {
1305    pub branch: Option<String>,
1306    pub head: Option<Oid>,
1307    pub ahead: usize,
1308    pub behind: usize,
1309    pub is_clean: bool,
1310    pub modified_files: Vec<PathBuf>,
1311}