repository.rs

  1use crate::status::FileStatus;
  2use crate::{blame::Blame, status::GitStatus};
  3use crate::{GitHostingProviderRegistry, COMMIT_MESSAGE};
  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, name_and_email: Option<(&str, &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, name_and_email: Option<(&str, &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        let commit_file = self.dot_git_dir().join(*COMMIT_MESSAGE);
294        let commit_file_path = commit_file.to_string_lossy();
295        let mut args = vec![
296            "commit",
297            "--quiet",
298            "-F",
299            commit_file_path.as_ref(),
300            "--cleanup=strip",
301        ];
302        let author = name_and_email.map(|(name, email)| format!("{name} <{email}>"));
303        if let Some(author) = author.as_deref() {
304            args.push("--author");
305            args.push(author);
306        }
307
308        let cmd = new_std_command(&self.git_binary_path)
309            .current_dir(&working_directory)
310            .args(args)
311            .status()?;
312        if !cmd.success() {
313            return Err(anyhow!("Failed to commit: {cmd}"));
314        }
315        Ok(())
316    }
317}
318
319#[derive(Debug, Clone)]
320pub struct FakeGitRepository {
321    state: Arc<Mutex<FakeGitRepositoryState>>,
322}
323
324#[derive(Debug, Clone)]
325pub struct FakeGitRepositoryState {
326    pub dot_git_dir: PathBuf,
327    pub event_emitter: smol::channel::Sender<PathBuf>,
328    pub index_contents: HashMap<PathBuf, String>,
329    pub blames: HashMap<PathBuf, Blame>,
330    pub statuses: HashMap<RepoPath, FileStatus>,
331    pub current_branch_name: Option<String>,
332    pub branches: HashSet<String>,
333}
334
335impl FakeGitRepository {
336    pub fn open(state: Arc<Mutex<FakeGitRepositoryState>>) -> Arc<dyn GitRepository> {
337        Arc::new(FakeGitRepository { state })
338    }
339}
340
341impl FakeGitRepositoryState {
342    pub fn new(dot_git_dir: PathBuf, event_emitter: smol::channel::Sender<PathBuf>) -> Self {
343        FakeGitRepositoryState {
344            dot_git_dir,
345            event_emitter,
346            index_contents: Default::default(),
347            blames: Default::default(),
348            statuses: Default::default(),
349            current_branch_name: Default::default(),
350            branches: Default::default(),
351        }
352    }
353}
354
355impl GitRepository for FakeGitRepository {
356    fn reload_index(&self) {}
357
358    fn load_index_text(&self, path: &Path) -> Option<String> {
359        let state = self.state.lock();
360        state.index_contents.get(path).cloned()
361    }
362
363    fn remote_url(&self, _name: &str) -> Option<String> {
364        None
365    }
366
367    fn branch_name(&self) -> Option<String> {
368        let state = self.state.lock();
369        state.current_branch_name.clone()
370    }
371
372    fn head_sha(&self) -> Option<String> {
373        None
374    }
375
376    fn dot_git_dir(&self) -> PathBuf {
377        let state = self.state.lock();
378        state.dot_git_dir.clone()
379    }
380
381    fn status(&self, path_prefixes: &[RepoPath]) -> Result<GitStatus> {
382        let state = self.state.lock();
383
384        let mut entries = state
385            .statuses
386            .iter()
387            .filter_map(|(repo_path, status)| {
388                if path_prefixes
389                    .iter()
390                    .any(|path_prefix| repo_path.0.starts_with(path_prefix))
391                {
392                    Some((repo_path.to_owned(), *status))
393                } else {
394                    None
395                }
396            })
397            .collect::<Vec<_>>();
398        entries.sort_unstable_by(|(a, _), (b, _)| a.cmp(&b));
399
400        Ok(GitStatus {
401            entries: entries.into(),
402        })
403    }
404
405    fn branches(&self) -> Result<Vec<Branch>> {
406        let state = self.state.lock();
407        let current_branch = &state.current_branch_name;
408        Ok(state
409            .branches
410            .iter()
411            .map(|branch_name| Branch {
412                is_head: Some(branch_name) == current_branch.as_ref(),
413                name: branch_name.into(),
414                unix_timestamp: None,
415            })
416            .collect())
417    }
418
419    fn branch_exits(&self, name: &str) -> Result<bool> {
420        let state = self.state.lock();
421        Ok(state.branches.contains(name))
422    }
423
424    fn change_branch(&self, name: &str) -> Result<()> {
425        let mut state = self.state.lock();
426        state.current_branch_name = Some(name.to_owned());
427        state
428            .event_emitter
429            .try_send(state.dot_git_dir.clone())
430            .expect("Dropped repo change event");
431        Ok(())
432    }
433
434    fn create_branch(&self, name: &str) -> Result<()> {
435        let mut state = self.state.lock();
436        state.branches.insert(name.to_owned());
437        state
438            .event_emitter
439            .try_send(state.dot_git_dir.clone())
440            .expect("Dropped repo change event");
441        Ok(())
442    }
443
444    fn blame(&self, path: &Path, _content: Rope) -> Result<crate::blame::Blame> {
445        let state = self.state.lock();
446        state
447            .blames
448            .get(path)
449            .with_context(|| format!("failed to get blame for {:?}", path))
450            .cloned()
451    }
452
453    fn stage_paths(&self, _paths: &[RepoPath]) -> Result<()> {
454        unimplemented!()
455    }
456
457    fn unstage_paths(&self, _paths: &[RepoPath]) -> Result<()> {
458        unimplemented!()
459    }
460
461    fn commit(&self, _name_and_email: Option<(&str, &str)>) -> Result<()> {
462        unimplemented!()
463    }
464}
465
466fn check_path_to_repo_path_errors(relative_file_path: &Path) -> Result<()> {
467    match relative_file_path.components().next() {
468        None => anyhow::bail!("repo path should not be empty"),
469        Some(Component::Prefix(_)) => anyhow::bail!(
470            "repo path `{}` should be relative, not a windows prefix",
471            relative_file_path.to_string_lossy()
472        ),
473        Some(Component::RootDir) => {
474            anyhow::bail!(
475                "repo path `{}` should be relative",
476                relative_file_path.to_string_lossy()
477            )
478        }
479        Some(Component::CurDir) => {
480            anyhow::bail!(
481                "repo path `{}` should not start with `.`",
482                relative_file_path.to_string_lossy()
483            )
484        }
485        Some(Component::ParentDir) => {
486            anyhow::bail!(
487                "repo path `{}` should not start with `..`",
488                relative_file_path.to_string_lossy()
489            )
490        }
491        _ => Ok(()),
492    }
493}
494
495pub static WORK_DIRECTORY_REPO_PATH: LazyLock<RepoPath> =
496    LazyLock::new(|| RepoPath(Path::new("").into()));
497
498#[derive(Clone, Debug, Ord, Hash, PartialOrd, Eq, PartialEq)]
499pub struct RepoPath(pub Arc<Path>);
500
501impl RepoPath {
502    pub fn new(path: PathBuf) -> Self {
503        debug_assert!(path.is_relative(), "Repo paths must be relative");
504
505        RepoPath(path.into())
506    }
507
508    pub fn from_str(path: &str) -> Self {
509        let path = Path::new(path);
510        debug_assert!(path.is_relative(), "Repo paths must be relative");
511
512        RepoPath(path.into())
513    }
514
515    pub fn to_proto(&self) -> String {
516        self.0.to_string_lossy().to_string()
517    }
518}
519
520impl std::fmt::Display for RepoPath {
521    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
522        self.0.to_string_lossy().fmt(f)
523    }
524}
525
526impl From<&Path> for RepoPath {
527    fn from(value: &Path) -> Self {
528        RepoPath::new(value.into())
529    }
530}
531
532impl From<PathBuf> for RepoPath {
533    fn from(value: PathBuf) -> Self {
534        RepoPath::new(value)
535    }
536}
537
538impl From<&str> for RepoPath {
539    fn from(value: &str) -> Self {
540        Self::from_str(value)
541    }
542}
543
544impl Default for RepoPath {
545    fn default() -> Self {
546        RepoPath(Path::new("").into())
547    }
548}
549
550impl AsRef<Path> for RepoPath {
551    fn as_ref(&self) -> &Path {
552        self.0.as_ref()
553    }
554}
555
556impl std::ops::Deref for RepoPath {
557    type Target = Path;
558
559    fn deref(&self) -> &Self::Target {
560        &self.0
561    }
562}
563
564impl Borrow<Path> for RepoPath {
565    fn borrow(&self) -> &Path {
566        self.0.as_ref()
567    }
568}
569
570#[derive(Debug)]
571pub struct RepoPathDescendants<'a>(pub &'a Path);
572
573impl<'a> MapSeekTarget<RepoPath> for RepoPathDescendants<'a> {
574    fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
575        if key.starts_with(self.0) {
576            Ordering::Greater
577        } else {
578            self.0.cmp(key)
579        }
580    }
581}