repository.rs

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