ex_cli/git/
repo.rs

1use crate::error::MyResult;
2use crate::git::flags::GitFlags;
3use git2::{Repository, RepositoryOpenFlags, Status, StatusEntry, StatusOptions};
4use std::collections::HashMap;
5use std::path::{Path, PathBuf};
6
7type GitStatusMap = HashMap<PathBuf, Status>;
8
9pub struct GitRepo {
10    repo: Repository,
11    root: PathBuf,
12    statuses: Option<GitStatusMap>,
13}
14
15impl GitRepo {
16    pub fn open_repository<'a, I>(path: &Path, ceiling: I) -> Option<Self> where
17        I: IntoIterator<Item = &'a PathBuf>,
18    {
19        let flags = RepositoryOpenFlags::empty();
20        if let Ok(repo) = Repository::open_ext(path, flags, ceiling) {
21            if let Some(root) = repo.workdir() {
22                let root = root.to_path_buf();
23                let repo = Self { repo, root, statuses: None };
24                return Some(repo);
25            }
26        }
27        None
28    }
29
30    pub fn get_root(&self) -> &Path {
31        &self.root
32    }
33
34    pub fn test_allowed(&mut self, flags: &GitFlags, path: &Path) -> MyResult<Option<GitFlags>> {
35        let path = path.strip_prefix(&self.root).map_err(|e| (e, path))?;
36        let status = self.repo.status_file(path)?;
37        if status.is_index_new() {
38            let statuses = self.statuses.get_or_insert_with(|| {
39                Self::read_statuses(&self.repo)
40            });
41            if let Some(status) = statuses.get(path) {
42                let result = flags.test_allowed(status);
43                return Ok(result);
44            }
45        }
46        let result = flags.test_allowed(&status);
47        Ok(result)
48    }
49
50    fn read_statuses(repo: &Repository) -> GitStatusMap {
51        let mut statuses = GitStatusMap::new();
52        let mut options = StatusOptions::new();
53        options.include_unmodified(true);
54        options.include_untracked(true);
55        options.include_ignored(true);
56        options.renames_head_to_index(true);
57        options.renames_index_to_workdir(true);
58        options.renames_from_rewrites(true);
59        if let Ok(entries) = repo.statuses(Some(&mut options)) {
60            for entry in entries.iter() {
61                if let Some(path) = Self::read_path(&entry) {
62                    statuses.insert(path.to_path_buf(), entry.status());
63                }
64            }
65        }
66        statuses
67    }
68
69    fn read_path<'a>(entry: &'a StatusEntry) -> Option<&'a Path> {
70        let delta = entry.head_to_index()?;
71        let old = delta.old_file().path()?;
72        let new = delta.new_file().path()?;
73        if new != old {
74            Some(new)
75        } else {
76            None
77        }
78    }
79}