repository.rs

  1use anyhow::Result;
  2use collections::HashMap;
  3use git2::{BranchType, StatusShow};
  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    time::SystemTime,
 14};
 15use sum_tree::{MapSeekTarget, TreeMap};
 16use util::ResultExt;
 17
 18pub use git2::Repository as LibGitRepository;
 19
 20#[derive(Clone, Debug, Hash, PartialEq)]
 21pub struct Branch {
 22    pub name: Box<str>,
 23    /// Timestamp of most recent commit, normalized to Unix Epoch format.
 24    pub unix_timestamp: Option<i64>,
 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, &current_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    pub fn from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
363        git_status.and_then(|status| {
364            proto::GitStatus::from_i32(status).map(|status| match status {
365                proto::GitStatus::Added => GitFileStatus::Added,
366                proto::GitStatus::Modified => GitFileStatus::Modified,
367                proto::GitStatus::Conflict => GitFileStatus::Conflict,
368            })
369        })
370    }
371
372    pub fn to_proto(self) -> i32 {
373        match self {
374            GitFileStatus::Added => proto::GitStatus::Added as i32,
375            GitFileStatus::Modified => proto::GitStatus::Modified as i32,
376            GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
377        }
378    }
379}
380
381#[derive(Clone, Debug, Ord, Hash, PartialOrd, Eq, PartialEq)]
382pub struct RepoPath(pub PathBuf);
383
384impl RepoPath {
385    pub fn new(path: PathBuf) -> Self {
386        debug_assert!(path.is_relative(), "Repo paths must be relative");
387
388        RepoPath(path)
389    }
390}
391
392impl From<&Path> for RepoPath {
393    fn from(value: &Path) -> Self {
394        RepoPath::new(value.to_path_buf())
395    }
396}
397
398impl From<PathBuf> for RepoPath {
399    fn from(value: PathBuf) -> Self {
400        RepoPath::new(value)
401    }
402}
403
404impl Default for RepoPath {
405    fn default() -> Self {
406        RepoPath(PathBuf::new())
407    }
408}
409
410impl AsRef<Path> for RepoPath {
411    fn as_ref(&self) -> &Path {
412        self.0.as_ref()
413    }
414}
415
416impl std::ops::Deref for RepoPath {
417    type Target = PathBuf;
418
419    fn deref(&self) -> &Self::Target {
420        &self.0
421    }
422}
423
424#[derive(Debug)]
425pub struct RepoPathDescendants<'a>(pub &'a Path);
426
427impl<'a> MapSeekTarget<RepoPath> for RepoPathDescendants<'a> {
428    fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
429        if key.starts_with(&self.0) {
430            Ordering::Greater
431        } else {
432            self.0.cmp(key)
433        }
434    }
435}