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