1use anyhow::Result;
2use collections::HashMap;
3use git2::{BranchType, ErrorCode};
4use parking_lot::Mutex;
5use rpc::proto;
6use serde_derive::{Deserialize, Serialize};
7use std::{
8 cmp::Ordering,
9 ffi::OsStr,
10 os::unix::prelude::OsStrExt,
11 path::{Component, Path, PathBuf},
12 sync::Arc,
13};
14use sum_tree::{MapSeekTarget, TreeMap};
15use util::ResultExt;
16
17pub use git2::Repository as LibGitRepository;
18
19#[derive(Clone, Debug, Hash, PartialEq)]
20pub struct Branch {
21 pub name: Box<str>,
22 /// Timestamp of most recent commit, normalized to Unix Epoch format.
23 pub unix_timestamp: Option<i64>,
24}
25#[async_trait::async_trait]
26pub trait GitRepository: Send {
27 fn reload_index(&self);
28
29 fn load_index_text(&self, relative_file_path: &Path) -> Option<String>;
30
31 fn branch_name(&self) -> Option<String>;
32
33 fn statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>>;
34
35 fn status(&self, path: &RepoPath) -> Result<Option<GitFileStatus>>;
36
37 fn branches(&self) -> Result<Vec<Branch>> {
38 Ok(vec![])
39 }
40 fn change_branch(&self, _: &str) -> Result<()> {
41 Ok(())
42 }
43 fn create_branch(&self, _: &str) -> Result<()> {
44 Ok(())
45 }
46}
47
48impl std::fmt::Debug for dyn GitRepository {
49 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50 f.debug_struct("dyn GitRepository<...>").finish()
51 }
52}
53
54#[async_trait::async_trait]
55impl GitRepository for LibGitRepository {
56 fn reload_index(&self) {
57 if let Ok(mut index) = self.index() {
58 _ = index.read(false);
59 }
60 }
61
62 fn load_index_text(&self, relative_file_path: &Path) -> Option<String> {
63 fn logic(repo: &LibGitRepository, relative_file_path: &Path) -> Result<Option<String>> {
64 const STAGE_NORMAL: i32 = 0;
65 let index = repo.index()?;
66
67 // This check is required because index.get_path() unwraps internally :(
68 check_path_to_repo_path_errors(relative_file_path)?;
69
70 let oid = match index.get_path(&relative_file_path, STAGE_NORMAL) {
71 Some(entry) => entry.id,
72 None => return Ok(None),
73 };
74
75 let content = repo.find_blob(oid)?.content().to_owned();
76 Ok(Some(String::from_utf8(content)?))
77 }
78
79 match logic(&self, relative_file_path) {
80 Ok(value) => return value,
81 Err(err) => log::error!("Error loading head text: {:?}", err),
82 }
83 None
84 }
85
86 fn branch_name(&self) -> Option<String> {
87 let head = self.head().log_err()?;
88 let branch = String::from_utf8_lossy(head.shorthand_bytes());
89 Some(branch.to_string())
90 }
91
92 fn statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>> {
93 let statuses = self.statuses(None).log_err()?;
94
95 let mut map = TreeMap::default();
96
97 for status in statuses
98 .iter()
99 .filter(|status| !status.status().contains(git2::Status::IGNORED))
100 {
101 let path = RepoPath(PathBuf::from(OsStr::from_bytes(status.path_bytes())));
102 let Some(status) = read_status(status.status()) else {
103 continue
104 };
105
106 map.insert(path, status)
107 }
108
109 Some(map)
110 }
111
112 fn status(&self, path: &RepoPath) -> Result<Option<GitFileStatus>> {
113 let status = self.status_file(path);
114 match status {
115 Ok(status) => Ok(read_status(status)),
116 Err(e) => {
117 if e.code() == ErrorCode::NotFound {
118 Ok(None)
119 } else {
120 Err(e.into())
121 }
122 }
123 }
124 }
125 fn branches(&self) -> Result<Vec<Branch>> {
126 let local_branches = self.branches(Some(BranchType::Local))?;
127 let valid_branches = local_branches
128 .filter_map(|branch| {
129 branch.ok().and_then(|(branch, _)| {
130 let name = branch.name().ok().flatten().map(Box::from)?;
131 let timestamp = branch.get().peel_to_commit().ok()?.time();
132 let unix_timestamp = timestamp.seconds();
133 let timezone_offset = timestamp.offset_minutes();
134 let utc_offset =
135 time::UtcOffset::from_whole_seconds(timezone_offset * 60).ok()?;
136 let unix_timestamp =
137 time::OffsetDateTime::from_unix_timestamp(unix_timestamp).ok()?;
138 Some(Branch {
139 name,
140 unix_timestamp: Some(unix_timestamp.to_offset(utc_offset).unix_timestamp()),
141 })
142 })
143 })
144 .collect();
145 Ok(valid_branches)
146 }
147 fn change_branch(&self, name: &str) -> Result<()> {
148 let revision = self.find_branch(name, BranchType::Local)?;
149 let revision = revision.get();
150 let as_tree = revision.peel_to_tree()?;
151 self.checkout_tree(as_tree.as_object(), None)?;
152 self.set_head(
153 revision
154 .name()
155 .ok_or_else(|| anyhow::anyhow!("Branch name could not be retrieved"))?,
156 )?;
157 Ok(())
158 }
159 fn create_branch(&self, name: &str) -> Result<()> {
160 let current_commit = self.head()?.peel_to_commit()?;
161 self.branch(name, ¤t_commit, false)?;
162
163 Ok(())
164 }
165}
166
167fn read_status(status: git2::Status) -> Option<GitFileStatus> {
168 if status.contains(git2::Status::CONFLICTED) {
169 Some(GitFileStatus::Conflict)
170 } else if status.intersects(
171 git2::Status::WT_MODIFIED
172 | git2::Status::WT_RENAMED
173 | git2::Status::INDEX_MODIFIED
174 | git2::Status::INDEX_RENAMED,
175 ) {
176 Some(GitFileStatus::Modified)
177 } else if status.intersects(git2::Status::WT_NEW | git2::Status::INDEX_NEW) {
178 Some(GitFileStatus::Added)
179 } else {
180 None
181 }
182}
183
184#[derive(Debug, Clone, Default)]
185pub struct FakeGitRepository {
186 state: Arc<Mutex<FakeGitRepositoryState>>,
187}
188
189#[derive(Debug, Clone, Default)]
190pub struct FakeGitRepositoryState {
191 pub index_contents: HashMap<PathBuf, String>,
192 pub worktree_statuses: HashMap<RepoPath, GitFileStatus>,
193 pub branch_name: Option<String>,
194}
195
196impl FakeGitRepository {
197 pub fn open(state: Arc<Mutex<FakeGitRepositoryState>>) -> Arc<Mutex<dyn GitRepository>> {
198 Arc::new(Mutex::new(FakeGitRepository { state }))
199 }
200}
201
202#[async_trait::async_trait]
203impl GitRepository for FakeGitRepository {
204 fn reload_index(&self) {}
205
206 fn load_index_text(&self, path: &Path) -> Option<String> {
207 let state = self.state.lock();
208 state.index_contents.get(path).cloned()
209 }
210
211 fn branch_name(&self) -> Option<String> {
212 let state = self.state.lock();
213 state.branch_name.clone()
214 }
215
216 fn statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>> {
217 let state = self.state.lock();
218 let mut map = TreeMap::default();
219 for (repo_path, status) in state.worktree_statuses.iter() {
220 map.insert(repo_path.to_owned(), status.to_owned());
221 }
222 Some(map)
223 }
224
225 fn status(&self, path: &RepoPath) -> Result<Option<GitFileStatus>> {
226 let state = self.state.lock();
227 Ok(state.worktree_statuses.get(path).cloned())
228 }
229}
230
231fn check_path_to_repo_path_errors(relative_file_path: &Path) -> Result<()> {
232 match relative_file_path.components().next() {
233 None => anyhow::bail!("repo path should not be empty"),
234 Some(Component::Prefix(_)) => anyhow::bail!(
235 "repo path `{}` should be relative, not a windows prefix",
236 relative_file_path.to_string_lossy()
237 ),
238 Some(Component::RootDir) => {
239 anyhow::bail!(
240 "repo path `{}` should be relative",
241 relative_file_path.to_string_lossy()
242 )
243 }
244 Some(Component::CurDir) => {
245 anyhow::bail!(
246 "repo path `{}` should not start with `.`",
247 relative_file_path.to_string_lossy()
248 )
249 }
250 Some(Component::ParentDir) => {
251 anyhow::bail!(
252 "repo path `{}` should not start with `..`",
253 relative_file_path.to_string_lossy()
254 )
255 }
256 _ => Ok(()),
257 }
258}
259
260#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
261pub enum GitFileStatus {
262 Added,
263 Modified,
264 Conflict,
265}
266
267impl GitFileStatus {
268 pub fn merge(
269 this: Option<GitFileStatus>,
270 other: Option<GitFileStatus>,
271 prefer_other: bool,
272 ) -> Option<GitFileStatus> {
273 if prefer_other {
274 return other;
275 } else {
276 match (this, other) {
277 (Some(GitFileStatus::Conflict), _) | (_, Some(GitFileStatus::Conflict)) => {
278 Some(GitFileStatus::Conflict)
279 }
280 (Some(GitFileStatus::Modified), _) | (_, Some(GitFileStatus::Modified)) => {
281 Some(GitFileStatus::Modified)
282 }
283 (Some(GitFileStatus::Added), _) | (_, Some(GitFileStatus::Added)) => {
284 Some(GitFileStatus::Added)
285 }
286 _ => None,
287 }
288 }
289 }
290
291 pub fn from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
292 git_status.and_then(|status| {
293 proto::GitStatus::from_i32(status).map(|status| match status {
294 proto::GitStatus::Added => GitFileStatus::Added,
295 proto::GitStatus::Modified => GitFileStatus::Modified,
296 proto::GitStatus::Conflict => GitFileStatus::Conflict,
297 })
298 })
299 }
300
301 pub fn to_proto(self) -> i32 {
302 match self {
303 GitFileStatus::Added => proto::GitStatus::Added as i32,
304 GitFileStatus::Modified => proto::GitStatus::Modified as i32,
305 GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
306 }
307 }
308}
309
310#[derive(Clone, Debug, Ord, Hash, PartialOrd, Eq, PartialEq)]
311pub struct RepoPath(pub PathBuf);
312
313impl RepoPath {
314 pub fn new(path: PathBuf) -> Self {
315 debug_assert!(path.is_relative(), "Repo paths must be relative");
316
317 RepoPath(path)
318 }
319}
320
321impl From<&Path> for RepoPath {
322 fn from(value: &Path) -> Self {
323 RepoPath::new(value.to_path_buf())
324 }
325}
326
327impl From<PathBuf> for RepoPath {
328 fn from(value: PathBuf) -> Self {
329 RepoPath::new(value)
330 }
331}
332
333impl Default for RepoPath {
334 fn default() -> Self {
335 RepoPath(PathBuf::new())
336 }
337}
338
339impl AsRef<Path> for RepoPath {
340 fn as_ref(&self) -> &Path {
341 self.0.as_ref()
342 }
343}
344
345impl std::ops::Deref for RepoPath {
346 type Target = PathBuf;
347
348 fn deref(&self) -> &Self::Target {
349 &self.0
350 }
351}
352
353#[derive(Debug)]
354pub struct RepoPathDescendants<'a>(pub &'a Path);
355
356impl<'a> MapSeekTarget<RepoPath> for RepoPathDescendants<'a> {
357 fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
358 if key.starts_with(&self.0) {
359 Ordering::Greater
360 } else {
361 self.0.cmp(key)
362 }
363 }
364}