1use 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
17pub struct RepositoryHandle<'a> {
22 registry: &'a Git2DB,
23 repo_id: RepoId,
24}
25
26impl<'a> RepositoryHandle<'a> {
27 pub(crate) fn new(registry: &'a Git2DB, repo_id: RepoId) -> Self {
29 Self { registry, repo_id }
30 }
31
32 pub fn id(&self) -> &RepoId {
34 &self.repo_id
35 }
36
37 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 pub fn name(&self) -> Git2DBResult<Option<&str>> {
49 Ok(self.metadata()?.name.as_deref())
50 }
51
52 pub fn worktree(&self) -> Git2DBResult<&Path> {
54 Ok(&self.metadata()?.worktree_path)
55 }
56
57 pub fn url(&self) -> Git2DBResult<&str> {
59 Ok(&self.metadata()?.url)
60 }
61
62 pub fn tracking_ref(&self) -> Git2DBResult<&GitRef> {
64 Ok(&self.metadata()?.tracking_ref)
65 }
66
67 pub async fn resolve_worktree_path(&self) -> Git2DBResult<PathBuf> {
74 let base_path = self.worktree()?.to_path_buf();
75
76 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 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 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 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 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 pub fn remote(&self) -> RemoteManager<'a> {
162 RemoteManager::new(self.registry, self.repo_id.clone())
163 }
164
165 pub fn branch(&self) -> BranchManager<'a> {
190 BranchManager::new(self.registry, self.repo_id.clone())
191 }
192
193 pub fn staging(&self) -> StageManager<'a> {
213 StageManager::new(self.registry, self.repo_id.clone())
214 }
215
216 pub async fn commit(&self, message: &str) -> Git2DBResult<Oid> {
246 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 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 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 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 let mut index = repo
308 .index()
309 .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?;
310
311 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 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 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 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 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 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 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 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 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, behind: 0, is_clean,
419 modified_files,
420 })
421 })
422 .await
423 .map_err(|e| Git2DBError::internal(format!("Task join error: {e}")))?
424 }
425
426 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 let git_manager = crate::manager::GitManager::global();
473 let sig = git_manager.create_signature(None, None)?;
474
475 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 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 let (analysis, _preference) = repo
493 .merge_analysis(&[&source_annotated])
494 .map_err(|e| Git2DBError::internal(format!("Failed to analyze merge: {e}")))?;
495
496 if analysis.contains(git2::MergeAnalysis::ANALYSIS_UP_TO_DATE) {
498 return Err(Git2DBError::invalid_operation("Already up to date"));
499 }
500
501 if analysis.contains(git2::MergeAnalysis::ANALYSIS_FASTFORWARD) {
503 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 repo.merge(&[&source_annotated], None, None)
516 .map_err(|e| Git2DBError::internal(format!("Failed to perform merge: {e}")))?;
517
518 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 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 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 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 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 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 pub fn default_branch(&self) -> Git2DBResult<String> {
624 let repo = self.open_repo()?;
625
626 if let Ok(head_ref) = repo.head() {
628 if let Some(name) = head_ref.symbolic_target() {
629 if let Some(branch_name) = name.strip_prefix("refs/heads/") {
631 return Ok(branch_name.to_owned());
632 }
633 }
634 }
635
636 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 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 Ok("main".to_owned())
663 }
664
665 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 pub fn ref_info(&self, ref_name: &str) -> Git2DBResult<Option<(String, Oid)>> {
745 let repo = self.open_repo()?;
746
747 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 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 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 pub async fn get_worktrees(&self) -> Git2DBResult<Vec<WorktreeHandle>> {
816 let tracked_repo = self.metadata()?;
817
818 let driver = self.registry.storage_driver().clone();
820
821 driver.get_worktrees(&tracked_repo.worktree_path).await
823 }
824
825 pub async fn get_worktree(&self, branch: &str) -> Git2DBResult<Option<WorktreeHandle>> {
842 let tracked_repo = self.metadata()?;
843
844 let driver = self.registry.storage_driver().clone();
846
847 driver
849 .get_worktree(&tracked_repo.worktree_path, branch)
850 .await
851 }
852
853 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 #[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 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 Self::run_git_lfs_pull(repo_path).await
931 }
932
933 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 #[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 Self::run_git_lfs_pull(repo_path).await
988 }
989
990 #[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 #[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 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 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 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 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 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 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 let result = driver.create_worktree(&opts).await;
1227
1228 match &result {
1229 Ok(_handle) => {
1230 }
1232 Err(e) => {
1233 tracing::error!(
1234 "Failed to create worktree at {}: {}",
1235 worktree_path.display(),
1236 e
1237 );
1238
1239 #[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#[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}