repository.rs

  1use crate::GitHostingProviderRegistry;
  2use crate::{blame::Blame, status::GitStatus};
  3use anyhow::{Context, Result};
  4use collections::{HashMap, HashSet};
  5use git2::BranchType;
  6use gpui::SharedString;
  7use parking_lot::Mutex;
  8use rope::Rope;
  9use serde::{Deserialize, Serialize};
 10use std::{
 11    cmp::Ordering,
 12    path::{Component, Path, PathBuf},
 13    sync::Arc,
 14};
 15use sum_tree::MapSeekTarget;
 16use util::ResultExt;
 17
 18#[derive(Clone, Debug, Hash, PartialEq)]
 19pub struct Branch {
 20    pub is_head: bool,
 21    pub name: SharedString,
 22    /// Timestamp of most recent commit, normalized to Unix Epoch format.
 23    pub unix_timestamp: Option<i64>,
 24}
 25
 26pub trait GitRepository: Send + Sync {
 27    fn reload_index(&self);
 28
 29    /// Loads a git repository entry's contents.
 30    /// Note that for symlink entries, this will return the contents of the symlink, not the target.
 31    fn load_index_text(&self, relative_file_path: &Path) -> Option<String>;
 32
 33    /// Returns the URL of the remote with the given name.
 34    fn remote_url(&self, name: &str) -> Option<String>;
 35    fn branch_name(&self) -> Option<String>;
 36
 37    /// Returns the SHA of the current HEAD.
 38    fn head_sha(&self) -> Option<String>;
 39
 40    fn status(&self, path_prefixes: &[PathBuf]) -> Result<GitStatus>;
 41
 42    fn branches(&self) -> Result<Vec<Branch>>;
 43    fn change_branch(&self, _: &str) -> Result<()>;
 44    fn create_branch(&self, _: &str) -> Result<()>;
 45    fn branch_exits(&self, _: &str) -> Result<bool>;
 46
 47    fn blame(&self, path: &Path, content: Rope) -> Result<crate::blame::Blame>;
 48
 49    /// Returns the path to the repository, typically the `.git` folder.
 50    fn dot_git_dir(&self) -> PathBuf;
 51}
 52
 53impl std::fmt::Debug for dyn GitRepository {
 54    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 55        f.debug_struct("dyn GitRepository<...>").finish()
 56    }
 57}
 58
 59pub struct RealGitRepository {
 60    pub repository: Mutex<git2::Repository>,
 61    pub git_binary_path: PathBuf,
 62    hosting_provider_registry: Arc<GitHostingProviderRegistry>,
 63}
 64
 65impl RealGitRepository {
 66    pub fn new(
 67        repository: git2::Repository,
 68        git_binary_path: Option<PathBuf>,
 69        hosting_provider_registry: Arc<GitHostingProviderRegistry>,
 70    ) -> Self {
 71        Self {
 72            repository: Mutex::new(repository),
 73            git_binary_path: git_binary_path.unwrap_or_else(|| PathBuf::from("git")),
 74            hosting_provider_registry,
 75        }
 76    }
 77}
 78
 79// https://git-scm.com/book/en/v2/Git-Internals-Git-Objects
 80const GIT_MODE_SYMLINK: u32 = 0o120000;
 81
 82impl GitRepository for RealGitRepository {
 83    fn reload_index(&self) {
 84        if let Ok(mut index) = self.repository.lock().index() {
 85            _ = index.read(false);
 86        }
 87    }
 88
 89    fn dot_git_dir(&self) -> PathBuf {
 90        let repo = self.repository.lock();
 91        repo.path().into()
 92    }
 93
 94    fn load_index_text(&self, relative_file_path: &Path) -> Option<String> {
 95        fn logic(repo: &git2::Repository, relative_file_path: &Path) -> Result<Option<String>> {
 96            const STAGE_NORMAL: i32 = 0;
 97            let index = repo.index()?;
 98
 99            // This check is required because index.get_path() unwraps internally :(
100            check_path_to_repo_path_errors(relative_file_path)?;
101
102            let oid = match index.get_path(relative_file_path, STAGE_NORMAL) {
103                Some(entry) if entry.mode != GIT_MODE_SYMLINK => entry.id,
104                _ => return Ok(None),
105            };
106
107            let content = repo.find_blob(oid)?.content().to_owned();
108            Ok(Some(String::from_utf8(content)?))
109        }
110
111        match logic(&self.repository.lock(), relative_file_path) {
112            Ok(value) => return value,
113            Err(err) => log::error!("Error loading head text: {:?}", err),
114        }
115        None
116    }
117
118    fn remote_url(&self, name: &str) -> Option<String> {
119        let repo = self.repository.lock();
120        let remote = repo.find_remote(name).ok()?;
121        remote.url().map(|url| url.to_string())
122    }
123
124    fn branch_name(&self) -> Option<String> {
125        let repo = self.repository.lock();
126        let head = repo.head().log_err()?;
127        let branch = String::from_utf8_lossy(head.shorthand_bytes());
128        Some(branch.to_string())
129    }
130
131    fn head_sha(&self) -> Option<String> {
132        Some(self.repository.lock().head().ok()?.target()?.to_string())
133    }
134
135    fn status(&self, path_prefixes: &[PathBuf]) -> Result<GitStatus> {
136        let working_directory = self
137            .repository
138            .lock()
139            .workdir()
140            .context("failed to read git work directory")?
141            .to_path_buf();
142        GitStatus::new(&self.git_binary_path, &working_directory, path_prefixes)
143    }
144
145    fn branch_exits(&self, name: &str) -> Result<bool> {
146        let repo = self.repository.lock();
147        let branch = repo.find_branch(name, BranchType::Local);
148        match branch {
149            Ok(_) => Ok(true),
150            Err(e) => match e.code() {
151                git2::ErrorCode::NotFound => Ok(false),
152                _ => Err(anyhow::anyhow!(e)),
153            },
154        }
155    }
156
157    fn branches(&self) -> Result<Vec<Branch>> {
158        let repo = self.repository.lock();
159        let local_branches = repo.branches(Some(BranchType::Local))?;
160        let valid_branches = local_branches
161            .filter_map(|branch| {
162                branch.ok().and_then(|(branch, _)| {
163                    let is_head = branch.is_head();
164                    let name = branch
165                        .name()
166                        .ok()
167                        .flatten()
168                        .map(|name| name.to_string().into())?;
169                    let timestamp = branch.get().peel_to_commit().ok()?.time();
170                    let unix_timestamp = timestamp.seconds();
171                    let timezone_offset = timestamp.offset_minutes();
172                    let utc_offset =
173                        time::UtcOffset::from_whole_seconds(timezone_offset * 60).ok()?;
174                    let unix_timestamp =
175                        time::OffsetDateTime::from_unix_timestamp(unix_timestamp).ok()?;
176                    Some(Branch {
177                        is_head,
178                        name,
179                        unix_timestamp: Some(unix_timestamp.to_offset(utc_offset).unix_timestamp()),
180                    })
181                })
182            })
183            .collect();
184        Ok(valid_branches)
185    }
186
187    fn change_branch(&self, name: &str) -> Result<()> {
188        let repo = self.repository.lock();
189        let revision = repo.find_branch(name, BranchType::Local)?;
190        let revision = revision.get();
191        let as_tree = revision.peel_to_tree()?;
192        repo.checkout_tree(as_tree.as_object(), None)?;
193        repo.set_head(
194            revision
195                .name()
196                .ok_or_else(|| anyhow::anyhow!("Branch name could not be retrieved"))?,
197        )?;
198        Ok(())
199    }
200
201    fn create_branch(&self, name: &str) -> Result<()> {
202        let repo = self.repository.lock();
203        let current_commit = repo.head()?.peel_to_commit()?;
204        repo.branch(name, &current_commit, false)?;
205        Ok(())
206    }
207
208    fn blame(&self, path: &Path, content: Rope) -> Result<crate::blame::Blame> {
209        let working_directory = self
210            .repository
211            .lock()
212            .workdir()
213            .with_context(|| format!("failed to get git working directory for file {:?}", path))?
214            .to_path_buf();
215
216        const REMOTE_NAME: &str = "origin";
217        let remote_url = self.remote_url(REMOTE_NAME);
218
219        crate::blame::Blame::for_path(
220            &self.git_binary_path,
221            &working_directory,
222            path,
223            &content,
224            remote_url,
225            self.hosting_provider_registry.clone(),
226        )
227    }
228}
229
230#[derive(Debug, Clone)]
231pub struct FakeGitRepository {
232    state: Arc<Mutex<FakeGitRepositoryState>>,
233}
234
235#[derive(Debug, Clone)]
236pub struct FakeGitRepositoryState {
237    pub dot_git_dir: PathBuf,
238    pub event_emitter: smol::channel::Sender<PathBuf>,
239    pub index_contents: HashMap<PathBuf, String>,
240    pub blames: HashMap<PathBuf, Blame>,
241    pub worktree_statuses: HashMap<RepoPath, GitFileStatus>,
242    pub current_branch_name: Option<String>,
243    pub branches: HashSet<String>,
244}
245
246impl FakeGitRepository {
247    pub fn open(state: Arc<Mutex<FakeGitRepositoryState>>) -> Arc<dyn GitRepository> {
248        Arc::new(FakeGitRepository { state })
249    }
250}
251
252impl FakeGitRepositoryState {
253    pub fn new(dot_git_dir: PathBuf, event_emitter: smol::channel::Sender<PathBuf>) -> Self {
254        FakeGitRepositoryState {
255            dot_git_dir,
256            event_emitter,
257            index_contents: Default::default(),
258            blames: Default::default(),
259            worktree_statuses: Default::default(),
260            current_branch_name: Default::default(),
261            branches: Default::default(),
262        }
263    }
264}
265
266impl GitRepository for FakeGitRepository {
267    fn reload_index(&self) {}
268
269    fn load_index_text(&self, path: &Path) -> Option<String> {
270        let state = self.state.lock();
271        state.index_contents.get(path).cloned()
272    }
273
274    fn remote_url(&self, _name: &str) -> Option<String> {
275        None
276    }
277
278    fn branch_name(&self) -> Option<String> {
279        let state = self.state.lock();
280        state.current_branch_name.clone()
281    }
282
283    fn head_sha(&self) -> Option<String> {
284        None
285    }
286
287    fn dot_git_dir(&self) -> PathBuf {
288        let state = self.state.lock();
289        state.dot_git_dir.clone()
290    }
291
292    fn status(&self, path_prefixes: &[PathBuf]) -> Result<GitStatus> {
293        let state = self.state.lock();
294        let mut entries = state
295            .worktree_statuses
296            .iter()
297            .filter_map(|(repo_path, status)| {
298                if path_prefixes
299                    .iter()
300                    .any(|path_prefix| repo_path.0.starts_with(path_prefix))
301                {
302                    Some((repo_path.to_owned(), *status))
303                } else {
304                    None
305                }
306            })
307            .collect::<Vec<_>>();
308        entries.sort_unstable_by(|a, b| a.0.cmp(&b.0));
309        Ok(GitStatus {
310            entries: entries.into(),
311        })
312    }
313
314    fn branches(&self) -> Result<Vec<Branch>> {
315        let state = self.state.lock();
316        let current_branch = &state.current_branch_name;
317        Ok(state
318            .branches
319            .iter()
320            .map(|branch_name| Branch {
321                is_head: Some(branch_name) == current_branch.as_ref(),
322                name: branch_name.into(),
323                unix_timestamp: None,
324            })
325            .collect())
326    }
327
328    fn branch_exits(&self, name: &str) -> Result<bool> {
329        let state = self.state.lock();
330        Ok(state.branches.contains(name))
331    }
332
333    fn change_branch(&self, name: &str) -> Result<()> {
334        let mut state = self.state.lock();
335        state.current_branch_name = Some(name.to_owned());
336        state
337            .event_emitter
338            .try_send(state.dot_git_dir.clone())
339            .expect("Dropped repo change event");
340        Ok(())
341    }
342
343    fn create_branch(&self, name: &str) -> Result<()> {
344        let mut state = self.state.lock();
345        state.branches.insert(name.to_owned());
346        state
347            .event_emitter
348            .try_send(state.dot_git_dir.clone())
349            .expect("Dropped repo change event");
350        Ok(())
351    }
352
353    fn blame(&self, path: &Path, _content: Rope) -> Result<crate::blame::Blame> {
354        let state = self.state.lock();
355        state
356            .blames
357            .get(path)
358            .with_context(|| format!("failed to get blame for {:?}", path))
359            .cloned()
360    }
361}
362
363fn check_path_to_repo_path_errors(relative_file_path: &Path) -> Result<()> {
364    match relative_file_path.components().next() {
365        None => anyhow::bail!("repo path should not be empty"),
366        Some(Component::Prefix(_)) => anyhow::bail!(
367            "repo path `{}` should be relative, not a windows prefix",
368            relative_file_path.to_string_lossy()
369        ),
370        Some(Component::RootDir) => {
371            anyhow::bail!(
372                "repo path `{}` should be relative",
373                relative_file_path.to_string_lossy()
374            )
375        }
376        Some(Component::CurDir) => {
377            anyhow::bail!(
378                "repo path `{}` should not start with `.`",
379                relative_file_path.to_string_lossy()
380            )
381        }
382        Some(Component::ParentDir) => {
383            anyhow::bail!(
384                "repo path `{}` should not start with `..`",
385                relative_file_path.to_string_lossy()
386            )
387        }
388        _ => Ok(()),
389    }
390}
391
392#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
393pub enum GitFileStatus {
394    Added,
395    Modified,
396    Conflict,
397}
398
399impl GitFileStatus {
400    pub fn merge(
401        this: Option<GitFileStatus>,
402        other: Option<GitFileStatus>,
403        prefer_other: bool,
404    ) -> Option<GitFileStatus> {
405        if prefer_other {
406            return other;
407        }
408
409        match (this, other) {
410            (Some(GitFileStatus::Conflict), _) | (_, Some(GitFileStatus::Conflict)) => {
411                Some(GitFileStatus::Conflict)
412            }
413            (Some(GitFileStatus::Modified), _) | (_, Some(GitFileStatus::Modified)) => {
414                Some(GitFileStatus::Modified)
415            }
416            (Some(GitFileStatus::Added), _) | (_, Some(GitFileStatus::Added)) => {
417                Some(GitFileStatus::Added)
418            }
419            _ => None,
420        }
421    }
422}
423
424#[derive(Clone, Debug, Ord, Hash, PartialOrd, Eq, PartialEq)]
425pub struct RepoPath(pub PathBuf);
426
427impl RepoPath {
428    pub fn new(path: PathBuf) -> Self {
429        debug_assert!(path.is_relative(), "Repo paths must be relative");
430
431        RepoPath(path)
432    }
433}
434
435impl From<&Path> for RepoPath {
436    fn from(value: &Path) -> Self {
437        RepoPath::new(value.to_path_buf())
438    }
439}
440
441impl From<PathBuf> for RepoPath {
442    fn from(value: PathBuf) -> Self {
443        RepoPath::new(value)
444    }
445}
446
447impl Default for RepoPath {
448    fn default() -> Self {
449        RepoPath(PathBuf::new())
450    }
451}
452
453impl AsRef<Path> for RepoPath {
454    fn as_ref(&self) -> &Path {
455        self.0.as_ref()
456    }
457}
458
459impl std::ops::Deref for RepoPath {
460    type Target = PathBuf;
461
462    fn deref(&self) -> &Self::Target {
463        &self.0
464    }
465}
466
467#[derive(Debug)]
468pub struct RepoPathDescendants<'a>(pub &'a Path);
469
470impl<'a> MapSeekTarget<RepoPath> for RepoPathDescendants<'a> {
471    fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
472        if key.starts_with(self.0) {
473            Ordering::Greater
474        } else {
475            self.0.cmp(key)
476        }
477    }
478}