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