repository.rs

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