repository.rs

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