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 schemars::JsonSchema;
11use serde::Deserialize;
12use std::borrow::Borrow;
13use std::io::Write as _;
14use std::process::Stdio;
15use std::sync::LazyLock;
16use std::{
17 cmp::Ordering,
18 path::{Component, Path, PathBuf},
19 sync::Arc,
20};
21use sum_tree::MapSeekTarget;
22use util::command::new_std_command;
23use util::ResultExt;
24
25#[derive(Clone, Debug, Hash, PartialEq, Eq)]
26pub struct Branch {
27 pub is_head: bool,
28 pub name: SharedString,
29 pub upstream: Option<Upstream>,
30 pub most_recent_commit: Option<CommitSummary>,
31}
32
33impl Branch {
34 pub fn tracking_status(&self) -> Option<UpstreamTrackingStatus> {
35 self.upstream
36 .as_ref()
37 .and_then(|upstream| upstream.tracking.status())
38 }
39
40 pub fn priority_key(&self) -> (bool, Option<i64>) {
41 (
42 self.is_head,
43 self.most_recent_commit
44 .as_ref()
45 .map(|commit| commit.commit_timestamp),
46 )
47 }
48}
49
50#[derive(Clone, Debug, Hash, PartialEq, Eq)]
51pub struct Upstream {
52 pub ref_name: SharedString,
53 pub tracking: UpstreamTracking,
54}
55
56#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
57pub enum UpstreamTracking {
58 /// Remote ref not present in local repository.
59 Gone,
60 /// Remote ref present in local repository (fetched from remote).
61 Tracked(UpstreamTrackingStatus),
62}
63
64impl UpstreamTracking {
65 pub fn is_gone(&self) -> bool {
66 matches!(self, UpstreamTracking::Gone)
67 }
68
69 pub fn status(&self) -> Option<UpstreamTrackingStatus> {
70 match self {
71 UpstreamTracking::Gone => None,
72 UpstreamTracking::Tracked(status) => Some(*status),
73 }
74 }
75}
76
77#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
78pub struct UpstreamTrackingStatus {
79 pub ahead: u32,
80 pub behind: u32,
81}
82
83#[derive(Clone, Debug, Hash, PartialEq, Eq)]
84pub struct CommitSummary {
85 pub sha: SharedString,
86 pub subject: SharedString,
87 /// This is a unix timestamp
88 pub commit_timestamp: i64,
89}
90
91#[derive(Clone, Debug, Hash, PartialEq, Eq)]
92pub struct CommitDetails {
93 pub sha: SharedString,
94 pub message: SharedString,
95 pub commit_timestamp: i64,
96 pub committer_email: SharedString,
97 pub committer_name: SharedString,
98}
99
100#[derive(Debug, Clone, Hash, PartialEq, Eq)]
101pub struct Remote {
102 pub name: SharedString,
103}
104
105pub enum ResetMode {
106 // reset the branch pointer, leave index and worktree unchanged
107 // (this will make it look like things that were committed are now
108 // staged)
109 Soft,
110 // reset the branch pointer and index, leave worktree unchanged
111 // (this makes it look as though things that were committed are now
112 // unstaged)
113 Mixed,
114}
115
116pub trait GitRepository: Send + Sync {
117 fn reload_index(&self);
118
119 /// Returns the contents of an entry in the repository's index, or None if there is no entry for the given path.
120 ///
121 /// Also returns `None` for symlinks.
122 fn load_index_text(&self, path: &RepoPath) -> Option<String>;
123
124 /// Returns the contents of an entry in the repository's HEAD, or None if HEAD does not exist or has no entry for the given path.
125 ///
126 /// Also returns `None` for symlinks.
127 fn load_committed_text(&self, path: &RepoPath) -> Option<String>;
128
129 fn set_index_text(&self, path: &RepoPath, content: Option<String>) -> anyhow::Result<()>;
130
131 /// Returns the URL of the remote with the given name.
132 fn remote_url(&self, name: &str) -> Option<String>;
133
134 /// Returns the SHA of the current HEAD.
135 fn head_sha(&self) -> Option<String>;
136
137 fn merge_head_shas(&self) -> Vec<String>;
138
139 /// Returns the list of git statuses, sorted by path
140 fn status(&self, path_prefixes: &[RepoPath]) -> Result<GitStatus>;
141
142 fn branches(&self) -> Result<Vec<Branch>>;
143 fn change_branch(&self, _: &str) -> Result<()>;
144 fn create_branch(&self, _: &str) -> Result<()>;
145 fn branch_exits(&self, _: &str) -> Result<bool>;
146
147 fn reset(&self, commit: &str, mode: ResetMode) -> Result<()>;
148 fn checkout_files(&self, commit: &str, paths: &[RepoPath]) -> Result<()>;
149
150 fn show(&self, commit: &str) -> Result<CommitDetails>;
151
152 fn blame(&self, path: &Path, content: Rope) -> Result<crate::blame::Blame>;
153
154 /// Returns the absolute path to the repository. For worktrees, this will be the path to the
155 /// worktree's gitdir within the main repository (typically `.git/worktrees/<name>`).
156 fn path(&self) -> PathBuf;
157
158 /// Returns the absolute path to the ".git" dir for the main repository, typically a `.git`
159 /// folder. For worktrees, this will be the path to the repository the worktree was created
160 /// from. Otherwise, this is the same value as `path()`.
161 ///
162 /// Git documentation calls this the "commondir", and for git CLI is overridden by
163 /// `GIT_COMMON_DIR`.
164 fn main_repository_path(&self) -> PathBuf;
165
166 /// Updates the index to match the worktree at the given paths.
167 ///
168 /// If any of the paths have been deleted from the worktree, they will be removed from the index if found there.
169 fn stage_paths(&self, paths: &[RepoPath]) -> Result<()>;
170 /// Updates the index to match HEAD at the given paths.
171 ///
172 /// If any of the paths were previously staged but do not exist in HEAD, they will be removed from the index.
173 fn unstage_paths(&self, paths: &[RepoPath]) -> Result<()>;
174
175 fn commit(&self, message: &str, name_and_email: Option<(&str, &str)>) -> Result<()>;
176
177 fn push(
178 &self,
179 branch_name: &str,
180 upstream_name: &str,
181 options: Option<PushOptions>,
182 ) -> Result<()>;
183 fn pull(&self, branch_name: &str, upstream_name: &str) -> Result<()>;
184 fn get_remotes(&self, branch_name: Option<&str>) -> Result<Vec<Remote>>;
185 fn fetch(&self) -> Result<()>;
186}
187
188#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]
189pub enum PushOptions {
190 SetUpstream,
191 Force,
192}
193
194impl std::fmt::Debug for dyn GitRepository {
195 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
196 f.debug_struct("dyn GitRepository<...>").finish()
197 }
198}
199
200pub struct RealGitRepository {
201 pub repository: Mutex<git2::Repository>,
202 pub git_binary_path: PathBuf,
203 hosting_provider_registry: Arc<GitHostingProviderRegistry>,
204}
205
206impl RealGitRepository {
207 pub fn new(
208 repository: git2::Repository,
209 git_binary_path: Option<PathBuf>,
210 hosting_provider_registry: Arc<GitHostingProviderRegistry>,
211 ) -> Self {
212 Self {
213 repository: Mutex::new(repository),
214 git_binary_path: git_binary_path.unwrap_or_else(|| PathBuf::from("git")),
215 hosting_provider_registry,
216 }
217 }
218
219 fn working_directory(&self) -> Result<PathBuf> {
220 self.repository
221 .lock()
222 .workdir()
223 .context("failed to read git work directory")
224 .map(Path::to_path_buf)
225 }
226}
227
228// https://git-scm.com/book/en/v2/Git-Internals-Git-Objects
229const GIT_MODE_SYMLINK: u32 = 0o120000;
230
231impl GitRepository for RealGitRepository {
232 fn reload_index(&self) {
233 if let Ok(mut index) = self.repository.lock().index() {
234 _ = index.read(false);
235 }
236 }
237
238 fn path(&self) -> PathBuf {
239 let repo = self.repository.lock();
240 repo.path().into()
241 }
242
243 fn main_repository_path(&self) -> PathBuf {
244 let repo = self.repository.lock();
245 repo.commondir().into()
246 }
247
248 fn show(&self, commit: &str) -> Result<CommitDetails> {
249 let repo = self.repository.lock();
250 let Ok(commit) = repo.revparse_single(commit)?.into_commit() else {
251 anyhow::bail!("{} is not a commit", commit);
252 };
253 let details = CommitDetails {
254 sha: commit.id().to_string().into(),
255 message: String::from_utf8_lossy(commit.message_raw_bytes())
256 .to_string()
257 .into(),
258 commit_timestamp: commit.time().seconds(),
259 committer_email: String::from_utf8_lossy(commit.committer().email_bytes())
260 .to_string()
261 .into(),
262 committer_name: String::from_utf8_lossy(commit.committer().name_bytes())
263 .to_string()
264 .into(),
265 };
266 Ok(details)
267 }
268
269 fn reset(&self, commit: &str, mode: ResetMode) -> Result<()> {
270 let working_directory = self.working_directory()?;
271
272 let mode_flag = match mode {
273 ResetMode::Mixed => "--mixed",
274 ResetMode::Soft => "--soft",
275 };
276
277 let output = new_std_command(&self.git_binary_path)
278 .current_dir(&working_directory)
279 .args(["reset", mode_flag, commit])
280 .output()?;
281 if !output.status.success() {
282 return Err(anyhow!(
283 "Failed to reset:\n{}",
284 String::from_utf8_lossy(&output.stderr)
285 ));
286 }
287 Ok(())
288 }
289
290 fn checkout_files(&self, commit: &str, paths: &[RepoPath]) -> Result<()> {
291 if paths.is_empty() {
292 return Ok(());
293 }
294 let working_directory = self.working_directory()?;
295
296 let output = new_std_command(&self.git_binary_path)
297 .current_dir(&working_directory)
298 .args(["checkout", commit, "--"])
299 .args(paths.iter().map(|path| path.as_ref()))
300 .output()?;
301 if !output.status.success() {
302 return Err(anyhow!(
303 "Failed to checkout files:\n{}",
304 String::from_utf8_lossy(&output.stderr)
305 ));
306 }
307 Ok(())
308 }
309
310 fn load_index_text(&self, path: &RepoPath) -> Option<String> {
311 fn logic(repo: &git2::Repository, path: &RepoPath) -> Result<Option<String>> {
312 const STAGE_NORMAL: i32 = 0;
313 let index = repo.index()?;
314
315 // This check is required because index.get_path() unwraps internally :(
316 check_path_to_repo_path_errors(path)?;
317
318 let oid = match index.get_path(path, STAGE_NORMAL) {
319 Some(entry) if entry.mode != GIT_MODE_SYMLINK => entry.id,
320 _ => return Ok(None),
321 };
322
323 let content = repo.find_blob(oid)?.content().to_owned();
324 Ok(Some(String::from_utf8(content)?))
325 }
326
327 match logic(&self.repository.lock(), path) {
328 Ok(value) => return value,
329 Err(err) => log::error!("Error loading index text: {:?}", err),
330 }
331 None
332 }
333
334 fn load_committed_text(&self, path: &RepoPath) -> Option<String> {
335 let repo = self.repository.lock();
336 let head = repo.head().ok()?.peel_to_tree().log_err()?;
337 let entry = head.get_path(path).ok()?;
338 if entry.filemode() == i32::from(git2::FileMode::Link) {
339 return None;
340 }
341 let content = repo.find_blob(entry.id()).log_err()?.content().to_owned();
342 let content = String::from_utf8(content).log_err()?;
343 Some(content)
344 }
345
346 fn set_index_text(&self, path: &RepoPath, content: Option<String>) -> anyhow::Result<()> {
347 let working_directory = self.working_directory()?;
348 if let Some(content) = content {
349 let mut child = new_std_command(&self.git_binary_path)
350 .current_dir(&working_directory)
351 .args(["hash-object", "-w", "--stdin"])
352 .stdin(Stdio::piped())
353 .stdout(Stdio::piped())
354 .spawn()?;
355 child.stdin.take().unwrap().write_all(content.as_bytes())?;
356 let output = child.wait_with_output()?.stdout;
357 let sha = String::from_utf8(output)?;
358
359 log::debug!("indexing SHA: {sha}, path {path:?}");
360
361 let status = new_std_command(&self.git_binary_path)
362 .current_dir(&working_directory)
363 .args(["update-index", "--add", "--cacheinfo", "100644", &sha])
364 .arg(path.as_ref())
365 .status()?;
366
367 if !status.success() {
368 return Err(anyhow!("Failed to add to index: {status:?}"));
369 }
370 } else {
371 let status = new_std_command(&self.git_binary_path)
372 .current_dir(&working_directory)
373 .args(["update-index", "--force-remove"])
374 .arg(path.as_ref())
375 .status()?;
376
377 if !status.success() {
378 return Err(anyhow!("Failed to remove from index: {status:?}"));
379 }
380 }
381
382 Ok(())
383 }
384
385 fn remote_url(&self, name: &str) -> Option<String> {
386 let repo = self.repository.lock();
387 let remote = repo.find_remote(name).ok()?;
388 remote.url().map(|url| url.to_string())
389 }
390
391 fn head_sha(&self) -> Option<String> {
392 Some(self.repository.lock().head().ok()?.target()?.to_string())
393 }
394
395 fn merge_head_shas(&self) -> Vec<String> {
396 let mut shas = Vec::default();
397 self.repository
398 .lock()
399 .mergehead_foreach(|oid| {
400 shas.push(oid.to_string());
401 true
402 })
403 .ok();
404 shas
405 }
406
407 fn status(&self, path_prefixes: &[RepoPath]) -> Result<GitStatus> {
408 let working_directory = self
409 .repository
410 .lock()
411 .workdir()
412 .context("failed to read git work directory")?
413 .to_path_buf();
414 GitStatus::new(&self.git_binary_path, &working_directory, path_prefixes)
415 }
416
417 fn branch_exits(&self, name: &str) -> Result<bool> {
418 let repo = self.repository.lock();
419 let branch = repo.find_branch(name, BranchType::Local);
420 match branch {
421 Ok(_) => Ok(true),
422 Err(e) => match e.code() {
423 git2::ErrorCode::NotFound => Ok(false),
424 _ => Err(anyhow!(e)),
425 },
426 }
427 }
428
429 fn branches(&self) -> Result<Vec<Branch>> {
430 let working_directory = self
431 .repository
432 .lock()
433 .workdir()
434 .context("failed to read git work directory")?
435 .to_path_buf();
436 let fields = [
437 "%(HEAD)",
438 "%(objectname)",
439 "%(refname)",
440 "%(upstream)",
441 "%(upstream:track)",
442 "%(committerdate:unix)",
443 "%(contents:subject)",
444 ]
445 .join("%00");
446 let args = vec!["for-each-ref", "refs/heads/**/*", "--format", &fields];
447
448 let output = new_std_command(&self.git_binary_path)
449 .current_dir(&working_directory)
450 .args(args)
451 .output()?;
452
453 if !output.status.success() {
454 return Err(anyhow!(
455 "Failed to git git branches:\n{}",
456 String::from_utf8_lossy(&output.stderr)
457 ));
458 }
459
460 let input = String::from_utf8_lossy(&output.stdout);
461
462 let mut branches = parse_branch_input(&input)?;
463 if branches.is_empty() {
464 let args = vec!["symbolic-ref", "--quiet", "--short", "HEAD"];
465
466 let output = new_std_command(&self.git_binary_path)
467 .current_dir(&working_directory)
468 .args(args)
469 .output()?;
470
471 // git symbolic-ref returns a non-0 exit code if HEAD points
472 // to something other than a branch
473 if output.status.success() {
474 let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
475
476 branches.push(Branch {
477 name: name.into(),
478 is_head: true,
479 upstream: None,
480 most_recent_commit: None,
481 });
482 }
483 }
484
485 Ok(branches)
486 }
487
488 fn change_branch(&self, name: &str) -> Result<()> {
489 let repo = self.repository.lock();
490 let revision = repo.find_branch(name, BranchType::Local)?;
491 let revision = revision.get();
492 let as_tree = revision.peel_to_tree()?;
493 repo.checkout_tree(as_tree.as_object(), None)?;
494 repo.set_head(
495 revision
496 .name()
497 .ok_or_else(|| anyhow!("Branch name could not be retrieved"))?,
498 )?;
499 Ok(())
500 }
501
502 fn create_branch(&self, name: &str) -> Result<()> {
503 let repo = self.repository.lock();
504 let current_commit = repo.head()?.peel_to_commit()?;
505 repo.branch(name, ¤t_commit, false)?;
506 Ok(())
507 }
508
509 fn blame(&self, path: &Path, content: Rope) -> Result<crate::blame::Blame> {
510 let working_directory = self
511 .repository
512 .lock()
513 .workdir()
514 .with_context(|| format!("failed to get git working directory for file {:?}", path))?
515 .to_path_buf();
516
517 const REMOTE_NAME: &str = "origin";
518 let remote_url = self.remote_url(REMOTE_NAME);
519
520 crate::blame::Blame::for_path(
521 &self.git_binary_path,
522 &working_directory,
523 path,
524 &content,
525 remote_url,
526 self.hosting_provider_registry.clone(),
527 )
528 }
529
530 fn stage_paths(&self, paths: &[RepoPath]) -> Result<()> {
531 let working_directory = self.working_directory()?;
532
533 if !paths.is_empty() {
534 let output = new_std_command(&self.git_binary_path)
535 .current_dir(&working_directory)
536 .args(["update-index", "--add", "--remove", "--"])
537 .args(paths.iter().map(|p| p.as_ref()))
538 .output()?;
539
540 // TODO: Get remote response out of this and show it to the user
541 if !output.status.success() {
542 return Err(anyhow!(
543 "Failed to stage paths:\n{}",
544 String::from_utf8_lossy(&output.stderr)
545 ));
546 }
547 }
548 Ok(())
549 }
550
551 fn unstage_paths(&self, paths: &[RepoPath]) -> Result<()> {
552 let working_directory = self.working_directory()?;
553
554 if !paths.is_empty() {
555 let output = new_std_command(&self.git_binary_path)
556 .current_dir(&working_directory)
557 .args(["reset", "--quiet", "--"])
558 .args(paths.iter().map(|p| p.as_ref()))
559 .output()?;
560
561 // TODO: Get remote response out of this and show it to the user
562 if !output.status.success() {
563 return Err(anyhow!(
564 "Failed to unstage:\n{}",
565 String::from_utf8_lossy(&output.stderr)
566 ));
567 }
568 }
569 Ok(())
570 }
571
572 fn commit(&self, message: &str, name_and_email: Option<(&str, &str)>) -> Result<()> {
573 let working_directory = self.working_directory()?;
574
575 let mut cmd = new_std_command(&self.git_binary_path);
576 cmd.current_dir(&working_directory)
577 .args(["commit", "--quiet", "-m"])
578 .arg(message)
579 .arg("--cleanup=strip");
580
581 if let Some((name, email)) = name_and_email {
582 cmd.arg("--author").arg(&format!("{name} <{email}>"));
583 }
584
585 let output = cmd.output()?;
586
587 // TODO: Get remote response out of this and show it to the user
588 if !output.status.success() {
589 return Err(anyhow!(
590 "Failed to commit:\n{}",
591 String::from_utf8_lossy(&output.stderr)
592 ));
593 }
594 Ok(())
595 }
596
597 fn push(
598 &self,
599 branch_name: &str,
600 remote_name: &str,
601 options: Option<PushOptions>,
602 ) -> Result<()> {
603 let working_directory = self.working_directory()?;
604
605 let output = new_std_command(&self.git_binary_path)
606 .current_dir(&working_directory)
607 .args(["push", "--quiet"])
608 .args(options.map(|option| match option {
609 PushOptions::SetUpstream => "--set-upstream",
610 PushOptions::Force => "--force-with-lease",
611 }))
612 .arg(remote_name)
613 .arg(format!("{}:{}", branch_name, branch_name))
614 .output()?;
615
616 if !output.status.success() {
617 return Err(anyhow!(
618 "Failed to push:\n{}",
619 String::from_utf8_lossy(&output.stderr)
620 ));
621 } else {
622 Ok(())
623 }
624 }
625
626 fn pull(&self, branch_name: &str, remote_name: &str) -> Result<()> {
627 let working_directory = self.working_directory()?;
628
629 let output = new_std_command(&self.git_binary_path)
630 .current_dir(&working_directory)
631 .args(["pull", "--quiet"])
632 .arg(remote_name)
633 .arg(branch_name)
634 .output()?;
635
636 if !output.status.success() {
637 return Err(anyhow!(
638 "Failed to pull:\n{}",
639 String::from_utf8_lossy(&output.stderr)
640 ));
641 } else {
642 return Ok(());
643 }
644 }
645
646 fn fetch(&self) -> Result<()> {
647 let working_directory = self.working_directory()?;
648
649 let output = new_std_command(&self.git_binary_path)
650 .current_dir(&working_directory)
651 .args(["fetch", "--quiet", "--all"])
652 .output()?;
653
654 if !output.status.success() {
655 return Err(anyhow!(
656 "Failed to fetch:\n{}",
657 String::from_utf8_lossy(&output.stderr)
658 ));
659 } else {
660 return Ok(());
661 }
662 }
663
664 fn get_remotes(&self, branch_name: Option<&str>) -> Result<Vec<Remote>> {
665 let working_directory = self.working_directory()?;
666
667 if let Some(branch_name) = branch_name {
668 let output = new_std_command(&self.git_binary_path)
669 .current_dir(&working_directory)
670 .args(["config", "--get"])
671 .arg(format!("branch.{}.remote", branch_name))
672 .output()?;
673
674 if output.status.success() {
675 let remote_name = String::from_utf8_lossy(&output.stdout);
676
677 return Ok(vec![Remote {
678 name: remote_name.trim().to_string().into(),
679 }]);
680 }
681 }
682
683 let output = new_std_command(&self.git_binary_path)
684 .current_dir(&working_directory)
685 .args(["remote"])
686 .output()?;
687
688 if output.status.success() {
689 let remote_names = String::from_utf8_lossy(&output.stdout)
690 .split('\n')
691 .filter(|name| !name.is_empty())
692 .map(|name| Remote {
693 name: name.trim().to_string().into(),
694 })
695 .collect();
696
697 return Ok(remote_names);
698 } else {
699 return Err(anyhow!(
700 "Failed to get remotes:\n{}",
701 String::from_utf8_lossy(&output.stderr)
702 ));
703 }
704 }
705}
706
707#[derive(Debug, Clone)]
708pub struct FakeGitRepository {
709 state: Arc<Mutex<FakeGitRepositoryState>>,
710}
711
712#[derive(Debug, Clone)]
713pub struct FakeGitRepositoryState {
714 pub path: PathBuf,
715 pub event_emitter: smol::channel::Sender<PathBuf>,
716 pub head_contents: HashMap<RepoPath, String>,
717 pub index_contents: HashMap<RepoPath, String>,
718 pub blames: HashMap<RepoPath, Blame>,
719 pub statuses: HashMap<RepoPath, FileStatus>,
720 pub current_branch_name: Option<String>,
721 pub branches: HashSet<String>,
722}
723
724impl FakeGitRepository {
725 pub fn open(state: Arc<Mutex<FakeGitRepositoryState>>) -> Arc<dyn GitRepository> {
726 Arc::new(FakeGitRepository { state })
727 }
728}
729
730impl FakeGitRepositoryState {
731 pub fn new(path: PathBuf, event_emitter: smol::channel::Sender<PathBuf>) -> Self {
732 FakeGitRepositoryState {
733 path,
734 event_emitter,
735 head_contents: Default::default(),
736 index_contents: Default::default(),
737 blames: Default::default(),
738 statuses: Default::default(),
739 current_branch_name: Default::default(),
740 branches: Default::default(),
741 }
742 }
743}
744
745impl GitRepository for FakeGitRepository {
746 fn reload_index(&self) {}
747
748 fn load_index_text(&self, path: &RepoPath) -> Option<String> {
749 let state = self.state.lock();
750 state.index_contents.get(path.as_ref()).cloned()
751 }
752
753 fn load_committed_text(&self, path: &RepoPath) -> Option<String> {
754 let state = self.state.lock();
755 state.head_contents.get(path.as_ref()).cloned()
756 }
757
758 fn set_index_text(&self, path: &RepoPath, content: Option<String>) -> anyhow::Result<()> {
759 let mut state = self.state.lock();
760 if let Some(content) = content {
761 state.index_contents.insert(path.clone(), content);
762 } else {
763 state.index_contents.remove(path);
764 }
765 state
766 .event_emitter
767 .try_send(state.path.clone())
768 .expect("Dropped repo change event");
769 Ok(())
770 }
771
772 fn remote_url(&self, _name: &str) -> Option<String> {
773 None
774 }
775
776 fn head_sha(&self) -> Option<String> {
777 None
778 }
779
780 fn merge_head_shas(&self) -> Vec<String> {
781 vec![]
782 }
783
784 fn show(&self, _: &str) -> Result<CommitDetails> {
785 unimplemented!()
786 }
787
788 fn reset(&self, _: &str, _: ResetMode) -> Result<()> {
789 unimplemented!()
790 }
791
792 fn checkout_files(&self, _: &str, _: &[RepoPath]) -> Result<()> {
793 unimplemented!()
794 }
795
796 fn path(&self) -> PathBuf {
797 let state = self.state.lock();
798 state.path.clone()
799 }
800
801 fn main_repository_path(&self) -> PathBuf {
802 self.path()
803 }
804
805 fn status(&self, path_prefixes: &[RepoPath]) -> Result<GitStatus> {
806 let state = self.state.lock();
807
808 let mut entries = state
809 .statuses
810 .iter()
811 .filter_map(|(repo_path, status)| {
812 if path_prefixes
813 .iter()
814 .any(|path_prefix| repo_path.0.starts_with(path_prefix))
815 {
816 Some((repo_path.to_owned(), *status))
817 } else {
818 None
819 }
820 })
821 .collect::<Vec<_>>();
822 entries.sort_unstable_by(|(a, _), (b, _)| a.cmp(&b));
823
824 Ok(GitStatus {
825 entries: entries.into(),
826 })
827 }
828
829 fn branches(&self) -> Result<Vec<Branch>> {
830 let state = self.state.lock();
831 let current_branch = &state.current_branch_name;
832 Ok(state
833 .branches
834 .iter()
835 .map(|branch_name| Branch {
836 is_head: Some(branch_name) == current_branch.as_ref(),
837 name: branch_name.into(),
838 most_recent_commit: None,
839 upstream: None,
840 })
841 .collect())
842 }
843
844 fn branch_exits(&self, name: &str) -> Result<bool> {
845 let state = self.state.lock();
846 Ok(state.branches.contains(name))
847 }
848
849 fn change_branch(&self, name: &str) -> Result<()> {
850 let mut state = self.state.lock();
851 state.current_branch_name = Some(name.to_owned());
852 state
853 .event_emitter
854 .try_send(state.path.clone())
855 .expect("Dropped repo change event");
856 Ok(())
857 }
858
859 fn create_branch(&self, name: &str) -> Result<()> {
860 let mut state = self.state.lock();
861 state.branches.insert(name.to_owned());
862 state
863 .event_emitter
864 .try_send(state.path.clone())
865 .expect("Dropped repo change event");
866 Ok(())
867 }
868
869 fn blame(&self, path: &Path, _content: Rope) -> Result<crate::blame::Blame> {
870 let state = self.state.lock();
871 state
872 .blames
873 .get(path)
874 .with_context(|| format!("failed to get blame for {:?}", path))
875 .cloned()
876 }
877
878 fn stage_paths(&self, _paths: &[RepoPath]) -> Result<()> {
879 unimplemented!()
880 }
881
882 fn unstage_paths(&self, _paths: &[RepoPath]) -> Result<()> {
883 unimplemented!()
884 }
885
886 fn commit(&self, _message: &str, _name_and_email: Option<(&str, &str)>) -> Result<()> {
887 unimplemented!()
888 }
889
890 fn push(&self, _branch: &str, _remote: &str, _options: Option<PushOptions>) -> Result<()> {
891 unimplemented!()
892 }
893
894 fn pull(&self, _branch: &str, _remote: &str) -> Result<()> {
895 unimplemented!()
896 }
897
898 fn fetch(&self) -> Result<()> {
899 unimplemented!()
900 }
901
902 fn get_remotes(&self, _branch: Option<&str>) -> Result<Vec<Remote>> {
903 unimplemented!()
904 }
905}
906
907fn check_path_to_repo_path_errors(relative_file_path: &Path) -> Result<()> {
908 match relative_file_path.components().next() {
909 None => anyhow::bail!("repo path should not be empty"),
910 Some(Component::Prefix(_)) => anyhow::bail!(
911 "repo path `{}` should be relative, not a windows prefix",
912 relative_file_path.to_string_lossy()
913 ),
914 Some(Component::RootDir) => {
915 anyhow::bail!(
916 "repo path `{}` should be relative",
917 relative_file_path.to_string_lossy()
918 )
919 }
920 Some(Component::CurDir) => {
921 anyhow::bail!(
922 "repo path `{}` should not start with `.`",
923 relative_file_path.to_string_lossy()
924 )
925 }
926 Some(Component::ParentDir) => {
927 anyhow::bail!(
928 "repo path `{}` should not start with `..`",
929 relative_file_path.to_string_lossy()
930 )
931 }
932 _ => Ok(()),
933 }
934}
935
936pub static WORK_DIRECTORY_REPO_PATH: LazyLock<RepoPath> =
937 LazyLock::new(|| RepoPath(Path::new("").into()));
938
939#[derive(Clone, Debug, Ord, Hash, PartialOrd, Eq, PartialEq)]
940pub struct RepoPath(pub Arc<Path>);
941
942impl RepoPath {
943 pub fn new(path: PathBuf) -> Self {
944 debug_assert!(path.is_relative(), "Repo paths must be relative");
945
946 RepoPath(path.into())
947 }
948
949 pub fn from_str(path: &str) -> Self {
950 let path = Path::new(path);
951 debug_assert!(path.is_relative(), "Repo paths must be relative");
952
953 RepoPath(path.into())
954 }
955}
956
957impl std::fmt::Display for RepoPath {
958 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
959 self.0.to_string_lossy().fmt(f)
960 }
961}
962
963impl From<&Path> for RepoPath {
964 fn from(value: &Path) -> Self {
965 RepoPath::new(value.into())
966 }
967}
968
969impl From<Arc<Path>> for RepoPath {
970 fn from(value: Arc<Path>) -> Self {
971 RepoPath(value)
972 }
973}
974
975impl From<PathBuf> for RepoPath {
976 fn from(value: PathBuf) -> Self {
977 RepoPath::new(value)
978 }
979}
980
981impl From<&str> for RepoPath {
982 fn from(value: &str) -> Self {
983 Self::from_str(value)
984 }
985}
986
987impl Default for RepoPath {
988 fn default() -> Self {
989 RepoPath(Path::new("").into())
990 }
991}
992
993impl AsRef<Path> for RepoPath {
994 fn as_ref(&self) -> &Path {
995 self.0.as_ref()
996 }
997}
998
999impl std::ops::Deref for RepoPath {
1000 type Target = Path;
1001
1002 fn deref(&self) -> &Self::Target {
1003 &self.0
1004 }
1005}
1006
1007impl Borrow<Path> for RepoPath {
1008 fn borrow(&self) -> &Path {
1009 self.0.as_ref()
1010 }
1011}
1012
1013#[derive(Debug)]
1014pub struct RepoPathDescendants<'a>(pub &'a Path);
1015
1016impl<'a> MapSeekTarget<RepoPath> for RepoPathDescendants<'a> {
1017 fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
1018 if key.starts_with(self.0) {
1019 Ordering::Greater
1020 } else {
1021 self.0.cmp(key)
1022 }
1023 }
1024}
1025
1026fn parse_branch_input(input: &str) -> Result<Vec<Branch>> {
1027 let mut branches = Vec::new();
1028 for line in input.split('\n') {
1029 if line.is_empty() {
1030 continue;
1031 }
1032 let mut fields = line.split('\x00');
1033 let is_current_branch = fields.next().context("no HEAD")? == "*";
1034 let head_sha: SharedString = fields.next().context("no objectname")?.to_string().into();
1035 let ref_name: SharedString = fields
1036 .next()
1037 .context("no refname")?
1038 .strip_prefix("refs/heads/")
1039 .context("unexpected format for refname")?
1040 .to_string()
1041 .into();
1042 let upstream_name = fields.next().context("no upstream")?.to_string();
1043 let upstream_tracking = parse_upstream_track(fields.next().context("no upstream:track")?)?;
1044 let commiterdate = fields.next().context("no committerdate")?.parse::<i64>()?;
1045 let subject: SharedString = fields
1046 .next()
1047 .context("no contents:subject")?
1048 .to_string()
1049 .into();
1050
1051 branches.push(Branch {
1052 is_head: is_current_branch,
1053 name: ref_name,
1054 most_recent_commit: Some(CommitSummary {
1055 sha: head_sha,
1056 subject,
1057 commit_timestamp: commiterdate,
1058 }),
1059 upstream: if upstream_name.is_empty() {
1060 None
1061 } else {
1062 Some(Upstream {
1063 ref_name: upstream_name.into(),
1064 tracking: upstream_tracking,
1065 })
1066 },
1067 })
1068 }
1069
1070 Ok(branches)
1071}
1072
1073fn parse_upstream_track(upstream_track: &str) -> Result<UpstreamTracking> {
1074 if upstream_track == "" {
1075 return Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
1076 ahead: 0,
1077 behind: 0,
1078 }));
1079 }
1080
1081 let upstream_track = upstream_track
1082 .strip_prefix("[")
1083 .ok_or_else(|| anyhow!("missing ["))?;
1084 let upstream_track = upstream_track
1085 .strip_suffix("]")
1086 .ok_or_else(|| anyhow!("missing ["))?;
1087 let mut ahead: u32 = 0;
1088 let mut behind: u32 = 0;
1089 for component in upstream_track.split(", ") {
1090 if component == "gone" {
1091 return Ok(UpstreamTracking::Gone);
1092 }
1093 if let Some(ahead_num) = component.strip_prefix("ahead ") {
1094 ahead = ahead_num.parse::<u32>()?;
1095 }
1096 if let Some(behind_num) = component.strip_prefix("behind ") {
1097 behind = behind_num.parse::<u32>()?;
1098 }
1099 }
1100 Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
1101 ahead,
1102 behind,
1103 }))
1104}
1105
1106#[test]
1107fn test_branches_parsing() {
1108 // suppress "help: octal escapes are not supported, `\0` is always null"
1109 #[allow(clippy::octal_escapes)]
1110 let input = "*\0060964da10574cd9bf06463a53bf6e0769c5c45e\0refs/heads/zed-patches\0refs/remotes/origin/zed-patches\0\01733187470\0generated protobuf\n";
1111 assert_eq!(
1112 parse_branch_input(&input).unwrap(),
1113 vec![Branch {
1114 is_head: true,
1115 name: "zed-patches".into(),
1116 upstream: Some(Upstream {
1117 ref_name: "refs/remotes/origin/zed-patches".into(),
1118 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
1119 ahead: 0,
1120 behind: 0
1121 })
1122 }),
1123 most_recent_commit: Some(CommitSummary {
1124 sha: "060964da10574cd9bf06463a53bf6e0769c5c45e".into(),
1125 subject: "generated protobuf".into(),
1126 commit_timestamp: 1733187470,
1127 })
1128 }]
1129 )
1130}