1use anyhow::Result;
2use collections::HashMap;
3use git2::{BranchType, StatusShow};
4use parking_lot::Mutex;
5use serde_derive::{Deserialize, Serialize};
6use std::{
7 cmp::Ordering,
8 ffi::OsStr,
9 os::unix::prelude::OsStrExt,
10 path::{Component, Path, PathBuf},
11 sync::Arc,
12 time::SystemTime,
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
26#[async_trait::async_trait]
27pub trait GitRepository: Send {
28 fn reload_index(&self);
29 fn load_index_text(&self, relative_file_path: &Path) -> Option<String>;
30 fn branch_name(&self) -> Option<String>;
31
32 /// Get the statuses of all of the files in the index that start with the given
33 /// path and have changes with resepect to the HEAD commit. This is fast because
34 /// the index stores hashes of trees, so that unchanged directories can be skipped.
35 fn staged_statuses(&self, path_prefix: &Path) -> TreeMap<RepoPath, GitFileStatus>;
36
37 /// Get the status of a given file in the working directory with respect to
38 /// the index. In the common case, when there are no changes, this only requires
39 /// an index lookup. The index stores the mtime of each file when it was added,
40 /// so there's no work to do if the mtime matches.
41 fn unstaged_status(&self, path: &RepoPath, mtime: SystemTime) -> Option<GitFileStatus>;
42
43 /// Get the status of a given file in the working directory with respect to
44 /// the HEAD commit. In the common case, when there are no changes, this only
45 /// requires an index lookup and blob comparison between the index and the HEAD
46 /// commit. The index stores the mtime of each file when it was added, so there's
47 /// no need to consider the working directory file if the mtime matches.
48 fn status(&self, path: &RepoPath, mtime: SystemTime) -> Option<GitFileStatus>;
49
50 fn branches(&self) -> Result<Vec<Branch>>;
51 fn change_branch(&self, _: &str) -> Result<()>;
52 fn create_branch(&self, _: &str) -> Result<()>;
53}
54
55impl std::fmt::Debug for dyn GitRepository {
56 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
57 f.debug_struct("dyn GitRepository<...>").finish()
58 }
59}
60
61impl GitRepository for LibGitRepository {
62 fn reload_index(&self) {
63 if let Ok(mut index) = self.index() {
64 _ = index.read(false);
65 }
66 }
67
68 fn load_index_text(&self, relative_file_path: &Path) -> Option<String> {
69 fn logic(repo: &LibGitRepository, relative_file_path: &Path) -> Result<Option<String>> {
70 const STAGE_NORMAL: i32 = 0;
71 let index = repo.index()?;
72
73 // This check is required because index.get_path() unwraps internally :(
74 check_path_to_repo_path_errors(relative_file_path)?;
75
76 let oid = match index.get_path(&relative_file_path, STAGE_NORMAL) {
77 Some(entry) => entry.id,
78 None => return Ok(None),
79 };
80
81 let content = repo.find_blob(oid)?.content().to_owned();
82 Ok(Some(String::from_utf8(content)?))
83 }
84
85 match logic(&self, relative_file_path) {
86 Ok(value) => return value,
87 Err(err) => log::error!("Error loading head text: {:?}", err),
88 }
89 None
90 }
91
92 fn branch_name(&self) -> Option<String> {
93 let head = self.head().log_err()?;
94 let branch = String::from_utf8_lossy(head.shorthand_bytes());
95 Some(branch.to_string())
96 }
97
98 fn staged_statuses(&self, path_prefix: &Path) -> TreeMap<RepoPath, GitFileStatus> {
99 let mut map = TreeMap::default();
100
101 let mut options = git2::StatusOptions::new();
102 options.pathspec(path_prefix);
103 options.show(StatusShow::Index);
104
105 if let Some(statuses) = self.statuses(Some(&mut options)).log_err() {
106 for status in statuses.iter() {
107 let path = RepoPath(PathBuf::from(OsStr::from_bytes(status.path_bytes())));
108 let status = status.status();
109 if !status.contains(git2::Status::IGNORED) {
110 if let Some(status) = read_status(status) {
111 map.insert(path, status)
112 }
113 }
114 }
115 }
116 map
117 }
118
119 fn unstaged_status(&self, path: &RepoPath, mtime: SystemTime) -> Option<GitFileStatus> {
120 // If the file has not changed since it was added to the index, then
121 // there can't be any changes.
122 if matches_index(self, path, mtime) {
123 return None;
124 }
125
126 let mut options = git2::StatusOptions::new();
127 options.pathspec(&path.0);
128 options.disable_pathspec_match(true);
129 options.include_untracked(true);
130 options.recurse_untracked_dirs(true);
131 options.include_unmodified(true);
132 options.show(StatusShow::Workdir);
133
134 let statuses = self.statuses(Some(&mut options)).log_err()?;
135 let status = statuses.get(0).and_then(|s| read_status(s.status()));
136 status
137 }
138
139 fn status(&self, path: &RepoPath, mtime: SystemTime) -> Option<GitFileStatus> {
140 let mut options = git2::StatusOptions::new();
141 options.pathspec(&path.0);
142 options.disable_pathspec_match(true);
143 options.include_untracked(true);
144 options.recurse_untracked_dirs(true);
145 options.include_unmodified(true);
146
147 // If the file has not changed since it was added to the index, then
148 // there's no need to examine the working directory file: just compare
149 // the blob in the index to the one in the HEAD commit.
150 if matches_index(self, path, mtime) {
151 options.show(StatusShow::Index);
152 }
153
154 let statuses = self.statuses(Some(&mut options)).log_err()?;
155 let status = statuses.get(0).and_then(|s| read_status(s.status()));
156 status
157 }
158
159 fn branches(&self) -> Result<Vec<Branch>> {
160 let local_branches = self.branches(Some(BranchType::Local))?;
161 let valid_branches = local_branches
162 .filter_map(|branch| {
163 branch.ok().and_then(|(branch, _)| {
164 let name = branch.name().ok().flatten().map(Box::from)?;
165 let timestamp = branch.get().peel_to_commit().ok()?.time();
166 let unix_timestamp = timestamp.seconds();
167 let timezone_offset = timestamp.offset_minutes();
168 let utc_offset =
169 time::UtcOffset::from_whole_seconds(timezone_offset * 60).ok()?;
170 let unix_timestamp =
171 time::OffsetDateTime::from_unix_timestamp(unix_timestamp).ok()?;
172 Some(Branch {
173 name,
174 unix_timestamp: Some(unix_timestamp.to_offset(utc_offset).unix_timestamp()),
175 })
176 })
177 })
178 .collect();
179 Ok(valid_branches)
180 }
181 fn change_branch(&self, name: &str) -> Result<()> {
182 let revision = self.find_branch(name, BranchType::Local)?;
183 let revision = revision.get();
184 let as_tree = revision.peel_to_tree()?;
185 self.checkout_tree(as_tree.as_object(), None)?;
186 self.set_head(
187 revision
188 .name()
189 .ok_or_else(|| anyhow::anyhow!("Branch name could not be retrieved"))?,
190 )?;
191 Ok(())
192 }
193 fn create_branch(&self, name: &str) -> Result<()> {
194 let current_commit = self.head()?.peel_to_commit()?;
195 self.branch(name, ¤t_commit, false)?;
196
197 Ok(())
198 }
199}
200
201fn matches_index(repo: &LibGitRepository, path: &RepoPath, mtime: SystemTime) -> bool {
202 if let Some(index) = repo.index().log_err() {
203 if let Some(entry) = index.get_path(&path, 0) {
204 if let Some(mtime) = mtime.duration_since(SystemTime::UNIX_EPOCH).log_err() {
205 if entry.mtime.seconds() == mtime.as_secs() as i32
206 && entry.mtime.nanoseconds() == mtime.subsec_nanos()
207 {
208 return true;
209 }
210 }
211 }
212 }
213 false
214}
215
216fn read_status(status: git2::Status) -> Option<GitFileStatus> {
217 if status.contains(git2::Status::CONFLICTED) {
218 Some(GitFileStatus::Conflict)
219 } else if status.intersects(
220 git2::Status::WT_MODIFIED
221 | git2::Status::WT_RENAMED
222 | git2::Status::INDEX_MODIFIED
223 | git2::Status::INDEX_RENAMED,
224 ) {
225 Some(GitFileStatus::Modified)
226 } else if status.intersects(git2::Status::WT_NEW | git2::Status::INDEX_NEW) {
227 Some(GitFileStatus::Added)
228 } else {
229 None
230 }
231}
232
233#[derive(Debug, Clone, Default)]
234pub struct FakeGitRepository {
235 state: Arc<Mutex<FakeGitRepositoryState>>,
236}
237
238#[derive(Debug, Clone, Default)]
239pub struct FakeGitRepositoryState {
240 pub index_contents: HashMap<PathBuf, String>,
241 pub worktree_statuses: HashMap<RepoPath, GitFileStatus>,
242 pub branch_name: Option<String>,
243}
244
245impl FakeGitRepository {
246 pub fn open(state: Arc<Mutex<FakeGitRepositoryState>>) -> Arc<Mutex<dyn GitRepository>> {
247 Arc::new(Mutex::new(FakeGitRepository { state }))
248 }
249}
250
251#[async_trait::async_trait]
252impl GitRepository for FakeGitRepository {
253 fn reload_index(&self) {}
254
255 fn load_index_text(&self, path: &Path) -> Option<String> {
256 let state = self.state.lock();
257 state.index_contents.get(path).cloned()
258 }
259
260 fn branch_name(&self) -> Option<String> {
261 let state = self.state.lock();
262 state.branch_name.clone()
263 }
264
265 fn staged_statuses(&self, path_prefix: &Path) -> TreeMap<RepoPath, GitFileStatus> {
266 let mut map = TreeMap::default();
267 let state = self.state.lock();
268 for (repo_path, status) in state.worktree_statuses.iter() {
269 if repo_path.0.starts_with(path_prefix) {
270 map.insert(repo_path.to_owned(), status.to_owned());
271 }
272 }
273 map
274 }
275
276 fn unstaged_status(&self, _path: &RepoPath, _mtime: SystemTime) -> Option<GitFileStatus> {
277 None
278 }
279
280 fn status(&self, path: &RepoPath, _mtime: SystemTime) -> Option<GitFileStatus> {
281 let state = self.state.lock();
282 state.worktree_statuses.get(path).cloned()
283 }
284
285 fn branches(&self) -> Result<Vec<Branch>> {
286 Ok(vec![])
287 }
288
289 fn change_branch(&self, name: &str) -> Result<()> {
290 let mut state = self.state.lock();
291 state.branch_name = Some(name.to_owned());
292 Ok(())
293 }
294
295 fn create_branch(&self, name: &str) -> Result<()> {
296 let mut state = self.state.lock();
297 state.branch_name = Some(name.to_owned());
298 Ok(())
299 }
300}
301
302fn check_path_to_repo_path_errors(relative_file_path: &Path) -> Result<()> {
303 match relative_file_path.components().next() {
304 None => anyhow::bail!("repo path should not be empty"),
305 Some(Component::Prefix(_)) => anyhow::bail!(
306 "repo path `{}` should be relative, not a windows prefix",
307 relative_file_path.to_string_lossy()
308 ),
309 Some(Component::RootDir) => {
310 anyhow::bail!(
311 "repo path `{}` should be relative",
312 relative_file_path.to_string_lossy()
313 )
314 }
315 Some(Component::CurDir) => {
316 anyhow::bail!(
317 "repo path `{}` should not start with `.`",
318 relative_file_path.to_string_lossy()
319 )
320 }
321 Some(Component::ParentDir) => {
322 anyhow::bail!(
323 "repo path `{}` should not start with `..`",
324 relative_file_path.to_string_lossy()
325 )
326 }
327 _ => Ok(()),
328 }
329}
330
331#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
332pub enum GitFileStatus {
333 Added,
334 Modified,
335 Conflict,
336}
337
338impl GitFileStatus {
339 pub fn merge(
340 this: Option<GitFileStatus>,
341 other: Option<GitFileStatus>,
342 prefer_other: bool,
343 ) -> Option<GitFileStatus> {
344 if prefer_other {
345 return other;
346 } else {
347 match (this, other) {
348 (Some(GitFileStatus::Conflict), _) | (_, Some(GitFileStatus::Conflict)) => {
349 Some(GitFileStatus::Conflict)
350 }
351 (Some(GitFileStatus::Modified), _) | (_, Some(GitFileStatus::Modified)) => {
352 Some(GitFileStatus::Modified)
353 }
354 (Some(GitFileStatus::Added), _) | (_, Some(GitFileStatus::Added)) => {
355 Some(GitFileStatus::Added)
356 }
357 _ => None,
358 }
359 }
360 }
361}
362
363#[derive(Clone, Debug, Ord, Hash, PartialOrd, Eq, PartialEq)]
364pub struct RepoPath(pub PathBuf);
365
366impl RepoPath {
367 pub fn new(path: PathBuf) -> Self {
368 debug_assert!(path.is_relative(), "Repo paths must be relative");
369
370 RepoPath(path)
371 }
372}
373
374impl From<&Path> for RepoPath {
375 fn from(value: &Path) -> Self {
376 RepoPath::new(value.to_path_buf())
377 }
378}
379
380impl From<PathBuf> for RepoPath {
381 fn from(value: PathBuf) -> Self {
382 RepoPath::new(value)
383 }
384}
385
386impl Default for RepoPath {
387 fn default() -> Self {
388 RepoPath(PathBuf::new())
389 }
390}
391
392impl AsRef<Path> for RepoPath {
393 fn as_ref(&self) -> &Path {
394 self.0.as_ref()
395 }
396}
397
398impl std::ops::Deref for RepoPath {
399 type Target = PathBuf;
400
401 fn deref(&self) -> &Self::Target {
402 &self.0
403 }
404}
405
406#[derive(Debug)]
407pub struct RepoPathDescendants<'a>(pub &'a Path);
408
409impl<'a> MapSeekTarget<RepoPath> for RepoPathDescendants<'a> {
410 fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
411 if key.starts_with(&self.0) {
412 Ordering::Greater
413 } else {
414 self.0.cmp(key)
415 }
416 }
417}