repository.rs

  1use anyhow::Result;
  2use collections::HashMap;
  3use git2::ErrorCode;
  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};
 14use sum_tree::{MapSeekTarget, TreeMap};
 15use util::ResultExt;
 16
 17pub use git2::Repository as LibGitRepository;
 18
 19#[async_trait::async_trait]
 20pub trait GitRepository: Send {
 21    fn reload_index(&self);
 22
 23    fn load_index_text(&self, relative_file_path: &Path) -> Option<String>;
 24
 25    fn branch_name(&self) -> Option<String>;
 26
 27    fn statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>>;
 28
 29    fn status(&self, path: &RepoPath) -> Result<Option<GitFileStatus>>;
 30}
 31
 32impl std::fmt::Debug for dyn GitRepository {
 33    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 34        f.debug_struct("dyn GitRepository<...>").finish()
 35    }
 36}
 37
 38#[async_trait::async_trait]
 39impl GitRepository for LibGitRepository {
 40    fn reload_index(&self) {
 41        if let Ok(mut index) = self.index() {
 42            _ = index.read(false);
 43        }
 44    }
 45
 46    fn load_index_text(&self, relative_file_path: &Path) -> Option<String> {
 47        fn logic(repo: &LibGitRepository, relative_file_path: &Path) -> Result<Option<String>> {
 48            const STAGE_NORMAL: i32 = 0;
 49            let index = repo.index()?;
 50
 51            // This check is required because index.get_path() unwraps internally :(
 52            check_path_to_repo_path_errors(relative_file_path)?;
 53
 54            let oid = match index.get_path(&relative_file_path, STAGE_NORMAL) {
 55                Some(entry) => entry.id,
 56                None => return Ok(None),
 57            };
 58
 59            let content = repo.find_blob(oid)?.content().to_owned();
 60            Ok(Some(String::from_utf8(content)?))
 61        }
 62
 63        match logic(&self, relative_file_path) {
 64            Ok(value) => return value,
 65            Err(err) => log::error!("Error loading head text: {:?}", err),
 66        }
 67        None
 68    }
 69
 70    fn branch_name(&self) -> Option<String> {
 71        let head = self.head().log_err()?;
 72        let branch = String::from_utf8_lossy(head.shorthand_bytes());
 73        Some(branch.to_string())
 74    }
 75
 76    fn statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>> {
 77        let statuses = self.statuses(None).log_err()?;
 78
 79        let mut map = TreeMap::default();
 80
 81        for status in statuses
 82            .iter()
 83            .filter(|status| !status.status().contains(git2::Status::IGNORED))
 84        {
 85            let path = RepoPath(PathBuf::from(OsStr::from_bytes(status.path_bytes())));
 86            let Some(status) = read_status(status.status()) else {
 87                continue
 88            };
 89
 90            map.insert(path, status)
 91        }
 92
 93        Some(map)
 94    }
 95
 96    fn status(&self, path: &RepoPath) -> Result<Option<GitFileStatus>> {
 97        let status = self.status_file(path);
 98        match status {
 99            Ok(status) => Ok(read_status(status)),
100            Err(e) => {
101                if e.code() == ErrorCode::NotFound {
102                    Ok(None)
103                } else {
104                    Err(e.into())
105                }
106            }
107        }
108    }
109}
110
111fn read_status(status: git2::Status) -> Option<GitFileStatus> {
112    if status.contains(git2::Status::CONFLICTED) {
113        Some(GitFileStatus::Conflict)
114    } else if status.intersects(
115        git2::Status::WT_MODIFIED
116            | git2::Status::WT_RENAMED
117            | git2::Status::INDEX_MODIFIED
118            | git2::Status::INDEX_RENAMED,
119    ) {
120        Some(GitFileStatus::Modified)
121    } else if status.intersects(git2::Status::WT_NEW | git2::Status::INDEX_NEW) {
122        Some(GitFileStatus::Added)
123    } else {
124        None
125    }
126}
127
128#[derive(Debug, Clone, Default)]
129pub struct FakeGitRepository {
130    state: Arc<Mutex<FakeGitRepositoryState>>,
131}
132
133#[derive(Debug, Clone, Default)]
134pub struct FakeGitRepositoryState {
135    pub index_contents: HashMap<PathBuf, String>,
136    pub worktree_statuses: HashMap<RepoPath, GitFileStatus>,
137    pub branch_name: Option<String>,
138}
139
140impl FakeGitRepository {
141    pub fn open(state: Arc<Mutex<FakeGitRepositoryState>>) -> Arc<Mutex<dyn GitRepository>> {
142        Arc::new(Mutex::new(FakeGitRepository { state }))
143    }
144}
145
146#[async_trait::async_trait]
147impl GitRepository for FakeGitRepository {
148    fn reload_index(&self) {}
149
150    fn load_index_text(&self, path: &Path) -> Option<String> {
151        let state = self.state.lock();
152        state.index_contents.get(path).cloned()
153    }
154
155    fn branch_name(&self) -> Option<String> {
156        let state = self.state.lock();
157        state.branch_name.clone()
158    }
159
160    fn statuses(&self) -> Option<TreeMap<RepoPath, GitFileStatus>> {
161        let state = self.state.lock();
162        let mut map = TreeMap::default();
163        for (repo_path, status) in state.worktree_statuses.iter() {
164            map.insert(repo_path.to_owned(), status.to_owned());
165        }
166        Some(map)
167    }
168
169    fn status(&self, path: &RepoPath) -> Result<Option<GitFileStatus>> {
170        let state = self.state.lock();
171        Ok(state.worktree_statuses.get(path).cloned())
172    }
173}
174
175fn check_path_to_repo_path_errors(relative_file_path: &Path) -> Result<()> {
176    match relative_file_path.components().next() {
177        None => anyhow::bail!("repo path should not be empty"),
178        Some(Component::Prefix(_)) => anyhow::bail!(
179            "repo path `{}` should be relative, not a windows prefix",
180            relative_file_path.to_string_lossy()
181        ),
182        Some(Component::RootDir) => {
183            anyhow::bail!(
184                "repo path `{}` should be relative",
185                relative_file_path.to_string_lossy()
186            )
187        }
188        Some(Component::CurDir) => {
189            anyhow::bail!(
190                "repo path `{}` should not start with `.`",
191                relative_file_path.to_string_lossy()
192            )
193        }
194        Some(Component::ParentDir) => {
195            anyhow::bail!(
196                "repo path `{}` should not start with `..`",
197                relative_file_path.to_string_lossy()
198            )
199        }
200        _ => Ok(()),
201    }
202}
203
204#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
205pub enum GitFileStatus {
206    Added,
207    Modified,
208    Conflict,
209}
210
211impl GitFileStatus {
212    pub fn merge(
213        this: Option<GitFileStatus>,
214        other: Option<GitFileStatus>,
215        prefer_other: bool,
216    ) -> Option<GitFileStatus> {
217        if prefer_other {
218            return other;
219        } else {
220            match (this, other) {
221                (Some(GitFileStatus::Conflict), _) | (_, Some(GitFileStatus::Conflict)) => {
222                    Some(GitFileStatus::Conflict)
223                }
224                (Some(GitFileStatus::Modified), _) | (_, Some(GitFileStatus::Modified)) => {
225                    Some(GitFileStatus::Modified)
226                }
227                (Some(GitFileStatus::Added), _) | (_, Some(GitFileStatus::Added)) => {
228                    Some(GitFileStatus::Added)
229                }
230                _ => None,
231            }
232        }
233    }
234
235    pub fn from_proto(git_status: Option<i32>) -> Option<GitFileStatus> {
236        git_status.and_then(|status| {
237            proto::GitStatus::from_i32(status).map(|status| match status {
238                proto::GitStatus::Added => GitFileStatus::Added,
239                proto::GitStatus::Modified => GitFileStatus::Modified,
240                proto::GitStatus::Conflict => GitFileStatus::Conflict,
241            })
242        })
243    }
244
245    pub fn to_proto(self) -> i32 {
246        match self {
247            GitFileStatus::Added => proto::GitStatus::Added as i32,
248            GitFileStatus::Modified => proto::GitStatus::Modified as i32,
249            GitFileStatus::Conflict => proto::GitStatus::Conflict as i32,
250        }
251    }
252}
253
254#[derive(Clone, Debug, Ord, Hash, PartialOrd, Eq, PartialEq)]
255pub struct RepoPath(pub PathBuf);
256
257impl RepoPath {
258    pub fn new(path: PathBuf) -> Self {
259        debug_assert!(path.is_relative(), "Repo paths must be relative");
260
261        RepoPath(path)
262    }
263}
264
265impl From<&Path> for RepoPath {
266    fn from(value: &Path) -> Self {
267        RepoPath::new(value.to_path_buf())
268    }
269}
270
271impl From<PathBuf> for RepoPath {
272    fn from(value: PathBuf) -> Self {
273        RepoPath::new(value)
274    }
275}
276
277impl Default for RepoPath {
278    fn default() -> Self {
279        RepoPath(PathBuf::new())
280    }
281}
282
283impl AsRef<Path> for RepoPath {
284    fn as_ref(&self) -> &Path {
285        self.0.as_ref()
286    }
287}
288
289impl std::ops::Deref for RepoPath {
290    type Target = PathBuf;
291
292    fn deref(&self) -> &Self::Target {
293        &self.0
294    }
295}
296
297#[derive(Debug)]
298pub struct RepoPathDescendants<'a>(pub &'a Path);
299
300impl<'a> MapSeekTarget<RepoPath> for RepoPathDescendants<'a> {
301    fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
302        if key.starts_with(&self.0) {
303            Ordering::Greater
304        } else {
305            self.0.cmp(key)
306        }
307    }
308}