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