repository.rs

  1use anyhow::Result;
  2use collections::HashMap;
  3use parking_lot::Mutex;
  4use std::{
  5    ffi::OsStr,
  6    os::unix::prelude::OsStrExt,
  7    path::{Component, Path, PathBuf},
  8    sync::Arc,
  9};
 10use sum_tree::TreeMap;
 11use util::ResultExt;
 12
 13pub use git2::Repository as LibGitRepository;
 14
 15#[async_trait::async_trait]
 16pub trait GitRepository: Send {
 17    fn reload_index(&self);
 18
 19    fn load_index_text(&self, relative_file_path: &Path) -> Option<String>;
 20
 21    fn branch_name(&self) -> Option<String>;
 22
 23    fn worktree_statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>>;
 24
 25    fn worktree_status(&self, path: &RepoPath) -> Option<GitFileStatus>;
 26}
 27
 28impl std::fmt::Debug for dyn GitRepository {
 29    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 30        f.debug_struct("dyn GitRepository<...>").finish()
 31    }
 32}
 33
 34#[async_trait::async_trait]
 35impl GitRepository for LibGitRepository {
 36    fn reload_index(&self) {
 37        if let Ok(mut index) = self.index() {
 38            _ = index.read(false);
 39        }
 40    }
 41
 42    fn load_index_text(&self, relative_file_path: &Path) -> Option<String> {
 43        fn logic(repo: &LibGitRepository, relative_file_path: &Path) -> Result<Option<String>> {
 44            const STAGE_NORMAL: i32 = 0;
 45            let index = repo.index()?;
 46
 47            // This check is required because index.get_path() unwraps internally :(
 48            check_path_to_repo_path_errors(relative_file_path)?;
 49
 50            let oid = match index.get_path(&relative_file_path, STAGE_NORMAL) {
 51                Some(entry) => entry.id,
 52                None => return Ok(None),
 53            };
 54
 55            let content = repo.find_blob(oid)?.content().to_owned();
 56            Ok(Some(String::from_utf8(content)?))
 57        }
 58
 59        match logic(&self, relative_file_path) {
 60            Ok(value) => return value,
 61            Err(err) => log::error!("Error loading head text: {:?}", err),
 62        }
 63        None
 64    }
 65
 66    fn branch_name(&self) -> Option<String> {
 67        let head = self.head().log_err()?;
 68        let branch = String::from_utf8_lossy(head.shorthand_bytes());
 69        Some(branch.to_string())
 70    }
 71
 72    fn worktree_statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>> {
 73        let statuses = self.statuses(None).log_err()?;
 74
 75        let mut map = TreeMap::default();
 76
 77        for status in statuses
 78            .iter()
 79            .filter(|status| !status.status().contains(git2::Status::IGNORED))
 80        {
 81            let path = RepoPath(PathBuf::from(OsStr::from_bytes(status.path_bytes())));
 82            let Some(status) = read_status(status.status()) else {
 83                continue
 84            };
 85
 86            map.insert(path, status)
 87        }
 88
 89        Some(map)
 90    }
 91
 92    fn worktree_status(&self, path: &RepoPath) -> Option<GitFileStatus> {
 93        let status = self.status_file(path).log_err()?;
 94        read_status(status)
 95    }
 96}
 97
 98fn read_status(status: git2::Status) -> Option<GitFileStatus> {
 99    if status.contains(git2::Status::CONFLICTED) {
100        Some(GitFileStatus::Conflict)
101    } else if status.intersects(git2::Status::WT_MODIFIED | git2::Status::WT_RENAMED) {
102        Some(GitFileStatus::Modified)
103    } else if status.intersects(git2::Status::WT_NEW) {
104        Some(GitFileStatus::Added)
105    } else {
106        None
107    }
108}
109
110#[derive(Debug, Clone, Default)]
111pub struct FakeGitRepository {
112    state: Arc<Mutex<FakeGitRepositoryState>>,
113}
114
115#[derive(Debug, Clone, Default)]
116pub struct FakeGitRepositoryState {
117    pub index_contents: HashMap<PathBuf, String>,
118    pub worktree_statuses: HashMap<RepoPath, GitFileStatus>,
119    pub branch_name: Option<String>,
120}
121
122impl FakeGitRepository {
123    pub fn open(state: Arc<Mutex<FakeGitRepositoryState>>) -> Arc<Mutex<dyn GitRepository>> {
124        Arc::new(Mutex::new(FakeGitRepository { state }))
125    }
126}
127
128#[async_trait::async_trait]
129impl GitRepository for FakeGitRepository {
130    fn reload_index(&self) {}
131
132    fn load_index_text(&self, path: &Path) -> Option<String> {
133        let state = self.state.lock();
134        state.index_contents.get(path).cloned()
135    }
136
137    fn branch_name(&self) -> Option<String> {
138        let state = self.state.lock();
139        state.branch_name.clone()
140    }
141
142    fn worktree_statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>> {
143        let state = self.state.lock();
144        let mut map = TreeMap::default();
145        for (repo_path, status) in state.worktree_statuses.iter() {
146            map.insert(repo_path.to_owned(), status.to_owned());
147        }
148        Some(map)
149    }
150
151    fn worktree_status(&self, path: &RepoPath) -> Option<GitFileStatus> {
152        let state = self.state.lock();
153        state.worktree_statuses.get(path).cloned()
154    }
155}
156
157fn check_path_to_repo_path_errors(relative_file_path: &Path) -> Result<()> {
158    match relative_file_path.components().next() {
159        None => anyhow::bail!("repo path should not be empty"),
160        Some(Component::Prefix(_)) => anyhow::bail!(
161            "repo path `{}` should be relative, not a windows prefix",
162            relative_file_path.to_string_lossy()
163        ),
164        Some(Component::RootDir) => {
165            anyhow::bail!(
166                "repo path `{}` should be relative",
167                relative_file_path.to_string_lossy()
168            )
169        }
170        Some(Component::CurDir) => {
171            anyhow::bail!(
172                "repo path `{}` should not start with `.`",
173                relative_file_path.to_string_lossy()
174            )
175        }
176        Some(Component::ParentDir) => {
177            anyhow::bail!(
178                "repo path `{}` should not start with `..`",
179                relative_file_path.to_string_lossy()
180            )
181        }
182        _ => Ok(()),
183    }
184}
185
186#[derive(Debug, Clone, PartialEq, Eq)]
187pub enum GitFileStatus {
188    Added,
189    Modified,
190    Conflict,
191}
192
193#[derive(Clone, Debug, Ord, Hash, PartialOrd, Eq, PartialEq)]
194pub struct RepoPath(PathBuf);
195
196impl RepoPath {
197    pub fn new(path: PathBuf) -> Self {
198        debug_assert!(path.is_relative(), "Repo paths must be relative");
199
200        RepoPath(path)
201    }
202}
203
204impl From<&Path> for RepoPath {
205    fn from(value: &Path) -> Self {
206        RepoPath::new(value.to_path_buf())
207    }
208}
209
210impl From<PathBuf> for RepoPath {
211    fn from(value: PathBuf) -> Self {
212        RepoPath::new(value)
213    }
214}
215
216impl Default for RepoPath {
217    fn default() -> Self {
218        RepoPath(PathBuf::new())
219    }
220}
221
222impl AsRef<Path> for RepoPath {
223    fn as_ref(&self) -> &Path {
224        self.0.as_ref()
225    }
226}
227
228impl std::ops::Deref for RepoPath {
229    type Target = PathBuf;
230
231    fn deref(&self) -> &Self::Target {
232        &self.0
233    }
234}