1use 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#[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
49pub struct DriverOpts {
51 pub base_repo: PathBuf,
53
54 pub worktree_path: PathBuf,
56
57 pub ref_spec: String,
60
61 pub progress: Option<Arc<dyn crate::callback_config::ProgressReporter>>,
63
64 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#[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#[derive(Clone)]
120pub struct DriverFactory {
121 name: &'static str,
123
124 factory: fn() -> Box<dyn Driver>,
126}
127
128impl DriverFactory {
129 pub const fn new(name: &'static str, factory: fn() -> Box<dyn Driver>) -> Self {
131 Self { name, factory }
132 }
133
134 pub fn get_driver(&self) -> Arc<dyn Driver> {
136 let boxed: Box<dyn Driver> = (self.factory)();
139 Arc::from(boxed)
140 }
141
142 pub fn name(&self) -> &'static str {
144 self.name
145 }
146}
147
148inventory::collect!(DriverFactory);
150
151#[async_trait]
156pub trait Driver: Send + Sync {
157 fn name(&self) -> &'static str;
159
160 fn is_available(&self) -> bool;
162
163 async fn create_worktree(&self, opts: &DriverOpts) -> Git2DBResult<WorktreeHandle>;
168
169 async fn get_worktrees(&self, base_repo: &Path) -> Git2DBResult<Vec<WorktreeHandle>>;
174
175 async fn get_worktree(
180 &self,
181 base_repo: &Path,
182 branch: &str,
183 ) -> Git2DBResult<Option<WorktreeHandle>>;
184}
185
186pub type AsyncCleanupFn =
188 Box<dyn FnOnce() -> Pin<Box<dyn Future<Output = Git2DBResult<()>> + Send>> + Send>;
189
190pub struct WorktreeHandle {
195 pub path: PathBuf,
197
198 pub driver_name: String,
200
201 cleanup: Option<Arc<Mutex<Option<AsyncCleanupFn>>>>,
203
204 repo: Option<git2::Repository>,
206
207 contained_fs: OnceCell<Arc<dyn hyprstream_containedfs::ContainedFs>>,
209}
210
211impl WorktreeHandle {
212 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 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 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 pub fn driver_name(&self) -> &str {
252 &self.driver_name
253 }
254
255 pub fn path(&self) -> &Path {
257 &self.path
258 }
259
260 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 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 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 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 pub fn is_valid(&self) -> bool {
299 self.path.exists() && self.path.join(".git").exists() && self.open_repository().is_ok()
300 }
301
302 pub fn is_dirty(&mut self) -> Git2DBResult<bool> {
304 let repo = self.get_repository()?;
305 let mut opts = git2::StatusOptions::new();
306 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 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(), }
322 }
323
324 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 pub async fn commit(&mut self, message: &str) -> Git2DBResult<Oid> {
354 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 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 let mut index = repo
391 .index()
392 .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?;
393
394 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 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 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 pub async fn amend(&mut self, message: Option<&str>) -> Git2DBResult<Oid> {
446 let repo = self.open_repository()?;
447
448 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 let mut index = repo
459 .index()
460 .map_err(|e| Git2DBError::internal(format!("Failed to get index: {e}")))?;
461
462 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 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 pub async fn merge(&mut self, branch: &str, ff_only: bool, no_ff: bool) -> Git2DBResult<Oid> {
503 let repo = self.open_repository()?;
504
505 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 let (merge_analysis, _) = repo
524 .merge_analysis(&[&annotated_commit])
525 .map_err(|e| Git2DBError::internal(format!("Merge analysis failed: {e}")))?;
526
527 if merge_analysis.is_up_to_date() {
529 return Ok(branch_commit.id());
530 }
531
532 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 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 repo.merge(&[&annotated_commit], None, None)
557 .map_err(|e| Git2DBError::internal(format!("Merge failed: {e}")))?;
558
559 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 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 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 let (ahead, behind) = if let (Some(branch_name), Some(local_oid)) = (&branch, head_oid) {
649 if let Ok(local_branch) = repo.find_branch(branch_name, git2::BranchType::Local) {
651 if let Ok(upstream_branch) = local_branch.upstream() {
653 if let Some(upstream_oid) = upstream_branch.get().target() {
654 match repo.graph_ahead_behind(local_oid, upstream_oid) {
656 Ok((a, b)) => (a, b),
657 Err(_) => {
658 (0, 0)
660 }
661 }
662 } else {
663 (0, 0)
664 }
665 } else {
666 (0, 0)
668 }
669 } else {
670 (0, 0)
672 }
673 } else {
674 (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 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 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 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 repo.set_head_detached(oid)
761 .map_err(|e| Git2DBError::internal(format!("Failed to update HEAD: {e}")))?;
762
763 Ok(())
764 }
765
766 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 pub async fn pull(&mut self, remote: Option<&str>) -> Git2DBResult<()> {
812 self.fetch(remote).await?;
814
815 let repo = self.open_repository()?;
816 let remote_name = remote.unwrap_or("origin");
817
818 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 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 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 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 repo.merge(&[&annotated_commit], None, None)
865 .map_err(|e| Git2DBError::internal(format!("Merge failed: {e}")))?;
866
867 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 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 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 pub async fn update(&mut self) -> Git2DBResult<()> {
962 self.fetch(None).await?;
963
964 let repo = self.open_repository()?;
965
966 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 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 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 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 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 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 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 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 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#[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}