repository.rs

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