1use crate::commit::parse_git_diff_name_status;
2use crate::status::{GitStatus, StatusCode};
3use crate::{Oid, SHORT_SHA_LENGTH};
4use anyhow::{Context as _, Result, anyhow, bail};
5use collections::HashMap;
6use futures::future::BoxFuture;
7use futures::{AsyncWriteExt, FutureExt as _, select_biased};
8use git2::BranchType;
9use gpui::{AppContext as _, AsyncApp, BackgroundExecutor, SharedString};
10use parking_lot::Mutex;
11use rope::Rope;
12use schemars::JsonSchema;
13use serde::Deserialize;
14use std::borrow::{Borrow, Cow};
15use std::ffi::{OsStr, OsString};
16use std::io::prelude::*;
17use std::path::Component;
18use std::process::{ExitStatus, Stdio};
19use std::sync::LazyLock;
20use std::{
21 cmp::Ordering,
22 future,
23 io::{BufRead, BufReader, BufWriter, Read},
24 path::{Path, PathBuf},
25 sync::Arc,
26};
27use sum_tree::MapSeekTarget;
28use thiserror::Error;
29use util::ResultExt;
30use util::command::{new_smol_command, new_std_command};
31use uuid::Uuid;
32
33pub use askpass::{AskPassDelegate, AskPassResult, AskPassSession};
34
35pub const REMOTE_CANCELLED_BY_USER: &str = "Operation cancelled by user";
36
37#[derive(Clone, Debug, Hash, PartialEq, Eq)]
38pub struct Branch {
39 pub is_head: bool,
40 pub ref_name: SharedString,
41 pub upstream: Option<Upstream>,
42 pub most_recent_commit: Option<CommitSummary>,
43}
44
45impl Branch {
46 pub fn name(&self) -> &str {
47 self.ref_name
48 .as_ref()
49 .strip_prefix("refs/heads/")
50 .or_else(|| self.ref_name.as_ref().strip_prefix("refs/remotes/"))
51 .unwrap_or(self.ref_name.as_ref())
52 }
53
54 pub fn is_remote(&self) -> bool {
55 self.ref_name.starts_with("refs/remotes/")
56 }
57
58 pub fn tracking_status(&self) -> Option<UpstreamTrackingStatus> {
59 self.upstream
60 .as_ref()
61 .and_then(|upstream| upstream.tracking.status())
62 }
63
64 pub fn priority_key(&self) -> (bool, Option<i64>) {
65 (
66 self.is_head,
67 self.most_recent_commit
68 .as_ref()
69 .map(|commit| commit.commit_timestamp),
70 )
71 }
72}
73
74#[derive(Clone, Debug, Hash, PartialEq, Eq)]
75pub struct Upstream {
76 pub ref_name: SharedString,
77 pub tracking: UpstreamTracking,
78}
79
80impl Upstream {
81 pub fn remote_name(&self) -> Option<&str> {
82 self.ref_name
83 .strip_prefix("refs/remotes/")
84 .and_then(|stripped| stripped.split("/").next())
85 }
86
87 pub fn stripped_ref_name(&self) -> Option<&str> {
88 self.ref_name.strip_prefix("refs/remotes/")
89 }
90}
91
92#[derive(Clone, Copy, Default)]
93pub struct CommitOptions {
94 pub amend: bool,
95}
96
97#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
98pub enum UpstreamTracking {
99 /// Remote ref not present in local repository.
100 Gone,
101 /// Remote ref present in local repository (fetched from remote).
102 Tracked(UpstreamTrackingStatus),
103}
104
105impl From<UpstreamTrackingStatus> for UpstreamTracking {
106 fn from(status: UpstreamTrackingStatus) -> Self {
107 UpstreamTracking::Tracked(status)
108 }
109}
110
111impl UpstreamTracking {
112 pub fn is_gone(&self) -> bool {
113 matches!(self, UpstreamTracking::Gone)
114 }
115
116 pub fn status(&self) -> Option<UpstreamTrackingStatus> {
117 match self {
118 UpstreamTracking::Gone => None,
119 UpstreamTracking::Tracked(status) => Some(*status),
120 }
121 }
122}
123
124#[derive(Debug, Clone)]
125pub struct RemoteCommandOutput {
126 pub stdout: String,
127 pub stderr: String,
128}
129
130impl RemoteCommandOutput {
131 pub fn is_empty(&self) -> bool {
132 self.stdout.is_empty() && self.stderr.is_empty()
133 }
134}
135
136#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
137pub struct UpstreamTrackingStatus {
138 pub ahead: u32,
139 pub behind: u32,
140}
141
142#[derive(Clone, Debug, Hash, PartialEq, Eq)]
143pub struct CommitSummary {
144 pub sha: SharedString,
145 pub subject: SharedString,
146 /// This is a unix timestamp
147 pub commit_timestamp: i64,
148 pub has_parent: bool,
149}
150
151#[derive(Clone, Debug, Default, Hash, PartialEq, Eq)]
152pub struct CommitDetails {
153 pub sha: SharedString,
154 pub message: SharedString,
155 pub commit_timestamp: i64,
156 pub author_email: SharedString,
157 pub author_name: SharedString,
158}
159
160#[derive(Debug)]
161pub struct CommitDiff {
162 pub files: Vec<CommitFile>,
163}
164
165#[derive(Debug)]
166pub struct CommitFile {
167 pub path: RepoPath,
168 pub old_text: Option<String>,
169 pub new_text: Option<String>,
170}
171
172impl CommitDetails {
173 pub fn short_sha(&self) -> SharedString {
174 self.sha[..SHORT_SHA_LENGTH].to_string().into()
175 }
176}
177
178#[derive(Debug, Clone, Hash, PartialEq, Eq)]
179pub struct Remote {
180 pub name: SharedString,
181}
182
183pub enum ResetMode {
184 /// Reset the branch pointer, leave index and worktree unchanged (this will make it look like things that were
185 /// committed are now staged).
186 Soft,
187 /// Reset the branch pointer and index, leave worktree unchanged (this makes it look as though things that were
188 /// committed are now unstaged).
189 Mixed,
190}
191
192pub trait GitRepository: Send + Sync {
193 fn reload_index(&self);
194
195 /// Returns the contents of an entry in the repository's index, or None if there is no entry for the given path.
196 ///
197 /// Also returns `None` for symlinks.
198 fn load_index_text(&self, path: RepoPath) -> BoxFuture<Option<String>>;
199
200 /// 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.
201 ///
202 /// Also returns `None` for symlinks.
203 fn load_committed_text(&self, path: RepoPath) -> BoxFuture<Option<String>>;
204
205 fn set_index_text(
206 &self,
207 path: RepoPath,
208 content: Option<String>,
209 env: Arc<HashMap<String, String>>,
210 ) -> BoxFuture<anyhow::Result<()>>;
211
212 /// Returns the URL of the remote with the given name.
213 fn remote_url(&self, name: &str) -> Option<String>;
214
215 /// Resolve a list of refs to SHAs.
216 fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<Result<Vec<Option<String>>>>;
217
218 fn head_sha(&self) -> BoxFuture<Option<String>> {
219 async move {
220 self.revparse_batch(vec!["HEAD".into()])
221 .await
222 .unwrap_or_default()
223 .into_iter()
224 .next()
225 .flatten()
226 }
227 .boxed()
228 }
229
230 fn merge_message(&self) -> BoxFuture<Option<String>>;
231
232 fn status(&self, path_prefixes: &[RepoPath]) -> BoxFuture<Result<GitStatus>>;
233
234 fn branches(&self) -> BoxFuture<Result<Vec<Branch>>>;
235
236 fn change_branch(&self, name: String) -> BoxFuture<Result<()>>;
237 fn create_branch(&self, name: String) -> BoxFuture<Result<()>>;
238
239 fn reset(
240 &self,
241 commit: String,
242 mode: ResetMode,
243 env: Arc<HashMap<String, String>>,
244 ) -> BoxFuture<Result<()>>;
245
246 fn checkout_files(
247 &self,
248 commit: String,
249 paths: Vec<RepoPath>,
250 env: Arc<HashMap<String, String>>,
251 ) -> BoxFuture<Result<()>>;
252
253 fn show(&self, commit: String) -> BoxFuture<Result<CommitDetails>>;
254
255 fn load_commit(&self, commit: String, cx: AsyncApp) -> BoxFuture<Result<CommitDiff>>;
256 fn blame(&self, path: RepoPath, content: Rope) -> BoxFuture<Result<crate::blame::Blame>>;
257
258 /// Returns the absolute path to the repository. For worktrees, this will be the path to the
259 /// worktree's gitdir within the main repository (typically `.git/worktrees/<name>`).
260 fn path(&self) -> PathBuf;
261
262 fn main_repository_path(&self) -> PathBuf;
263
264 /// Updates the index to match the worktree at the given paths.
265 ///
266 /// If any of the paths have been deleted from the worktree, they will be removed from the index if found there.
267 fn stage_paths(
268 &self,
269 paths: Vec<RepoPath>,
270 env: Arc<HashMap<String, String>>,
271 ) -> BoxFuture<Result<()>>;
272 /// Updates the index to match HEAD at the given paths.
273 ///
274 /// If any of the paths were previously staged but do not exist in HEAD, they will be removed from the index.
275 fn unstage_paths(
276 &self,
277 paths: Vec<RepoPath>,
278 env: Arc<HashMap<String, String>>,
279 ) -> BoxFuture<Result<()>>;
280
281 fn commit(
282 &self,
283 message: SharedString,
284 name_and_email: Option<(SharedString, SharedString)>,
285 options: CommitOptions,
286 env: Arc<HashMap<String, String>>,
287 ) -> BoxFuture<Result<()>>;
288
289 fn push(
290 &self,
291 branch_name: String,
292 upstream_name: String,
293 options: Option<PushOptions>,
294 askpass: AskPassDelegate,
295 env: Arc<HashMap<String, String>>,
296 // This method takes an AsyncApp to ensure it's invoked on the main thread,
297 // otherwise git-credentials-manager won't work.
298 cx: AsyncApp,
299 ) -> BoxFuture<Result<RemoteCommandOutput>>;
300
301 fn pull(
302 &self,
303 branch_name: String,
304 upstream_name: String,
305 askpass: AskPassDelegate,
306 env: Arc<HashMap<String, String>>,
307 // This method takes an AsyncApp to ensure it's invoked on the main thread,
308 // otherwise git-credentials-manager won't work.
309 cx: AsyncApp,
310 ) -> BoxFuture<Result<RemoteCommandOutput>>;
311
312 fn fetch(
313 &self,
314 askpass: AskPassDelegate,
315 env: Arc<HashMap<String, String>>,
316 // This method takes an AsyncApp to ensure it's invoked on the main thread,
317 // otherwise git-credentials-manager won't work.
318 cx: AsyncApp,
319 ) -> BoxFuture<Result<RemoteCommandOutput>>;
320
321 fn get_remotes(&self, branch_name: Option<String>) -> BoxFuture<Result<Vec<Remote>>>;
322
323 /// returns a list of remote branches that contain HEAD
324 fn check_for_pushed_commit(&self) -> BoxFuture<Result<Vec<SharedString>>>;
325
326 /// Run git diff
327 fn diff(&self, diff: DiffType) -> BoxFuture<Result<String>>;
328
329 /// Creates a checkpoint for the repository.
330 fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>>;
331
332 /// Resets to a previously-created checkpoint.
333 fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<Result<()>>;
334
335 /// Compares two checkpoints, returning true if they are equal
336 fn compare_checkpoints(
337 &self,
338 left: GitRepositoryCheckpoint,
339 right: GitRepositoryCheckpoint,
340 ) -> BoxFuture<Result<bool>>;
341
342 /// Computes a diff between two checkpoints.
343 fn diff_checkpoints(
344 &self,
345 base_checkpoint: GitRepositoryCheckpoint,
346 target_checkpoint: GitRepositoryCheckpoint,
347 ) -> BoxFuture<Result<String>>;
348}
349
350pub enum DiffType {
351 HeadToIndex,
352 HeadToWorktree,
353}
354
355#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]
356pub enum PushOptions {
357 SetUpstream,
358 Force,
359}
360
361impl std::fmt::Debug for dyn GitRepository {
362 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
363 f.debug_struct("dyn GitRepository<...>").finish()
364 }
365}
366
367pub struct RealGitRepository {
368 pub repository: Arc<Mutex<git2::Repository>>,
369 pub git_binary_path: PathBuf,
370 executor: BackgroundExecutor,
371}
372
373impl RealGitRepository {
374 pub fn new(
375 dotgit_path: &Path,
376 git_binary_path: Option<PathBuf>,
377 executor: BackgroundExecutor,
378 ) -> Option<Self> {
379 let workdir_root = dotgit_path.parent()?;
380 let repository = git2::Repository::open(workdir_root).log_err()?;
381 Some(Self {
382 repository: Arc::new(Mutex::new(repository)),
383 git_binary_path: git_binary_path.unwrap_or_else(|| PathBuf::from("git")),
384 executor,
385 })
386 }
387
388 fn working_directory(&self) -> Result<PathBuf> {
389 self.repository
390 .lock()
391 .workdir()
392 .context("failed to read git work directory")
393 .map(Path::to_path_buf)
394 }
395}
396
397#[derive(Clone, Debug)]
398pub struct GitRepositoryCheckpoint {
399 pub commit_sha: Oid,
400}
401
402impl GitRepository for RealGitRepository {
403 fn reload_index(&self) {
404 if let Ok(mut index) = self.repository.lock().index() {
405 _ = index.read(false);
406 }
407 }
408
409 fn path(&self) -> PathBuf {
410 let repo = self.repository.lock();
411 repo.path().into()
412 }
413
414 fn main_repository_path(&self) -> PathBuf {
415 let repo = self.repository.lock();
416 repo.commondir().into()
417 }
418
419 fn show(&self, commit: String) -> BoxFuture<Result<CommitDetails>> {
420 let working_directory = self.working_directory();
421 self.executor
422 .spawn(async move {
423 let working_directory = working_directory?;
424 let output = new_std_command("git")
425 .current_dir(&working_directory)
426 .args([
427 "--no-optional-locks",
428 "show",
429 "--no-patch",
430 "--format=%H%x00%B%x00%at%x00%ae%x00%an%x00",
431 &commit,
432 ])
433 .output()?;
434 let output = std::str::from_utf8(&output.stdout)?;
435 let fields = output.split('\0').collect::<Vec<_>>();
436 if fields.len() != 6 {
437 bail!("unexpected git-show output for {commit:?}: {output:?}")
438 }
439 let sha = fields[0].to_string().into();
440 let message = fields[1].to_string().into();
441 let commit_timestamp = fields[2].parse()?;
442 let author_email = fields[3].to_string().into();
443 let author_name = fields[4].to_string().into();
444 Ok(CommitDetails {
445 sha,
446 message,
447 commit_timestamp,
448 author_email,
449 author_name,
450 })
451 })
452 .boxed()
453 }
454
455 fn load_commit(&self, commit: String, cx: AsyncApp) -> BoxFuture<Result<CommitDiff>> {
456 let Some(working_directory) = self.repository.lock().workdir().map(ToOwned::to_owned)
457 else {
458 return future::ready(Err(anyhow!("no working directory"))).boxed();
459 };
460 cx.background_spawn(async move {
461 let show_output = util::command::new_std_command("git")
462 .current_dir(&working_directory)
463 .args([
464 "--no-optional-locks",
465 "show",
466 "--format=%P",
467 "-z",
468 "--no-renames",
469 "--name-status",
470 ])
471 .arg(&commit)
472 .stdin(Stdio::null())
473 .stdout(Stdio::piped())
474 .stderr(Stdio::piped())
475 .output()
476 .map_err(|e| anyhow!("Failed to start git show process: {e}"))?;
477
478 let show_stdout = String::from_utf8_lossy(&show_output.stdout);
479 let mut lines = show_stdout.split('\n');
480 let parent_sha = lines.next().unwrap().trim().trim_end_matches('\0');
481 let changes = parse_git_diff_name_status(lines.next().unwrap_or(""));
482
483 let mut cat_file_process = util::command::new_std_command("git")
484 .current_dir(&working_directory)
485 .args(["--no-optional-locks", "cat-file", "--batch=%(objectsize)"])
486 .stdin(Stdio::piped())
487 .stdout(Stdio::piped())
488 .stderr(Stdio::piped())
489 .spawn()
490 .map_err(|e| anyhow!("Failed to start git cat-file process: {e}"))?;
491
492 use std::io::Write as _;
493 let mut files = Vec::<CommitFile>::new();
494 let mut stdin = BufWriter::with_capacity(512, cat_file_process.stdin.take().unwrap());
495 let mut stdout = BufReader::new(cat_file_process.stdout.take().unwrap());
496 let mut info_line = String::new();
497 let mut newline = [b'\0'];
498 for (path, status_code) in changes {
499 match status_code {
500 StatusCode::Modified => {
501 writeln!(&mut stdin, "{commit}:{}", path.display())?;
502 writeln!(&mut stdin, "{parent_sha}:{}", path.display())?;
503 }
504 StatusCode::Added => {
505 writeln!(&mut stdin, "{commit}:{}", path.display())?;
506 }
507 StatusCode::Deleted => {
508 writeln!(&mut stdin, "{parent_sha}:{}", path.display())?;
509 }
510 _ => continue,
511 }
512 stdin.flush()?;
513
514 info_line.clear();
515 stdout.read_line(&mut info_line)?;
516
517 let len = info_line.trim_end().parse().with_context(|| {
518 format!("invalid object size output from cat-file {info_line}")
519 })?;
520 let mut text = vec![0; len];
521 stdout.read_exact(&mut text)?;
522 stdout.read_exact(&mut newline)?;
523 let text = String::from_utf8_lossy(&text).to_string();
524
525 let mut old_text = None;
526 let mut new_text = None;
527 match status_code {
528 StatusCode::Modified => {
529 info_line.clear();
530 stdout.read_line(&mut info_line)?;
531 let len = info_line.trim_end().parse().with_context(|| {
532 format!("invalid object size output from cat-file {}", info_line)
533 })?;
534 let mut parent_text = vec![0; len];
535 stdout.read_exact(&mut parent_text)?;
536 stdout.read_exact(&mut newline)?;
537 old_text = Some(String::from_utf8_lossy(&parent_text).to_string());
538 new_text = Some(text);
539 }
540 StatusCode::Added => new_text = Some(text),
541 StatusCode::Deleted => old_text = Some(text),
542 _ => continue,
543 }
544
545 files.push(CommitFile {
546 path: path.into(),
547 old_text,
548 new_text,
549 })
550 }
551
552 Ok(CommitDiff { files })
553 })
554 .boxed()
555 }
556
557 fn reset(
558 &self,
559 commit: String,
560 mode: ResetMode,
561 env: Arc<HashMap<String, String>>,
562 ) -> BoxFuture<Result<()>> {
563 async move {
564 let working_directory = self.working_directory();
565
566 let mode_flag = match mode {
567 ResetMode::Mixed => "--mixed",
568 ResetMode::Soft => "--soft",
569 };
570
571 let output = new_smol_command(&self.git_binary_path)
572 .envs(env.iter())
573 .current_dir(&working_directory?)
574 .args(["reset", mode_flag, &commit])
575 .output()
576 .await?;
577 if !output.status.success() {
578 return Err(anyhow!(
579 "Failed to reset:\n{}",
580 String::from_utf8_lossy(&output.stderr)
581 ));
582 }
583 Ok(())
584 }
585 .boxed()
586 }
587
588 fn checkout_files(
589 &self,
590 commit: String,
591 paths: Vec<RepoPath>,
592 env: Arc<HashMap<String, String>>,
593 ) -> BoxFuture<Result<()>> {
594 let working_directory = self.working_directory();
595 let git_binary_path = self.git_binary_path.clone();
596 async move {
597 if paths.is_empty() {
598 return Ok(());
599 }
600
601 let output = new_smol_command(&git_binary_path)
602 .current_dir(&working_directory?)
603 .envs(env.iter())
604 .args(["checkout", &commit, "--"])
605 .args(paths.iter().map(|path| path.as_ref()))
606 .output()
607 .await?;
608 if !output.status.success() {
609 return Err(anyhow!(
610 "Failed to checkout files:\n{}",
611 String::from_utf8_lossy(&output.stderr)
612 ));
613 }
614 Ok(())
615 }
616 .boxed()
617 }
618
619 fn load_index_text(&self, path: RepoPath) -> BoxFuture<Option<String>> {
620 // https://git-scm.com/book/en/v2/Git-Internals-Git-Objects
621 const GIT_MODE_SYMLINK: u32 = 0o120000;
622
623 let repo = self.repository.clone();
624 self.executor
625 .spawn(async move {
626 fn logic(repo: &git2::Repository, path: &RepoPath) -> Result<Option<String>> {
627 // This check is required because index.get_path() unwraps internally :(
628 check_path_to_repo_path_errors(path)?;
629
630 let mut index = repo.index()?;
631 index.read(false)?;
632
633 const STAGE_NORMAL: i32 = 0;
634 let oid = match index.get_path(path, STAGE_NORMAL) {
635 Some(entry) if entry.mode != GIT_MODE_SYMLINK => entry.id,
636 _ => return Ok(None),
637 };
638
639 let content = repo.find_blob(oid)?.content().to_owned();
640 Ok(String::from_utf8(content).ok())
641 }
642
643 match logic(&repo.lock(), &path) {
644 Ok(value) => return value,
645 Err(err) => log::error!("Error loading index text: {:?}", err),
646 }
647 None
648 })
649 .boxed()
650 }
651
652 fn load_committed_text(&self, path: RepoPath) -> BoxFuture<Option<String>> {
653 let repo = self.repository.clone();
654 self.executor
655 .spawn(async move {
656 let repo = repo.lock();
657 let head = repo.head().ok()?.peel_to_tree().log_err()?;
658 let entry = head.get_path(&path).ok()?;
659 if entry.filemode() == i32::from(git2::FileMode::Link) {
660 return None;
661 }
662 let content = repo.find_blob(entry.id()).log_err()?.content().to_owned();
663 String::from_utf8(content).ok()
664 })
665 .boxed()
666 }
667
668 fn set_index_text(
669 &self,
670 path: RepoPath,
671 content: Option<String>,
672 env: Arc<HashMap<String, String>>,
673 ) -> BoxFuture<anyhow::Result<()>> {
674 let working_directory = self.working_directory();
675 let git_binary_path = self.git_binary_path.clone();
676 self.executor
677 .spawn(async move {
678 let working_directory = working_directory?;
679 if let Some(content) = content {
680 let mut child = new_smol_command(&git_binary_path)
681 .current_dir(&working_directory)
682 .envs(env.iter())
683 .args(["hash-object", "-w", "--stdin"])
684 .stdin(Stdio::piped())
685 .stdout(Stdio::piped())
686 .spawn()?;
687 child
688 .stdin
689 .take()
690 .unwrap()
691 .write_all(content.as_bytes())
692 .await?;
693 let output = child.output().await?.stdout;
694 let sha = String::from_utf8(output)?;
695
696 log::debug!("indexing SHA: {sha}, path {path:?}");
697
698 let output = new_smol_command(&git_binary_path)
699 .current_dir(&working_directory)
700 .envs(env.iter())
701 .args(["update-index", "--add", "--cacheinfo", "100644", &sha])
702 .arg(path.to_unix_style())
703 .output()
704 .await?;
705
706 if !output.status.success() {
707 return Err(anyhow!(
708 "Failed to stage:\n{}",
709 String::from_utf8_lossy(&output.stderr)
710 ));
711 }
712 } else {
713 let output = new_smol_command(&git_binary_path)
714 .current_dir(&working_directory)
715 .envs(env.iter())
716 .args(["update-index", "--force-remove"])
717 .arg(path.to_unix_style())
718 .output()
719 .await?;
720
721 if !output.status.success() {
722 return Err(anyhow!(
723 "Failed to unstage:\n{}",
724 String::from_utf8_lossy(&output.stderr)
725 ));
726 }
727 }
728
729 Ok(())
730 })
731 .boxed()
732 }
733
734 fn remote_url(&self, name: &str) -> Option<String> {
735 let repo = self.repository.lock();
736 let remote = repo.find_remote(name).ok()?;
737 remote.url().map(|url| url.to_string())
738 }
739
740 fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<Result<Vec<Option<String>>>> {
741 let working_directory = self.working_directory();
742 self.executor
743 .spawn(async move {
744 let working_directory = working_directory?;
745 let mut process = new_std_command("git")
746 .current_dir(&working_directory)
747 .args([
748 "--no-optional-locks",
749 "cat-file",
750 "--batch-check=%(objectname)",
751 "-z",
752 ])
753 .stdin(Stdio::piped())
754 .stdout(Stdio::piped())
755 .stderr(Stdio::piped())
756 .spawn()?;
757
758 let stdin = process
759 .stdin
760 .take()
761 .ok_or_else(|| anyhow!("no stdin for git cat-file subprocess"))?;
762 let mut stdin = BufWriter::new(stdin);
763 for rev in &revs {
764 write!(&mut stdin, "{rev}\0")?;
765 }
766 drop(stdin);
767
768 let output = process.wait_with_output()?;
769 let output = std::str::from_utf8(&output.stdout)?;
770 let shas = output
771 .lines()
772 .map(|line| {
773 if line.ends_with("missing") {
774 None
775 } else {
776 Some(line.to_string())
777 }
778 })
779 .collect::<Vec<_>>();
780
781 if shas.len() != revs.len() {
782 // In an octopus merge, git cat-file still only outputs the first sha from MERGE_HEAD.
783 bail!("unexpected number of shas")
784 }
785
786 Ok(shas)
787 })
788 .boxed()
789 }
790
791 fn merge_message(&self) -> BoxFuture<Option<String>> {
792 let path = self.path().join("MERGE_MSG");
793 self.executor
794 .spawn(async move { std::fs::read_to_string(&path).ok() })
795 .boxed()
796 }
797
798 fn status(&self, path_prefixes: &[RepoPath]) -> BoxFuture<Result<GitStatus>> {
799 let git_binary_path = self.git_binary_path.clone();
800 let working_directory = self.working_directory();
801 let path_prefixes = path_prefixes.to_owned();
802 self.executor
803 .spawn(async move {
804 let output = new_std_command(&git_binary_path)
805 .current_dir(working_directory?)
806 .args(git_status_args(&path_prefixes))
807 .output()?;
808 if output.status.success() {
809 let stdout = String::from_utf8_lossy(&output.stdout);
810 stdout.parse()
811 } else {
812 let stderr = String::from_utf8_lossy(&output.stderr);
813 Err(anyhow!("git status failed: {}", stderr))
814 }
815 })
816 .boxed()
817 }
818
819 fn branches(&self) -> BoxFuture<Result<Vec<Branch>>> {
820 let working_directory = self.working_directory();
821 let git_binary_path = self.git_binary_path.clone();
822 self.executor
823 .spawn(async move {
824 let fields = [
825 "%(HEAD)",
826 "%(objectname)",
827 "%(parent)",
828 "%(refname)",
829 "%(upstream)",
830 "%(upstream:track)",
831 "%(committerdate:unix)",
832 "%(contents:subject)",
833 ]
834 .join("%00");
835 let args = vec![
836 "for-each-ref",
837 "refs/heads/**/*",
838 "refs/remotes/**/*",
839 "--format",
840 &fields,
841 ];
842 let working_directory = working_directory?;
843 let output = new_smol_command(&git_binary_path)
844 .current_dir(&working_directory)
845 .args(args)
846 .output()
847 .await?;
848
849 if !output.status.success() {
850 return Err(anyhow!(
851 "Failed to git git branches:\n{}",
852 String::from_utf8_lossy(&output.stderr)
853 ));
854 }
855
856 let input = String::from_utf8_lossy(&output.stdout);
857
858 let mut branches = parse_branch_input(&input)?;
859 if branches.is_empty() {
860 let args = vec!["symbolic-ref", "--quiet", "HEAD"];
861
862 let output = new_smol_command(&git_binary_path)
863 .current_dir(&working_directory)
864 .args(args)
865 .output()
866 .await?;
867
868 // git symbolic-ref returns a non-0 exit code if HEAD points
869 // to something other than a branch
870 if output.status.success() {
871 let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
872
873 branches.push(Branch {
874 ref_name: name.into(),
875 is_head: true,
876 upstream: None,
877 most_recent_commit: None,
878 });
879 }
880 }
881
882 Ok(branches)
883 })
884 .boxed()
885 }
886
887 fn change_branch(&self, name: String) -> BoxFuture<Result<()>> {
888 let repo = self.repository.clone();
889 self.executor
890 .spawn(async move {
891 let repo = repo.lock();
892 let branch = if let Ok(branch) = repo.find_branch(&name, BranchType::Local) {
893 branch
894 } else if let Ok(revision) = repo.find_branch(&name, BranchType::Remote) {
895 let (_, branch_name) =
896 name.split_once("/").context("Unexpected branch format")?;
897 let revision = revision.get();
898 let branch_commit = revision.peel_to_commit()?;
899 let mut branch = repo.branch(&branch_name, &branch_commit, false)?;
900 branch.set_upstream(Some(&name))?;
901 branch
902 } else {
903 return Err(anyhow!("Branch not found"));
904 };
905
906 let revision = branch.get();
907 let as_tree = revision.peel_to_tree()?;
908 repo.checkout_tree(as_tree.as_object(), None)?;
909 repo.set_head(
910 revision
911 .name()
912 .ok_or_else(|| anyhow!("Branch name could not be retrieved"))?,
913 )?;
914 Ok(())
915 })
916 .boxed()
917 }
918
919 fn create_branch(&self, name: String) -> BoxFuture<Result<()>> {
920 let repo = self.repository.clone();
921 self.executor
922 .spawn(async move {
923 let repo = repo.lock();
924 let current_commit = repo.head()?.peel_to_commit()?;
925 repo.branch(&name, ¤t_commit, false)?;
926 Ok(())
927 })
928 .boxed()
929 }
930
931 fn blame(&self, path: RepoPath, content: Rope) -> BoxFuture<Result<crate::blame::Blame>> {
932 let working_directory = self.working_directory();
933 let git_binary_path = self.git_binary_path.clone();
934
935 let remote_url = self
936 .remote_url("upstream")
937 .or_else(|| self.remote_url("origin"));
938
939 self.executor
940 .spawn(async move {
941 crate::blame::Blame::for_path(
942 &git_binary_path,
943 &working_directory?,
944 &path,
945 &content,
946 remote_url,
947 )
948 .await
949 })
950 .boxed()
951 }
952
953 fn diff(&self, diff: DiffType) -> BoxFuture<Result<String>> {
954 let working_directory = self.working_directory();
955 let git_binary_path = self.git_binary_path.clone();
956 self.executor
957 .spawn(async move {
958 let args = match diff {
959 DiffType::HeadToIndex => Some("--staged"),
960 DiffType::HeadToWorktree => None,
961 };
962
963 let output = new_smol_command(&git_binary_path)
964 .current_dir(&working_directory?)
965 .args(["diff"])
966 .args(args)
967 .output()
968 .await?;
969
970 if !output.status.success() {
971 return Err(anyhow!(
972 "Failed to run git diff:\n{}",
973 String::from_utf8_lossy(&output.stderr)
974 ));
975 }
976 Ok(String::from_utf8_lossy(&output.stdout).to_string())
977 })
978 .boxed()
979 }
980
981 fn stage_paths(
982 &self,
983 paths: Vec<RepoPath>,
984 env: Arc<HashMap<String, String>>,
985 ) -> BoxFuture<Result<()>> {
986 let working_directory = self.working_directory();
987 let git_binary_path = self.git_binary_path.clone();
988 self.executor
989 .spawn(async move {
990 if !paths.is_empty() {
991 let output = new_smol_command(&git_binary_path)
992 .current_dir(&working_directory?)
993 .envs(env.iter())
994 .args(["update-index", "--add", "--remove", "--"])
995 .args(paths.iter().map(|p| p.to_unix_style()))
996 .output()
997 .await?;
998
999 if !output.status.success() {
1000 return Err(anyhow!(
1001 "Failed to stage paths:\n{}",
1002 String::from_utf8_lossy(&output.stderr)
1003 ));
1004 }
1005 }
1006 Ok(())
1007 })
1008 .boxed()
1009 }
1010
1011 fn unstage_paths(
1012 &self,
1013 paths: Vec<RepoPath>,
1014 env: Arc<HashMap<String, String>>,
1015 ) -> BoxFuture<Result<()>> {
1016 let working_directory = self.working_directory();
1017 let git_binary_path = self.git_binary_path.clone();
1018
1019 self.executor
1020 .spawn(async move {
1021 if !paths.is_empty() {
1022 let output = new_smol_command(&git_binary_path)
1023 .current_dir(&working_directory?)
1024 .envs(env.iter())
1025 .args(["reset", "--quiet", "--"])
1026 .args(paths.iter().map(|p| p.as_ref()))
1027 .output()
1028 .await?;
1029
1030 if !output.status.success() {
1031 return Err(anyhow!(
1032 "Failed to unstage:\n{}",
1033 String::from_utf8_lossy(&output.stderr)
1034 ));
1035 }
1036 }
1037 Ok(())
1038 })
1039 .boxed()
1040 }
1041
1042 fn commit(
1043 &self,
1044 message: SharedString,
1045 name_and_email: Option<(SharedString, SharedString)>,
1046 options: CommitOptions,
1047 env: Arc<HashMap<String, String>>,
1048 ) -> BoxFuture<Result<()>> {
1049 let working_directory = self.working_directory();
1050 self.executor
1051 .spawn(async move {
1052 let mut cmd = new_smol_command("git");
1053 cmd.current_dir(&working_directory?)
1054 .envs(env.iter())
1055 .args(["commit", "--quiet", "-m"])
1056 .arg(&message.to_string())
1057 .arg("--cleanup=strip");
1058
1059 if options.amend {
1060 cmd.arg("--amend");
1061 }
1062
1063 if let Some((name, email)) = name_and_email {
1064 cmd.arg("--author").arg(&format!("{name} <{email}>"));
1065 }
1066
1067 let output = cmd.output().await?;
1068
1069 if !output.status.success() {
1070 return Err(anyhow!(
1071 "Failed to commit:\n{}",
1072 String::from_utf8_lossy(&output.stderr)
1073 ));
1074 }
1075 Ok(())
1076 })
1077 .boxed()
1078 }
1079
1080 fn push(
1081 &self,
1082 branch_name: String,
1083 remote_name: String,
1084 options: Option<PushOptions>,
1085 ask_pass: AskPassDelegate,
1086 env: Arc<HashMap<String, String>>,
1087 cx: AsyncApp,
1088 ) -> BoxFuture<Result<RemoteCommandOutput>> {
1089 let working_directory = self.working_directory();
1090 let executor = cx.background_executor().clone();
1091 async move {
1092 let working_directory = working_directory?;
1093 let mut command = new_smol_command("git");
1094 command
1095 .envs(env.iter())
1096 .current_dir(&working_directory)
1097 .args(["push"])
1098 .args(options.map(|option| match option {
1099 PushOptions::SetUpstream => "--set-upstream",
1100 PushOptions::Force => "--force-with-lease",
1101 }))
1102 .arg(remote_name)
1103 .arg(format!("{}:{}", branch_name, branch_name))
1104 .stdin(smol::process::Stdio::null())
1105 .stdout(smol::process::Stdio::piped())
1106 .stderr(smol::process::Stdio::piped());
1107
1108 run_git_command(env, ask_pass, command, &executor).await
1109 }
1110 .boxed()
1111 }
1112
1113 fn pull(
1114 &self,
1115 branch_name: String,
1116 remote_name: String,
1117 ask_pass: AskPassDelegate,
1118 env: Arc<HashMap<String, String>>,
1119 cx: AsyncApp,
1120 ) -> BoxFuture<Result<RemoteCommandOutput>> {
1121 let working_directory = self.working_directory();
1122 let executor = cx.background_executor().clone();
1123 async move {
1124 let mut command = new_smol_command("git");
1125 command
1126 .envs(env.iter())
1127 .current_dir(&working_directory?)
1128 .args(["pull"])
1129 .arg(remote_name)
1130 .arg(branch_name)
1131 .stdout(smol::process::Stdio::piped())
1132 .stderr(smol::process::Stdio::piped());
1133
1134 run_git_command(env, ask_pass, command, &executor).await
1135 }
1136 .boxed()
1137 }
1138
1139 fn fetch(
1140 &self,
1141 ask_pass: AskPassDelegate,
1142 env: Arc<HashMap<String, String>>,
1143 cx: AsyncApp,
1144 ) -> BoxFuture<Result<RemoteCommandOutput>> {
1145 let working_directory = self.working_directory();
1146 let executor = cx.background_executor().clone();
1147 async move {
1148 let mut command = new_smol_command("git");
1149 command
1150 .envs(env.iter())
1151 .current_dir(&working_directory?)
1152 .args(["fetch", "--all"])
1153 .stdout(smol::process::Stdio::piped())
1154 .stderr(smol::process::Stdio::piped());
1155
1156 run_git_command(env, ask_pass, command, &executor).await
1157 }
1158 .boxed()
1159 }
1160
1161 fn get_remotes(&self, branch_name: Option<String>) -> BoxFuture<Result<Vec<Remote>>> {
1162 let working_directory = self.working_directory();
1163 let git_binary_path = self.git_binary_path.clone();
1164 self.executor
1165 .spawn(async move {
1166 let working_directory = working_directory?;
1167 if let Some(branch_name) = branch_name {
1168 let output = new_smol_command(&git_binary_path)
1169 .current_dir(&working_directory)
1170 .args(["config", "--get"])
1171 .arg(format!("branch.{}.remote", branch_name))
1172 .output()
1173 .await?;
1174
1175 if output.status.success() {
1176 let remote_name = String::from_utf8_lossy(&output.stdout);
1177
1178 return Ok(vec![Remote {
1179 name: remote_name.trim().to_string().into(),
1180 }]);
1181 }
1182 }
1183
1184 let output = new_smol_command(&git_binary_path)
1185 .current_dir(&working_directory)
1186 .args(["remote"])
1187 .output()
1188 .await?;
1189
1190 if output.status.success() {
1191 let remote_names = String::from_utf8_lossy(&output.stdout)
1192 .split('\n')
1193 .filter(|name| !name.is_empty())
1194 .map(|name| Remote {
1195 name: name.trim().to_string().into(),
1196 })
1197 .collect();
1198
1199 return Ok(remote_names);
1200 } else {
1201 return Err(anyhow!(
1202 "Failed to get remotes:\n{}",
1203 String::from_utf8_lossy(&output.stderr)
1204 ));
1205 }
1206 })
1207 .boxed()
1208 }
1209
1210 fn check_for_pushed_commit(&self) -> BoxFuture<Result<Vec<SharedString>>> {
1211 let working_directory = self.working_directory();
1212 let git_binary_path = self.git_binary_path.clone();
1213 self.executor
1214 .spawn(async move {
1215 let working_directory = working_directory?;
1216 let git_cmd = async |args: &[&str]| -> Result<String> {
1217 let output = new_smol_command(&git_binary_path)
1218 .current_dir(&working_directory)
1219 .args(args)
1220 .output()
1221 .await?;
1222 if output.status.success() {
1223 Ok(String::from_utf8(output.stdout)?)
1224 } else {
1225 Err(anyhow!(String::from_utf8_lossy(&output.stderr).to_string()))
1226 }
1227 };
1228
1229 let head = git_cmd(&["rev-parse", "HEAD"])
1230 .await
1231 .context("Failed to get HEAD")?
1232 .trim()
1233 .to_owned();
1234
1235 let mut remote_branches = vec![];
1236 let mut add_if_matching = async |remote_head: &str| {
1237 if let Ok(merge_base) = git_cmd(&["merge-base", &head, remote_head]).await {
1238 if merge_base.trim() == head {
1239 if let Some(s) = remote_head.strip_prefix("refs/remotes/") {
1240 remote_branches.push(s.to_owned().into());
1241 }
1242 }
1243 }
1244 };
1245
1246 // check the main branch of each remote
1247 let remotes = git_cmd(&["remote"])
1248 .await
1249 .context("Failed to get remotes")?;
1250 for remote in remotes.lines() {
1251 if let Ok(remote_head) =
1252 git_cmd(&["symbolic-ref", &format!("refs/remotes/{remote}/HEAD")]).await
1253 {
1254 add_if_matching(remote_head.trim()).await;
1255 }
1256 }
1257
1258 // ... and the remote branch that the checked-out one is tracking
1259 if let Ok(remote_head) =
1260 git_cmd(&["rev-parse", "--symbolic-full-name", "@{u}"]).await
1261 {
1262 add_if_matching(remote_head.trim()).await;
1263 }
1264
1265 Ok(remote_branches)
1266 })
1267 .boxed()
1268 }
1269
1270 fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>> {
1271 let working_directory = self.working_directory();
1272 let git_binary_path = self.git_binary_path.clone();
1273 let executor = self.executor.clone();
1274 self.executor
1275 .spawn(async move {
1276 let working_directory = working_directory?;
1277 let mut git = GitBinary::new(git_binary_path, working_directory, executor)
1278 .envs(checkpoint_author_envs());
1279 git.with_temp_index(async |git| {
1280 let head_sha = git.run(&["rev-parse", "HEAD"]).await.ok();
1281 git.run(&["add", "--all"]).await?;
1282 let tree = git.run(&["write-tree"]).await?;
1283 let checkpoint_sha = if let Some(head_sha) = head_sha.as_deref() {
1284 git.run(&["commit-tree", &tree, "-p", head_sha, "-m", "Checkpoint"])
1285 .await?
1286 } else {
1287 git.run(&["commit-tree", &tree, "-m", "Checkpoint"]).await?
1288 };
1289
1290 Ok(GitRepositoryCheckpoint {
1291 commit_sha: checkpoint_sha.parse()?,
1292 })
1293 })
1294 .await
1295 })
1296 .boxed()
1297 }
1298
1299 fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<Result<()>> {
1300 let working_directory = self.working_directory();
1301 let git_binary_path = self.git_binary_path.clone();
1302
1303 let executor = self.executor.clone();
1304 self.executor
1305 .spawn(async move {
1306 let working_directory = working_directory?;
1307
1308 let mut git = GitBinary::new(git_binary_path, working_directory, executor);
1309 git.run(&[
1310 "restore",
1311 "--source",
1312 &checkpoint.commit_sha.to_string(),
1313 "--worktree",
1314 ".",
1315 ])
1316 .await?;
1317
1318 git.with_temp_index(async move |git| {
1319 git.run(&["read-tree", &checkpoint.commit_sha.to_string()])
1320 .await?;
1321 git.run(&["clean", "-d", "--force"]).await
1322 })
1323 .await?;
1324
1325 Ok(())
1326 })
1327 .boxed()
1328 }
1329
1330 fn compare_checkpoints(
1331 &self,
1332 left: GitRepositoryCheckpoint,
1333 right: GitRepositoryCheckpoint,
1334 ) -> BoxFuture<Result<bool>> {
1335 let working_directory = self.working_directory();
1336 let git_binary_path = self.git_binary_path.clone();
1337
1338 let executor = self.executor.clone();
1339 self.executor
1340 .spawn(async move {
1341 let working_directory = working_directory?;
1342 let git = GitBinary::new(git_binary_path, working_directory, executor);
1343 let result = git
1344 .run(&[
1345 "diff-tree",
1346 "--quiet",
1347 &left.commit_sha.to_string(),
1348 &right.commit_sha.to_string(),
1349 ])
1350 .await;
1351 match result {
1352 Ok(_) => Ok(true),
1353 Err(error) => {
1354 if let Some(GitBinaryCommandError { status, .. }) =
1355 error.downcast_ref::<GitBinaryCommandError>()
1356 {
1357 if status.code() == Some(1) {
1358 return Ok(false);
1359 }
1360 }
1361
1362 Err(error)
1363 }
1364 }
1365 })
1366 .boxed()
1367 }
1368
1369 fn diff_checkpoints(
1370 &self,
1371 base_checkpoint: GitRepositoryCheckpoint,
1372 target_checkpoint: GitRepositoryCheckpoint,
1373 ) -> BoxFuture<Result<String>> {
1374 let working_directory = self.working_directory();
1375 let git_binary_path = self.git_binary_path.clone();
1376
1377 let executor = self.executor.clone();
1378 self.executor
1379 .spawn(async move {
1380 let working_directory = working_directory?;
1381 let git = GitBinary::new(git_binary_path, working_directory, executor);
1382 git.run(&[
1383 "diff",
1384 "--find-renames",
1385 "--patch",
1386 &base_checkpoint.commit_sha.to_string(),
1387 &target_checkpoint.commit_sha.to_string(),
1388 ])
1389 .await
1390 })
1391 .boxed()
1392 }
1393}
1394
1395fn git_status_args(path_prefixes: &[RepoPath]) -> Vec<OsString> {
1396 let mut args = vec![
1397 OsString::from("--no-optional-locks"),
1398 OsString::from("status"),
1399 OsString::from("--porcelain=v1"),
1400 OsString::from("--untracked-files=all"),
1401 OsString::from("--no-renames"),
1402 OsString::from("-z"),
1403 ];
1404 args.extend(path_prefixes.iter().map(|path_prefix| {
1405 if path_prefix.0.as_ref() == Path::new("") {
1406 Path::new(".").into()
1407 } else {
1408 path_prefix.as_os_str().into()
1409 }
1410 }));
1411 args
1412}
1413
1414struct GitBinary {
1415 git_binary_path: PathBuf,
1416 working_directory: PathBuf,
1417 executor: BackgroundExecutor,
1418 index_file_path: Option<PathBuf>,
1419 envs: HashMap<String, String>,
1420}
1421
1422impl GitBinary {
1423 fn new(
1424 git_binary_path: PathBuf,
1425 working_directory: PathBuf,
1426 executor: BackgroundExecutor,
1427 ) -> Self {
1428 Self {
1429 git_binary_path,
1430 working_directory,
1431 executor,
1432 index_file_path: None,
1433 envs: HashMap::default(),
1434 }
1435 }
1436
1437 fn envs(mut self, envs: HashMap<String, String>) -> Self {
1438 self.envs = envs;
1439 self
1440 }
1441
1442 pub async fn with_temp_index<R>(
1443 &mut self,
1444 f: impl AsyncFnOnce(&Self) -> Result<R>,
1445 ) -> Result<R> {
1446 let index_file_path = self.path_for_index_id(Uuid::new_v4());
1447
1448 let delete_temp_index = util::defer({
1449 let index_file_path = index_file_path.clone();
1450 let executor = self.executor.clone();
1451 move || {
1452 executor
1453 .spawn(async move {
1454 smol::fs::remove_file(index_file_path).await.log_err();
1455 })
1456 .detach();
1457 }
1458 });
1459
1460 // Copy the default index file so that Git doesn't have to rebuild the
1461 // whole index from scratch. This might fail if this is an empty repository.
1462 smol::fs::copy(
1463 self.working_directory.join(".git").join("index"),
1464 &index_file_path,
1465 )
1466 .await
1467 .ok();
1468
1469 self.index_file_path = Some(index_file_path.clone());
1470 let result = f(self).await;
1471 self.index_file_path = None;
1472 let result = result?;
1473
1474 smol::fs::remove_file(index_file_path).await.ok();
1475 delete_temp_index.abort();
1476
1477 Ok(result)
1478 }
1479
1480 fn path_for_index_id(&self, id: Uuid) -> PathBuf {
1481 self.working_directory
1482 .join(".git")
1483 .join(format!("index-{}.tmp", id))
1484 }
1485
1486 pub async fn run<S>(&self, args: impl IntoIterator<Item = S>) -> Result<String>
1487 where
1488 S: AsRef<OsStr>,
1489 {
1490 let mut stdout = self.run_raw(args).await?;
1491 if stdout.chars().last() == Some('\n') {
1492 stdout.pop();
1493 }
1494 Ok(stdout)
1495 }
1496
1497 /// Returns the result of the command without trimming the trailing newline.
1498 pub async fn run_raw<S>(&self, args: impl IntoIterator<Item = S>) -> Result<String>
1499 where
1500 S: AsRef<OsStr>,
1501 {
1502 let mut command = self.build_command(args);
1503 let output = command.output().await?;
1504 if output.status.success() {
1505 Ok(String::from_utf8(output.stdout)?)
1506 } else {
1507 Err(anyhow!(GitBinaryCommandError {
1508 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
1509 status: output.status,
1510 }))
1511 }
1512 }
1513
1514 fn build_command<S>(&self, args: impl IntoIterator<Item = S>) -> smol::process::Command
1515 where
1516 S: AsRef<OsStr>,
1517 {
1518 let mut command = new_smol_command(&self.git_binary_path);
1519 command.current_dir(&self.working_directory);
1520 command.args(args);
1521 if let Some(index_file_path) = self.index_file_path.as_ref() {
1522 command.env("GIT_INDEX_FILE", index_file_path);
1523 }
1524 command.envs(&self.envs);
1525 command
1526 }
1527}
1528
1529#[derive(Error, Debug)]
1530#[error("Git command failed: {stdout}")]
1531struct GitBinaryCommandError {
1532 stdout: String,
1533 status: ExitStatus,
1534}
1535
1536async fn run_git_command(
1537 env: Arc<HashMap<String, String>>,
1538 ask_pass: AskPassDelegate,
1539 mut command: smol::process::Command,
1540 executor: &BackgroundExecutor,
1541) -> Result<RemoteCommandOutput> {
1542 if env.contains_key("GIT_ASKPASS") {
1543 let git_process = command.spawn()?;
1544 let output = git_process.output().await?;
1545 if !output.status.success() {
1546 Err(anyhow!("{}", String::from_utf8_lossy(&output.stderr)))
1547 } else {
1548 Ok(RemoteCommandOutput {
1549 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
1550 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
1551 })
1552 }
1553 } else {
1554 let ask_pass = AskPassSession::new(executor, ask_pass).await?;
1555 command
1556 .env("GIT_ASKPASS", ask_pass.script_path())
1557 .env("SSH_ASKPASS", ask_pass.script_path())
1558 .env("SSH_ASKPASS_REQUIRE", "force");
1559 let git_process = command.spawn()?;
1560
1561 run_askpass_command(ask_pass, git_process).await
1562 }
1563}
1564
1565async fn run_askpass_command(
1566 mut ask_pass: AskPassSession,
1567 git_process: smol::process::Child,
1568) -> std::result::Result<RemoteCommandOutput, anyhow::Error> {
1569 select_biased! {
1570 result = ask_pass.run().fuse() => {
1571 match result {
1572 AskPassResult::CancelledByUser => {
1573 Err(anyhow!(REMOTE_CANCELLED_BY_USER))?
1574 }
1575 AskPassResult::Timedout => {
1576 Err(anyhow!("Connecting to host timed out"))?
1577 }
1578 }
1579 }
1580 output = git_process.output().fuse() => {
1581 let output = output?;
1582 if !output.status.success() {
1583 Err(anyhow!(
1584 "{}",
1585 String::from_utf8_lossy(&output.stderr)
1586 ))
1587 } else {
1588 Ok(RemoteCommandOutput {
1589 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
1590 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
1591 })
1592 }
1593 }
1594 }
1595}
1596
1597pub static WORK_DIRECTORY_REPO_PATH: LazyLock<RepoPath> =
1598 LazyLock::new(|| RepoPath(Path::new("").into()));
1599
1600#[derive(Clone, Debug, Ord, Hash, PartialOrd, Eq, PartialEq)]
1601pub struct RepoPath(pub Arc<Path>);
1602
1603impl RepoPath {
1604 pub fn new(path: PathBuf) -> Self {
1605 debug_assert!(path.is_relative(), "Repo paths must be relative");
1606
1607 RepoPath(path.into())
1608 }
1609
1610 pub fn from_str(path: &str) -> Self {
1611 let path = Path::new(path);
1612 debug_assert!(path.is_relative(), "Repo paths must be relative");
1613
1614 RepoPath(path.into())
1615 }
1616
1617 pub fn to_unix_style(&self) -> Cow<'_, OsStr> {
1618 #[cfg(target_os = "windows")]
1619 {
1620 use std::ffi::OsString;
1621
1622 let path = self.0.as_os_str().to_string_lossy().replace("\\", "/");
1623 Cow::Owned(OsString::from(path))
1624 }
1625 #[cfg(not(target_os = "windows"))]
1626 {
1627 Cow::Borrowed(self.0.as_os_str())
1628 }
1629 }
1630}
1631
1632impl std::fmt::Display for RepoPath {
1633 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1634 self.0.to_string_lossy().fmt(f)
1635 }
1636}
1637
1638impl From<&Path> for RepoPath {
1639 fn from(value: &Path) -> Self {
1640 RepoPath::new(value.into())
1641 }
1642}
1643
1644impl From<Arc<Path>> for RepoPath {
1645 fn from(value: Arc<Path>) -> Self {
1646 RepoPath(value)
1647 }
1648}
1649
1650impl From<PathBuf> for RepoPath {
1651 fn from(value: PathBuf) -> Self {
1652 RepoPath::new(value)
1653 }
1654}
1655
1656impl From<&str> for RepoPath {
1657 fn from(value: &str) -> Self {
1658 Self::from_str(value)
1659 }
1660}
1661
1662impl Default for RepoPath {
1663 fn default() -> Self {
1664 RepoPath(Path::new("").into())
1665 }
1666}
1667
1668impl AsRef<Path> for RepoPath {
1669 fn as_ref(&self) -> &Path {
1670 self.0.as_ref()
1671 }
1672}
1673
1674impl std::ops::Deref for RepoPath {
1675 type Target = Path;
1676
1677 fn deref(&self) -> &Self::Target {
1678 &self.0
1679 }
1680}
1681
1682impl Borrow<Path> for RepoPath {
1683 fn borrow(&self) -> &Path {
1684 self.0.as_ref()
1685 }
1686}
1687
1688#[derive(Debug)]
1689pub struct RepoPathDescendants<'a>(pub &'a Path);
1690
1691impl MapSeekTarget<RepoPath> for RepoPathDescendants<'_> {
1692 fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
1693 if key.starts_with(self.0) {
1694 Ordering::Greater
1695 } else {
1696 self.0.cmp(key)
1697 }
1698 }
1699}
1700
1701fn parse_branch_input(input: &str) -> Result<Vec<Branch>> {
1702 let mut branches = Vec::new();
1703 for line in input.split('\n') {
1704 if line.is_empty() {
1705 continue;
1706 }
1707 let mut fields = line.split('\x00');
1708 let is_current_branch = fields.next().context("no HEAD")? == "*";
1709 let head_sha: SharedString = fields.next().context("no objectname")?.to_string().into();
1710 let parent_sha: SharedString = fields.next().context("no parent")?.to_string().into();
1711 let ref_name = fields.next().context("no refname")?.to_string().into();
1712 let upstream_name = fields.next().context("no upstream")?.to_string();
1713 let upstream_tracking = parse_upstream_track(fields.next().context("no upstream:track")?)?;
1714 let commiterdate = fields.next().context("no committerdate")?.parse::<i64>()?;
1715 let subject: SharedString = fields
1716 .next()
1717 .context("no contents:subject")?
1718 .to_string()
1719 .into();
1720
1721 branches.push(Branch {
1722 is_head: is_current_branch,
1723 ref_name: ref_name,
1724 most_recent_commit: Some(CommitSummary {
1725 sha: head_sha,
1726 subject,
1727 commit_timestamp: commiterdate,
1728 has_parent: !parent_sha.is_empty(),
1729 }),
1730 upstream: if upstream_name.is_empty() {
1731 None
1732 } else {
1733 Some(Upstream {
1734 ref_name: upstream_name.into(),
1735 tracking: upstream_tracking,
1736 })
1737 },
1738 })
1739 }
1740
1741 Ok(branches)
1742}
1743
1744fn parse_upstream_track(upstream_track: &str) -> Result<UpstreamTracking> {
1745 if upstream_track == "" {
1746 return Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
1747 ahead: 0,
1748 behind: 0,
1749 }));
1750 }
1751
1752 let upstream_track = upstream_track
1753 .strip_prefix("[")
1754 .ok_or_else(|| anyhow!("missing ["))?;
1755 let upstream_track = upstream_track
1756 .strip_suffix("]")
1757 .ok_or_else(|| anyhow!("missing ["))?;
1758 let mut ahead: u32 = 0;
1759 let mut behind: u32 = 0;
1760 for component in upstream_track.split(", ") {
1761 if component == "gone" {
1762 return Ok(UpstreamTracking::Gone);
1763 }
1764 if let Some(ahead_num) = component.strip_prefix("ahead ") {
1765 ahead = ahead_num.parse::<u32>()?;
1766 }
1767 if let Some(behind_num) = component.strip_prefix("behind ") {
1768 behind = behind_num.parse::<u32>()?;
1769 }
1770 }
1771 Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
1772 ahead,
1773 behind,
1774 }))
1775}
1776
1777fn check_path_to_repo_path_errors(relative_file_path: &Path) -> Result<()> {
1778 match relative_file_path.components().next() {
1779 None => anyhow::bail!("repo path should not be empty"),
1780 Some(Component::Prefix(_)) => anyhow::bail!(
1781 "repo path `{}` should be relative, not a windows prefix",
1782 relative_file_path.to_string_lossy()
1783 ),
1784 Some(Component::RootDir) => {
1785 anyhow::bail!(
1786 "repo path `{}` should be relative",
1787 relative_file_path.to_string_lossy()
1788 )
1789 }
1790 Some(Component::CurDir) => {
1791 anyhow::bail!(
1792 "repo path `{}` should not start with `.`",
1793 relative_file_path.to_string_lossy()
1794 )
1795 }
1796 Some(Component::ParentDir) => {
1797 anyhow::bail!(
1798 "repo path `{}` should not start with `..`",
1799 relative_file_path.to_string_lossy()
1800 )
1801 }
1802 _ => Ok(()),
1803 }
1804}
1805
1806fn checkpoint_author_envs() -> HashMap<String, String> {
1807 HashMap::from_iter([
1808 ("GIT_AUTHOR_NAME".to_string(), "Zed".to_string()),
1809 ("GIT_AUTHOR_EMAIL".to_string(), "hi@zed.dev".to_string()),
1810 ("GIT_COMMITTER_NAME".to_string(), "Zed".to_string()),
1811 ("GIT_COMMITTER_EMAIL".to_string(), "hi@zed.dev".to_string()),
1812 ])
1813}
1814
1815#[cfg(test)]
1816mod tests {
1817 use super::*;
1818 use gpui::TestAppContext;
1819
1820 #[gpui::test]
1821 async fn test_checkpoint_basic(cx: &mut TestAppContext) {
1822 cx.executor().allow_parking();
1823
1824 let repo_dir = tempfile::tempdir().unwrap();
1825
1826 git2::Repository::init(repo_dir.path()).unwrap();
1827 let file_path = repo_dir.path().join("file");
1828 smol::fs::write(&file_path, "initial").await.unwrap();
1829
1830 let repo =
1831 RealGitRepository::new(&repo_dir.path().join(".git"), None, cx.executor()).unwrap();
1832 repo.stage_paths(
1833 vec![RepoPath::from_str("file")],
1834 Arc::new(HashMap::default()),
1835 )
1836 .await
1837 .unwrap();
1838 repo.commit(
1839 "Initial commit".into(),
1840 None,
1841 CommitOptions::default(),
1842 Arc::new(checkpoint_author_envs()),
1843 )
1844 .await
1845 .unwrap();
1846
1847 smol::fs::write(&file_path, "modified before checkpoint")
1848 .await
1849 .unwrap();
1850 smol::fs::write(repo_dir.path().join("new_file_before_checkpoint"), "1")
1851 .await
1852 .unwrap();
1853 let checkpoint = repo.checkpoint().await.unwrap();
1854
1855 // Ensure the user can't see any branches after creating a checkpoint.
1856 assert_eq!(repo.branches().await.unwrap().len(), 1);
1857
1858 smol::fs::write(&file_path, "modified after checkpoint")
1859 .await
1860 .unwrap();
1861 repo.stage_paths(
1862 vec![RepoPath::from_str("file")],
1863 Arc::new(HashMap::default()),
1864 )
1865 .await
1866 .unwrap();
1867 repo.commit(
1868 "Commit after checkpoint".into(),
1869 None,
1870 CommitOptions::default(),
1871 Arc::new(checkpoint_author_envs()),
1872 )
1873 .await
1874 .unwrap();
1875
1876 smol::fs::remove_file(repo_dir.path().join("new_file_before_checkpoint"))
1877 .await
1878 .unwrap();
1879 smol::fs::write(repo_dir.path().join("new_file_after_checkpoint"), "2")
1880 .await
1881 .unwrap();
1882
1883 // Ensure checkpoint stays alive even after a Git GC.
1884 repo.gc().await.unwrap();
1885 repo.restore_checkpoint(checkpoint.clone()).await.unwrap();
1886
1887 assert_eq!(
1888 smol::fs::read_to_string(&file_path).await.unwrap(),
1889 "modified before checkpoint"
1890 );
1891 assert_eq!(
1892 smol::fs::read_to_string(repo_dir.path().join("new_file_before_checkpoint"))
1893 .await
1894 .unwrap(),
1895 "1"
1896 );
1897 assert_eq!(
1898 smol::fs::read_to_string(repo_dir.path().join("new_file_after_checkpoint"))
1899 .await
1900 .ok(),
1901 None
1902 );
1903 }
1904
1905 #[gpui::test]
1906 async fn test_checkpoint_empty_repo(cx: &mut TestAppContext) {
1907 cx.executor().allow_parking();
1908
1909 let repo_dir = tempfile::tempdir().unwrap();
1910 git2::Repository::init(repo_dir.path()).unwrap();
1911 let repo =
1912 RealGitRepository::new(&repo_dir.path().join(".git"), None, cx.executor()).unwrap();
1913
1914 smol::fs::write(repo_dir.path().join("foo"), "foo")
1915 .await
1916 .unwrap();
1917 let checkpoint_sha = repo.checkpoint().await.unwrap();
1918
1919 // Ensure the user can't see any branches after creating a checkpoint.
1920 assert_eq!(repo.branches().await.unwrap().len(), 1);
1921
1922 smol::fs::write(repo_dir.path().join("foo"), "bar")
1923 .await
1924 .unwrap();
1925 smol::fs::write(repo_dir.path().join("baz"), "qux")
1926 .await
1927 .unwrap();
1928 repo.restore_checkpoint(checkpoint_sha).await.unwrap();
1929 assert_eq!(
1930 smol::fs::read_to_string(repo_dir.path().join("foo"))
1931 .await
1932 .unwrap(),
1933 "foo"
1934 );
1935 assert_eq!(
1936 smol::fs::read_to_string(repo_dir.path().join("baz"))
1937 .await
1938 .ok(),
1939 None
1940 );
1941 }
1942
1943 #[gpui::test]
1944 async fn test_compare_checkpoints(cx: &mut TestAppContext) {
1945 cx.executor().allow_parking();
1946
1947 let repo_dir = tempfile::tempdir().unwrap();
1948 git2::Repository::init(repo_dir.path()).unwrap();
1949 let repo =
1950 RealGitRepository::new(&repo_dir.path().join(".git"), None, cx.executor()).unwrap();
1951
1952 smol::fs::write(repo_dir.path().join("file1"), "content1")
1953 .await
1954 .unwrap();
1955 let checkpoint1 = repo.checkpoint().await.unwrap();
1956
1957 smol::fs::write(repo_dir.path().join("file2"), "content2")
1958 .await
1959 .unwrap();
1960 let checkpoint2 = repo.checkpoint().await.unwrap();
1961
1962 assert!(
1963 !repo
1964 .compare_checkpoints(checkpoint1, checkpoint2.clone())
1965 .await
1966 .unwrap()
1967 );
1968
1969 let checkpoint3 = repo.checkpoint().await.unwrap();
1970 assert!(
1971 repo.compare_checkpoints(checkpoint2, checkpoint3)
1972 .await
1973 .unwrap()
1974 );
1975 }
1976
1977 #[test]
1978 fn test_branches_parsing() {
1979 // suppress "help: octal escapes are not supported, `\0` is always null"
1980 #[allow(clippy::octal_escapes)]
1981 let input = "*\0060964da10574cd9bf06463a53bf6e0769c5c45e\0\0refs/heads/zed-patches\0refs/remotes/origin/zed-patches\0\01733187470\0generated protobuf\n";
1982 assert_eq!(
1983 parse_branch_input(&input).unwrap(),
1984 vec![Branch {
1985 is_head: true,
1986 ref_name: "refs/heads/zed-patches".into(),
1987 upstream: Some(Upstream {
1988 ref_name: "refs/remotes/origin/zed-patches".into(),
1989 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
1990 ahead: 0,
1991 behind: 0
1992 })
1993 }),
1994 most_recent_commit: Some(CommitSummary {
1995 sha: "060964da10574cd9bf06463a53bf6e0769c5c45e".into(),
1996 subject: "generated protobuf".into(),
1997 commit_timestamp: 1733187470,
1998 has_parent: false,
1999 })
2000 }]
2001 )
2002 }
2003
2004 impl RealGitRepository {
2005 /// Force a Git garbage collection on the repository.
2006 fn gc(&self) -> BoxFuture<Result<()>> {
2007 let working_directory = self.working_directory();
2008 let git_binary_path = self.git_binary_path.clone();
2009 let executor = self.executor.clone();
2010 self.executor
2011 .spawn(async move {
2012 let git_binary_path = git_binary_path.clone();
2013 let working_directory = working_directory?;
2014 let git = GitBinary::new(git_binary_path, working_directory, executor);
2015 git.run(&["gc", "--prune"]).await?;
2016 Ok(())
2017 })
2018 .boxed()
2019 }
2020 }
2021}