Skip to main content

endringer_git/
backend.rs

1//! [`GitBackend`] — wraps `gix::ThreadSafeRepository` and implements [`VcsBackend`].
2
3use std::time::SystemTime;
4
5use endringer_core::error::{anyhow_to_backend, Error as CrateError, NotFoundKind, Result};
6use endringer_core::backend::VcsBackend;
7use endringer_core::types::{
8    AheadBehind, BlameEntry, BranchInfo, BranchTrackingInfo, CommitId, CommitInfo,
9    ConflictSummary, DiffSummary, OperationState, RefInfo, RefKind, RemoteInfo,
10    RepositoryInfo, SortOrder, StashEntry, StatusDigest, SubmoduleInfo, TagInfo,
11    TreeEntry, WorktreeInfo, WorktreeStatus,
12};
13
14use crate::{blame, branch, commit, conflict, diff, graph, info, object, operation,
15            refs, stash, status, submodule, tag, tree, worktree};
16
17/// Git backend.
18///
19/// Uses [`gix::ThreadSafeRepository`] so the struct is natively `Send + Sync`
20/// without any mutex. Each method obtains a cheap thread-local repository view
21/// via [`gix::ThreadSafeRepository::to_thread_local`], eliminating serialization
22/// under concurrent async load.
23pub struct GitBackend {
24    inner: gix::ThreadSafeRepository,
25}
26
27impl GitBackend {
28    /// Opens or discovers a Git repository at or above `path`.
29    ///
30    /// Traverses parent directories until it finds a `.git` directory (or a
31    /// bare repository), so callers may pass any subdirectory of the worktree.
32    pub fn open(path: &std::path::Path) -> anyhow::Result<Self> {
33        let inner = gix::discover(path)?.into_sync();
34        Ok(GitBackend { inner })
35    }
36}
37
38/// Obtains a thread-local [`gix::Repository`] view from the shared handle.
39///
40/// This is a zero-copy operation: no re-opening of files, no locking.
41macro_rules! repo {
42    ($self:expr) => {
43        $self.inner.to_thread_local()
44    };
45}
46
47/// Converts an `anyhow::Result` to `endringer_core::Result` at the dispatch boundary.
48macro_rules! be {
49    ($e:expr) => {
50        $e.map_err(anyhow_to_backend)
51    };
52}
53
54impl VcsBackend for GitBackend {
55    fn status_digest(&self) -> Result<StatusDigest> {
56        be!(commit::status_digest(&repo!(self)))
57    }
58
59    fn local_branches(&self) -> Result<Vec<BranchInfo>> {
60        be!(branch::local_branches(&repo!(self)))
61    }
62
63    fn remote_branches(&self) -> Result<Vec<BranchInfo>> {
64        be!(branch::remote_branches(&repo!(self)))
65    }
66
67    fn list_commits(&self) -> Result<Vec<CommitInfo>> {
68        be!(branch::list_commits(&repo!(self)))
69    }
70
71    fn list_commits_sorted(&self, order: SortOrder) -> Result<Vec<CommitInfo>> {
72        be!(branch::list_commits_sorted(&repo!(self), order))
73    }
74
75    fn log_since(&self, since: SystemTime, until: SystemTime) -> Result<Vec<CommitInfo>> {
76        be!(branch::log_since(&repo!(self), since, until))
77    }
78
79    fn find_commit(&self, id: &CommitId) -> Result<CommitInfo> {
80        branch::find_commit(&repo!(self), id).map_err(|e| {
81            let msg = e.to_string();
82            if msg.contains("not found") || msg.contains("commit '") && msg.contains("not found") {
83                CrateError::NotFound { kind: NotFoundKind::Commit, name: id.to_string() }
84            } else if msg.contains("not a commit") {
85                CrateError::NotACommit { id: id.clone() }
86            } else {
87                anyhow_to_backend(e)
88            }
89        })
90    }
91
92    fn list_tags(&self) -> Result<Vec<TagInfo>> {
93        be!(tag::list_tags(&repo!(self)))
94    }
95
96    fn list_tags_sorted(&self, order: SortOrder) -> Result<Vec<TagInfo>> {
97        be!(tag::list_tags_sorted(&repo!(self), order))
98    }
99
100    fn create_tag(&self, name: &str) -> Result<()> {
101        be!(tag::create_tag(&repo!(self), name))
102    }
103
104    fn create_annotated_tag(&self, name: &str, message: &str) -> Result<()> {
105        be!(tag::create_annotated_tag(&repo!(self), name, message))
106    }
107
108    fn delete_tag(&self, name: &str) -> Result<()> {
109        be!(tag::delete_tag(&repo!(self), name))
110    }
111
112    fn diff(&self, from: &CommitId, to: &CommitId) -> Result<DiffSummary> {
113        be!(diff::diff(&repo!(self), from, to))
114    }
115
116    fn remote_url(&self, name: &str) -> Result<Option<String>> {
117        let repo = repo!(self);
118        let remote = match repo.find_remote(name) {
119            Ok(r) => r,
120            Err(e) => {
121                let msg = e.to_string();
122                // gix reports "The remote named \"X\" did not exist" for
123                // unknown remotes — treat as absent, not an error.
124                if msg.contains("did not exist")
125                    || msg.contains("not found")
126                    || msg.contains("does not exist")
127                {
128                    return Ok(None);
129                }
130                return Err(anyhow_to_backend(anyhow::anyhow!(msg)));
131            }
132        };
133        let url = remote.url(gix::remote::Direction::Fetch);
134        Ok(url.map(|u| u.to_bstring().to_string()))
135    }
136
137    fn is_dirty(&self) -> Result<bool> {
138        be!(status::is_dirty(&repo!(self)))
139    }
140
141    fn merge_base(&self, a: &CommitId, b: &CommitId) -> Result<Option<CommitId>> {
142        be!(graph::merge_base(&repo!(self), a, b))
143    }
144
145    fn is_ancestor(&self, candidate: &CommitId, descendant: &CommitId) -> Result<bool> {
146        be!(graph::is_ancestor(&repo!(self), candidate, descendant))
147    }
148
149    fn ahead_behind(&self, local: &CommitId, upstream: &CommitId) -> Result<AheadBehind> {
150        be!(graph::ahead_behind(&repo!(self), local, upstream))
151    }
152
153    fn branch_ahead_behind(&self, branch: &str) -> Result<Option<AheadBehind>> {
154        be!(graph::branch_ahead_behind(&repo!(self), branch))
155    }
156
157    fn repository_info(&self) -> Result<RepositoryInfo> {
158        be!(info::repository_info(&repo!(self), endringer_core::types::BackendKind::Git))
159    }
160
161    fn branch_tracking(&self, branch: &str) -> Result<BranchTrackingInfo> {
162        be!(branch::branch_tracking(&repo!(self), branch))
163    }
164
165    fn local_branch_tracking(&self) -> Result<Vec<BranchTrackingInfo>> {
166        be!(branch::local_branch_tracking(&repo!(self)))
167    }
168
169    fn is_merged_into(&self, b: &str, target: &str) -> Result<bool> {
170        be!(branch::is_merged_into(&repo!(self), b, target))
171    }
172
173    fn blame(&self, path: &std::path::Path) -> Result<Vec<BlameEntry>> {
174        be!(blame::blame(&repo!(self), path))
175    }
176
177    fn worktree_status(&self) -> Result<WorktreeStatus> {
178        be!(status::worktree_status(&repo!(self)))
179    }
180
181    fn file_at_commit(&self, path: &std::path::Path, commit_id: &CommitId) -> Result<Vec<u8>> {
182        object::file_at_commit(&repo!(self), path, commit_id).map_err(|e| {
183            let msg = e.to_string();
184            if msg.contains("not found") || msg.contains("does not exist") {
185                CrateError::PathNotFound {
186                    path: path.to_path_buf(),
187                    commit: Some(commit_id.clone()),
188                }
189            } else {
190                anyhow_to_backend(e)
191            }
192        })
193    }
194
195    fn submodules(&self) -> Result<Vec<SubmoduleInfo>> {
196        be!(submodule::submodules(&repo!(self)))
197    }
198
199    fn stash_entries(&self) -> Result<Vec<StashEntry>> {
200        be!(stash::stash_entries(&repo!(self)))
201    }
202
203    fn worktrees(&self) -> Result<Vec<WorktreeInfo>> {
204        be!(worktree::worktrees(&repo!(self)))
205    }
206
207    fn operation_state(&self) -> Result<OperationState> {
208        be!(operation::operation_state(repo!(self).git_dir()))
209    }
210
211    fn unmerged_paths(&self) -> Result<Vec<std::path::PathBuf>> {
212        be!(conflict::unmerged_paths(&repo!(self)))
213    }
214
215    fn conflict_summary(&self) -> Result<ConflictSummary> {
216        be!(conflict::conflict_summary(&repo!(self)))
217    }
218
219    fn blame_at(&self, path: &std::path::Path, commit_id: &CommitId) -> Result<Vec<BlameEntry>> {
220        be!(blame::blame_at(&repo!(self), path, commit_id))
221    }
222
223    fn tree_at_commit(&self, commit_id: &CommitId) -> Result<Vec<TreeEntry>> {
224        be!(tree::tree_at_commit(&repo!(self), commit_id))
225    }
226
227    fn tree_at_path(&self, commit_id: &CommitId, path: &std::path::Path) -> Result<Vec<TreeEntry>> {
228        be!(tree::tree_at_path(&repo!(self), commit_id, path))
229    }
230
231    fn remotes(&self) -> Result<Vec<RemoteInfo>> {
232        be!(refs::remotes(&repo!(self)))
233    }
234
235    fn references(&self) -> Result<Vec<RefInfo>> {
236        be!(refs::references(&repo!(self)))
237    }
238
239    fn references_by_kind(&self, kind: RefKind) -> Result<Vec<RefInfo>> {
240        be!(refs::references_by_kind(&repo!(self), kind))
241    }
242}