repository.rs

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