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