1use crate::commit::parse_git_diff_name_status;
2use crate::stash::GitStash;
3use crate::status::{DiffTreeType, GitStatus, StatusCode, TreeDiff};
4use crate::{Oid, RunHook, SHORT_SHA_LENGTH};
5use anyhow::{Context as _, Result, anyhow, bail};
6use collections::HashMap;
7use futures::future::BoxFuture;
8use futures::io::BufWriter;
9use futures::{AsyncWriteExt, FutureExt as _, select_biased};
10use git2::{BranchType, ErrorCode};
11use gpui::{AppContext as _, AsyncApp, BackgroundExecutor, SharedString, Task};
12use parking_lot::Mutex;
13use rope::Rope;
14use schemars::JsonSchema;
15use serde::Deserialize;
16use smol::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
17
18use std::collections::HashSet;
19use std::ffi::{OsStr, OsString};
20use std::process::{ExitStatus, Stdio};
21use std::{
22 cmp::Ordering,
23 future,
24 path::{Path, PathBuf},
25 sync::Arc,
26};
27use sum_tree::MapSeekTarget;
28use thiserror::Error;
29use util::command::new_smol_command;
30use util::paths::PathStyle;
31use util::rel_path::RelPath;
32use util::{ResultExt, paths};
33use uuid::Uuid;
34
35pub use askpass::{AskPassDelegate, AskPassResult, AskPassSession};
36
37pub const REMOTE_CANCELLED_BY_USER: &str = "Operation cancelled by user";
38
39#[derive(Clone, Debug, Hash, PartialEq, Eq)]
40pub struct Branch {
41 pub is_head: bool,
42 pub ref_name: SharedString,
43 pub upstream: Option<Upstream>,
44 pub most_recent_commit: Option<CommitSummary>,
45}
46
47impl Branch {
48 pub fn name(&self) -> &str {
49 self.ref_name
50 .as_ref()
51 .strip_prefix("refs/heads/")
52 .or_else(|| self.ref_name.as_ref().strip_prefix("refs/remotes/"))
53 .unwrap_or(self.ref_name.as_ref())
54 }
55
56 pub fn is_remote(&self) -> bool {
57 self.ref_name.starts_with("refs/remotes/")
58 }
59
60 pub fn remote_name(&self) -> Option<&str> {
61 self.ref_name
62 .strip_prefix("refs/remotes/")
63 .and_then(|stripped| stripped.split("/").next())
64 }
65
66 pub fn tracking_status(&self) -> Option<UpstreamTrackingStatus> {
67 self.upstream
68 .as_ref()
69 .and_then(|upstream| upstream.tracking.status())
70 }
71
72 pub fn priority_key(&self) -> (bool, Option<i64>) {
73 (
74 self.is_head,
75 self.most_recent_commit
76 .as_ref()
77 .map(|commit| commit.commit_timestamp),
78 )
79 }
80}
81
82#[derive(Clone, Debug, Hash, PartialEq, Eq)]
83pub struct Worktree {
84 pub path: PathBuf,
85 pub ref_name: SharedString,
86 pub sha: SharedString,
87}
88
89impl Worktree {
90 pub fn branch(&self) -> &str {
91 self.ref_name
92 .as_ref()
93 .strip_prefix("refs/heads/")
94 .or_else(|| self.ref_name.as_ref().strip_prefix("refs/remotes/"))
95 .unwrap_or(self.ref_name.as_ref())
96 }
97}
98
99pub fn parse_worktrees_from_str<T: AsRef<str>>(raw_worktrees: T) -> Vec<Worktree> {
100 let mut worktrees = Vec::new();
101 let entries = raw_worktrees.as_ref().split("\n\n");
102 for entry in entries {
103 let mut parts = entry.splitn(3, '\n');
104 let path = parts
105 .next()
106 .and_then(|p| p.split_once(' ').map(|(_, path)| path.to_string()));
107 let sha = parts
108 .next()
109 .and_then(|p| p.split_once(' ').map(|(_, sha)| sha.to_string()));
110 let ref_name = parts
111 .next()
112 .and_then(|p| p.split_once(' ').map(|(_, ref_name)| ref_name.to_string()));
113
114 if let (Some(path), Some(sha), Some(ref_name)) = (path, sha, ref_name) {
115 worktrees.push(Worktree {
116 path: PathBuf::from(path),
117 ref_name: ref_name.into(),
118 sha: sha.into(),
119 })
120 }
121 }
122
123 worktrees
124}
125
126#[derive(Clone, Debug, Hash, PartialEq, Eq)]
127pub struct Upstream {
128 pub ref_name: SharedString,
129 pub tracking: UpstreamTracking,
130}
131
132impl Upstream {
133 pub fn is_remote(&self) -> bool {
134 self.remote_name().is_some()
135 }
136
137 pub fn remote_name(&self) -> Option<&str> {
138 self.ref_name
139 .strip_prefix("refs/remotes/")
140 .and_then(|stripped| stripped.split("/").next())
141 }
142
143 pub fn stripped_ref_name(&self) -> Option<&str> {
144 self.ref_name.strip_prefix("refs/remotes/")
145 }
146}
147
148#[derive(Clone, Copy, Default)]
149pub struct CommitOptions {
150 pub amend: bool,
151 pub signoff: bool,
152}
153
154#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
155pub enum UpstreamTracking {
156 /// Remote ref not present in local repository.
157 Gone,
158 /// Remote ref present in local repository (fetched from remote).
159 Tracked(UpstreamTrackingStatus),
160}
161
162impl From<UpstreamTrackingStatus> for UpstreamTracking {
163 fn from(status: UpstreamTrackingStatus) -> Self {
164 UpstreamTracking::Tracked(status)
165 }
166}
167
168impl UpstreamTracking {
169 pub fn is_gone(&self) -> bool {
170 matches!(self, UpstreamTracking::Gone)
171 }
172
173 pub fn status(&self) -> Option<UpstreamTrackingStatus> {
174 match self {
175 UpstreamTracking::Gone => None,
176 UpstreamTracking::Tracked(status) => Some(*status),
177 }
178 }
179}
180
181#[derive(Debug, Clone)]
182pub struct RemoteCommandOutput {
183 pub stdout: String,
184 pub stderr: String,
185}
186
187impl RemoteCommandOutput {
188 pub fn is_empty(&self) -> bool {
189 self.stdout.is_empty() && self.stderr.is_empty()
190 }
191}
192
193#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
194pub struct UpstreamTrackingStatus {
195 pub ahead: u32,
196 pub behind: u32,
197}
198
199#[derive(Clone, Debug, Hash, PartialEq, Eq)]
200pub struct CommitSummary {
201 pub sha: SharedString,
202 pub subject: SharedString,
203 /// This is a unix timestamp
204 pub commit_timestamp: i64,
205 pub author_name: SharedString,
206 pub has_parent: bool,
207}
208
209#[derive(Clone, Debug, Default, Hash, PartialEq, Eq)]
210pub struct CommitDetails {
211 pub sha: SharedString,
212 pub message: SharedString,
213 pub commit_timestamp: i64,
214 pub author_email: SharedString,
215 pub author_name: SharedString,
216}
217
218#[derive(Clone, Debug, Hash, PartialEq, Eq)]
219pub struct FileHistoryEntry {
220 pub sha: SharedString,
221 pub subject: SharedString,
222 pub message: SharedString,
223 pub commit_timestamp: i64,
224 pub author_name: SharedString,
225 pub author_email: SharedString,
226}
227
228#[derive(Debug, Clone)]
229pub struct FileHistory {
230 pub entries: Vec<FileHistoryEntry>,
231 pub path: RepoPath,
232}
233
234#[derive(Debug)]
235pub struct CommitDiff {
236 pub files: Vec<CommitFile>,
237}
238
239#[derive(Debug)]
240pub struct CommitFile {
241 pub path: RepoPath,
242 pub old_text: Option<String>,
243 pub new_text: Option<String>,
244}
245
246impl CommitDetails {
247 pub fn short_sha(&self) -> SharedString {
248 self.sha[..SHORT_SHA_LENGTH].to_string().into()
249 }
250}
251
252#[derive(Debug, Clone, Hash, PartialEq, Eq)]
253pub struct Remote {
254 pub name: SharedString,
255}
256
257pub enum ResetMode {
258 /// Reset the branch pointer, leave index and worktree unchanged (this will make it look like things that were
259 /// committed are now staged).
260 Soft,
261 /// Reset the branch pointer and index, leave worktree unchanged (this makes it look as though things that were
262 /// committed are now unstaged).
263 Mixed,
264}
265
266#[derive(Debug, Clone, Hash, PartialEq, Eq)]
267pub enum FetchOptions {
268 All,
269 Remote(Remote),
270}
271
272impl FetchOptions {
273 pub fn to_proto(&self) -> Option<String> {
274 match self {
275 FetchOptions::All => None,
276 FetchOptions::Remote(remote) => Some(remote.clone().name.into()),
277 }
278 }
279
280 pub fn from_proto(remote_name: Option<String>) -> Self {
281 match remote_name {
282 Some(name) => FetchOptions::Remote(Remote { name: name.into() }),
283 None => FetchOptions::All,
284 }
285 }
286
287 pub fn name(&self) -> SharedString {
288 match self {
289 Self::All => "Fetch all remotes".into(),
290 Self::Remote(remote) => remote.name.clone(),
291 }
292 }
293}
294
295impl std::fmt::Display for FetchOptions {
296 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
297 match self {
298 FetchOptions::All => write!(f, "--all"),
299 FetchOptions::Remote(remote) => write!(f, "{}", remote.name),
300 }
301 }
302}
303
304/// Modifies .git/info/exclude temporarily
305pub struct GitExcludeOverride {
306 git_exclude_path: PathBuf,
307 original_excludes: Option<String>,
308 added_excludes: Option<String>,
309}
310
311impl GitExcludeOverride {
312 const START_BLOCK_MARKER: &str = "\n\n# ====== Auto-added by Zed: =======\n";
313 const END_BLOCK_MARKER: &str = "\n# ====== End of auto-added by Zed =======\n";
314
315 pub async fn new(git_exclude_path: PathBuf) -> Result<Self> {
316 let original_excludes =
317 smol::fs::read_to_string(&git_exclude_path)
318 .await
319 .ok()
320 .map(|content| {
321 // Auto-generated lines are normally cleaned up in
322 // `restore_original()` or `drop()`, but may stuck in rare cases.
323 // Make sure to remove them.
324 Self::remove_auto_generated_block(&content)
325 });
326
327 Ok(GitExcludeOverride {
328 git_exclude_path,
329 original_excludes,
330 added_excludes: None,
331 })
332 }
333
334 pub async fn add_excludes(&mut self, excludes: &str) -> Result<()> {
335 self.added_excludes = Some(if let Some(ref already_added) = self.added_excludes {
336 format!("{already_added}\n{excludes}")
337 } else {
338 excludes.to_string()
339 });
340
341 let mut content = self.original_excludes.clone().unwrap_or_default();
342
343 content.push_str(Self::START_BLOCK_MARKER);
344 content.push_str(self.added_excludes.as_ref().unwrap());
345 content.push_str(Self::END_BLOCK_MARKER);
346
347 smol::fs::write(&self.git_exclude_path, content).await?;
348 Ok(())
349 }
350
351 pub async fn restore_original(&mut self) -> Result<()> {
352 if let Some(ref original) = self.original_excludes {
353 smol::fs::write(&self.git_exclude_path, original).await?;
354 } else if self.git_exclude_path.exists() {
355 smol::fs::remove_file(&self.git_exclude_path).await?;
356 }
357
358 self.added_excludes = None;
359
360 Ok(())
361 }
362
363 fn remove_auto_generated_block(content: &str) -> String {
364 let start_marker = Self::START_BLOCK_MARKER;
365 let end_marker = Self::END_BLOCK_MARKER;
366 let mut content = content.to_string();
367
368 let start_index = content.find(start_marker);
369 let end_index = content.rfind(end_marker);
370
371 if let (Some(start), Some(end)) = (start_index, end_index) {
372 if end > start {
373 content.replace_range(start..end + end_marker.len(), "");
374 }
375 }
376
377 // Older versions of Zed didn't have end-of-block markers,
378 // so it's impossible to determine auto-generated lines.
379 // Conservatively remove the standard list of excludes
380 let standard_excludes = format!(
381 "{}{}",
382 Self::START_BLOCK_MARKER,
383 include_str!("./checkpoint.gitignore")
384 );
385 content = content.replace(&standard_excludes, "");
386
387 content
388 }
389}
390
391impl Drop for GitExcludeOverride {
392 fn drop(&mut self) {
393 if self.added_excludes.is_some() {
394 let git_exclude_path = self.git_exclude_path.clone();
395 let original_excludes = self.original_excludes.clone();
396 smol::spawn(async move {
397 if let Some(original) = original_excludes {
398 smol::fs::write(&git_exclude_path, original).await
399 } else {
400 smol::fs::remove_file(&git_exclude_path).await
401 }
402 })
403 .detach();
404 }
405 }
406}
407
408pub trait GitRepository: Send + Sync {
409 fn reload_index(&self);
410
411 /// Returns the contents of an entry in the repository's index, or None if there is no entry for the given path.
412 ///
413 /// Also returns `None` for symlinks.
414 fn load_index_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>>;
415
416 /// 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.
417 ///
418 /// Also returns `None` for symlinks.
419 fn load_committed_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>>;
420 fn load_blob_content(&self, oid: Oid) -> BoxFuture<'_, Result<String>>;
421
422 fn set_index_text(
423 &self,
424 path: RepoPath,
425 content: Option<String>,
426 env: Arc<HashMap<String, String>>,
427 is_executable: bool,
428 ) -> BoxFuture<'_, anyhow::Result<()>>;
429
430 /// Returns the URL of the remote with the given name.
431 fn remote_url(&self, name: &str) -> BoxFuture<'_, Option<String>>;
432
433 /// Resolve a list of refs to SHAs.
434 fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<'_, Result<Vec<Option<String>>>>;
435
436 fn head_sha(&self) -> BoxFuture<'_, Option<String>> {
437 async move {
438 self.revparse_batch(vec!["HEAD".into()])
439 .await
440 .unwrap_or_default()
441 .into_iter()
442 .next()
443 .flatten()
444 }
445 .boxed()
446 }
447
448 fn merge_message(&self) -> BoxFuture<'_, Option<String>>;
449
450 fn status(&self, path_prefixes: &[RepoPath]) -> Task<Result<GitStatus>>;
451 fn diff_tree(&self, request: DiffTreeType) -> BoxFuture<'_, Result<TreeDiff>>;
452
453 fn stash_entries(&self) -> BoxFuture<'_, Result<GitStash>>;
454
455 fn branches(&self) -> BoxFuture<'_, Result<Vec<Branch>>>;
456
457 fn change_branch(&self, name: String) -> BoxFuture<'_, Result<()>>;
458 fn create_branch(&self, name: String, base_branch: Option<String>)
459 -> BoxFuture<'_, Result<()>>;
460 fn rename_branch(&self, branch: String, new_name: String) -> BoxFuture<'_, Result<()>>;
461
462 fn delete_branch(&self, name: String) -> BoxFuture<'_, Result<()>>;
463
464 fn worktrees(&self) -> BoxFuture<'_, Result<Vec<Worktree>>>;
465
466 fn create_worktree(
467 &self,
468 name: String,
469 directory: PathBuf,
470 from_commit: Option<String>,
471 ) -> BoxFuture<'_, Result<()>>;
472
473 fn reset(
474 &self,
475 commit: String,
476 mode: ResetMode,
477 env: Arc<HashMap<String, String>>,
478 ) -> BoxFuture<'_, Result<()>>;
479
480 fn checkout_files(
481 &self,
482 commit: String,
483 paths: Vec<RepoPath>,
484 env: Arc<HashMap<String, String>>,
485 ) -> BoxFuture<'_, Result<()>>;
486
487 fn show(&self, commit: String) -> BoxFuture<'_, Result<CommitDetails>>;
488
489 fn load_commit(&self, commit: String, cx: AsyncApp) -> BoxFuture<'_, Result<CommitDiff>>;
490 fn blame(&self, path: RepoPath, content: Rope) -> BoxFuture<'_, Result<crate::blame::Blame>>;
491 fn file_history(&self, path: RepoPath) -> BoxFuture<'_, Result<FileHistory>>;
492 fn file_history_paginated(
493 &self,
494 path: RepoPath,
495 skip: usize,
496 limit: Option<usize>,
497 ) -> BoxFuture<'_, Result<FileHistory>>;
498
499 /// Returns the absolute path to the repository. For worktrees, this will be the path to the
500 /// worktree's gitdir within the main repository (typically `.git/worktrees/<name>`).
501 fn path(&self) -> PathBuf;
502
503 fn main_repository_path(&self) -> PathBuf;
504
505 /// Updates the index to match the worktree at the given paths.
506 ///
507 /// If any of the paths have been deleted from the worktree, they will be removed from the index if found there.
508 fn stage_paths(
509 &self,
510 paths: Vec<RepoPath>,
511 env: Arc<HashMap<String, String>>,
512 ) -> BoxFuture<'_, Result<()>>;
513 /// Updates the index to match HEAD at the given paths.
514 ///
515 /// If any of the paths were previously staged but do not exist in HEAD, they will be removed from the index.
516 fn unstage_paths(
517 &self,
518 paths: Vec<RepoPath>,
519 env: Arc<HashMap<String, String>>,
520 ) -> BoxFuture<'_, Result<()>>;
521
522 fn run_hook(
523 &self,
524 hook: RunHook,
525 env: Arc<HashMap<String, String>>,
526 ) -> BoxFuture<'_, Result<()>>;
527
528 fn commit(
529 &self,
530 message: SharedString,
531 name_and_email: Option<(SharedString, SharedString)>,
532 options: CommitOptions,
533 askpass: AskPassDelegate,
534 env: Arc<HashMap<String, String>>,
535 ) -> BoxFuture<'_, Result<()>>;
536
537 fn stash_paths(
538 &self,
539 paths: Vec<RepoPath>,
540 env: Arc<HashMap<String, String>>,
541 ) -> BoxFuture<'_, Result<()>>;
542
543 fn stash_pop(
544 &self,
545 index: Option<usize>,
546 env: Arc<HashMap<String, String>>,
547 ) -> BoxFuture<'_, Result<()>>;
548
549 fn stash_apply(
550 &self,
551 index: Option<usize>,
552 env: Arc<HashMap<String, String>>,
553 ) -> BoxFuture<'_, Result<()>>;
554
555 fn stash_drop(
556 &self,
557 index: Option<usize>,
558 env: Arc<HashMap<String, String>>,
559 ) -> BoxFuture<'_, Result<()>>;
560
561 fn push(
562 &self,
563 branch_name: String,
564 upstream_name: String,
565 options: Option<PushOptions>,
566 askpass: AskPassDelegate,
567 env: Arc<HashMap<String, String>>,
568 // This method takes an AsyncApp to ensure it's invoked on the main thread,
569 // otherwise git-credentials-manager won't work.
570 cx: AsyncApp,
571 ) -> BoxFuture<'_, Result<RemoteCommandOutput>>;
572
573 fn pull(
574 &self,
575 branch_name: Option<String>,
576 upstream_name: String,
577 rebase: bool,
578 askpass: AskPassDelegate,
579 env: Arc<HashMap<String, String>>,
580 // This method takes an AsyncApp to ensure it's invoked on the main thread,
581 // otherwise git-credentials-manager won't work.
582 cx: AsyncApp,
583 ) -> BoxFuture<'_, Result<RemoteCommandOutput>>;
584
585 fn fetch(
586 &self,
587 fetch_options: FetchOptions,
588 askpass: AskPassDelegate,
589 env: Arc<HashMap<String, String>>,
590 // This method takes an AsyncApp to ensure it's invoked on the main thread,
591 // otherwise git-credentials-manager won't work.
592 cx: AsyncApp,
593 ) -> BoxFuture<'_, Result<RemoteCommandOutput>>;
594
595 fn get_push_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>>;
596
597 fn get_branch_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>>;
598
599 fn get_all_remotes(&self) -> BoxFuture<'_, Result<Vec<Remote>>>;
600
601 fn remove_remote(&self, name: String) -> BoxFuture<'_, Result<()>>;
602
603 fn create_remote(&self, name: String, url: String) -> BoxFuture<'_, Result<()>>;
604
605 /// returns a list of remote branches that contain HEAD
606 fn check_for_pushed_commit(&self) -> BoxFuture<'_, Result<Vec<SharedString>>>;
607
608 /// Run git diff
609 fn diff(&self, diff: DiffType) -> BoxFuture<'_, Result<String>>;
610
611 /// Creates a checkpoint for the repository.
612 fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>>;
613
614 /// Resets to a previously-created checkpoint.
615 fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>>;
616
617 /// Compares two checkpoints, returning true if they are equal
618 fn compare_checkpoints(
619 &self,
620 left: GitRepositoryCheckpoint,
621 right: GitRepositoryCheckpoint,
622 ) -> BoxFuture<'_, Result<bool>>;
623
624 /// Computes a diff between two checkpoints.
625 fn diff_checkpoints(
626 &self,
627 base_checkpoint: GitRepositoryCheckpoint,
628 target_checkpoint: GitRepositoryCheckpoint,
629 ) -> BoxFuture<'_, Result<String>>;
630
631 fn default_branch(&self) -> BoxFuture<'_, Result<Option<SharedString>>>;
632}
633
634pub enum DiffType {
635 HeadToIndex,
636 HeadToWorktree,
637}
638
639#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]
640pub enum PushOptions {
641 SetUpstream,
642 Force,
643}
644
645impl std::fmt::Debug for dyn GitRepository {
646 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
647 f.debug_struct("dyn GitRepository<...>").finish()
648 }
649}
650
651pub struct RealGitRepository {
652 pub repository: Arc<Mutex<git2::Repository>>,
653 pub system_git_binary_path: Option<PathBuf>,
654 pub any_git_binary_path: PathBuf,
655 executor: BackgroundExecutor,
656}
657
658impl RealGitRepository {
659 pub fn new(
660 dotgit_path: &Path,
661 bundled_git_binary_path: Option<PathBuf>,
662 system_git_binary_path: Option<PathBuf>,
663 executor: BackgroundExecutor,
664 ) -> Option<Self> {
665 let any_git_binary_path = system_git_binary_path.clone().or(bundled_git_binary_path)?;
666 let workdir_root = dotgit_path.parent()?;
667 let repository = git2::Repository::open(workdir_root).log_err()?;
668 Some(Self {
669 repository: Arc::new(Mutex::new(repository)),
670 system_git_binary_path,
671 any_git_binary_path,
672 executor,
673 })
674 }
675
676 fn working_directory(&self) -> Result<PathBuf> {
677 self.repository
678 .lock()
679 .workdir()
680 .context("failed to read git work directory")
681 .map(Path::to_path_buf)
682 }
683}
684
685#[derive(Clone, Debug)]
686pub struct GitRepositoryCheckpoint {
687 pub commit_sha: Oid,
688}
689
690#[derive(Debug)]
691pub struct GitCommitter {
692 pub name: Option<String>,
693 pub email: Option<String>,
694}
695
696pub async fn get_git_committer(cx: &AsyncApp) -> GitCommitter {
697 if cfg!(any(feature = "test-support", test)) {
698 return GitCommitter {
699 name: None,
700 email: None,
701 };
702 }
703
704 let git_binary_path =
705 if cfg!(target_os = "macos") && option_env!("ZED_BUNDLE").as_deref() == Some("true") {
706 cx.update(|cx| {
707 cx.path_for_auxiliary_executable("git")
708 .context("could not find git binary path")
709 .log_err()
710 })
711 .ok()
712 .flatten()
713 } else {
714 None
715 };
716
717 let git = GitBinary::new(
718 git_binary_path.unwrap_or(PathBuf::from("git")),
719 paths::home_dir().clone(),
720 cx.background_executor().clone(),
721 );
722
723 cx.background_spawn(async move {
724 let name = git.run(["config", "--global", "user.name"]).await.log_err();
725 let email = git
726 .run(["config", "--global", "user.email"])
727 .await
728 .log_err();
729 GitCommitter { name, email }
730 })
731 .await
732}
733
734impl GitRepository for RealGitRepository {
735 fn reload_index(&self) {
736 if let Ok(mut index) = self.repository.lock().index() {
737 _ = index.read(false);
738 }
739 }
740
741 fn path(&self) -> PathBuf {
742 let repo = self.repository.lock();
743 repo.path().into()
744 }
745
746 fn main_repository_path(&self) -> PathBuf {
747 let repo = self.repository.lock();
748 repo.commondir().into()
749 }
750
751 fn show(&self, commit: String) -> BoxFuture<'_, Result<CommitDetails>> {
752 let git_binary_path = self.any_git_binary_path.clone();
753 let working_directory = self.working_directory();
754 self.executor
755 .spawn(async move {
756 let working_directory = working_directory?;
757 let output = new_smol_command(git_binary_path)
758 .current_dir(&working_directory)
759 .args([
760 "--no-optional-locks",
761 "show",
762 "--no-patch",
763 "--format=%H%x00%B%x00%at%x00%ae%x00%an%x00",
764 &commit,
765 ])
766 .output()
767 .await?;
768 let output = std::str::from_utf8(&output.stdout)?;
769 let fields = output.split('\0').collect::<Vec<_>>();
770 if fields.len() != 6 {
771 bail!("unexpected git-show output for {commit:?}: {output:?}")
772 }
773 let sha = fields[0].to_string().into();
774 let message = fields[1].to_string().into();
775 let commit_timestamp = fields[2].parse()?;
776 let author_email = fields[3].to_string().into();
777 let author_name = fields[4].to_string().into();
778 Ok(CommitDetails {
779 sha,
780 message,
781 commit_timestamp,
782 author_email,
783 author_name,
784 })
785 })
786 .boxed()
787 }
788
789 fn load_commit(&self, commit: String, cx: AsyncApp) -> BoxFuture<'_, Result<CommitDiff>> {
790 let Some(working_directory) = self.repository.lock().workdir().map(ToOwned::to_owned)
791 else {
792 return future::ready(Err(anyhow!("no working directory"))).boxed();
793 };
794 let git_binary_path = self.any_git_binary_path.clone();
795 cx.background_spawn(async move {
796 let show_output = util::command::new_smol_command(&git_binary_path)
797 .current_dir(&working_directory)
798 .args([
799 "--no-optional-locks",
800 "show",
801 "--format=",
802 "-z",
803 "--no-renames",
804 "--name-status",
805 "--first-parent",
806 ])
807 .arg(&commit)
808 .stdin(Stdio::null())
809 .stdout(Stdio::piped())
810 .stderr(Stdio::piped())
811 .output()
812 .await
813 .context("starting git show process")?;
814
815 let show_stdout = String::from_utf8_lossy(&show_output.stdout);
816 let changes = parse_git_diff_name_status(&show_stdout);
817 let parent_sha = format!("{}^", commit);
818
819 let mut cat_file_process = util::command::new_smol_command(&git_binary_path)
820 .current_dir(&working_directory)
821 .args(["--no-optional-locks", "cat-file", "--batch=%(objectsize)"])
822 .stdin(Stdio::piped())
823 .stdout(Stdio::piped())
824 .stderr(Stdio::piped())
825 .spawn()
826 .context("starting git cat-file process")?;
827
828 let mut files = Vec::<CommitFile>::new();
829 let mut stdin = BufWriter::with_capacity(512, cat_file_process.stdin.take().unwrap());
830 let mut stdout = BufReader::new(cat_file_process.stdout.take().unwrap());
831 let mut info_line = String::new();
832 let mut newline = [b'\0'];
833 for (path, status_code) in changes {
834 // git-show outputs `/`-delimited paths even on Windows.
835 let Some(rel_path) = RelPath::unix(path).log_err() else {
836 continue;
837 };
838
839 match status_code {
840 StatusCode::Modified => {
841 stdin.write_all(commit.as_bytes()).await?;
842 stdin.write_all(b":").await?;
843 stdin.write_all(path.as_bytes()).await?;
844 stdin.write_all(b"\n").await?;
845 stdin.write_all(parent_sha.as_bytes()).await?;
846 stdin.write_all(b":").await?;
847 stdin.write_all(path.as_bytes()).await?;
848 stdin.write_all(b"\n").await?;
849 }
850 StatusCode::Added => {
851 stdin.write_all(commit.as_bytes()).await?;
852 stdin.write_all(b":").await?;
853 stdin.write_all(path.as_bytes()).await?;
854 stdin.write_all(b"\n").await?;
855 }
856 StatusCode::Deleted => {
857 stdin.write_all(parent_sha.as_bytes()).await?;
858 stdin.write_all(b":").await?;
859 stdin.write_all(path.as_bytes()).await?;
860 stdin.write_all(b"\n").await?;
861 }
862 _ => continue,
863 }
864 stdin.flush().await?;
865
866 info_line.clear();
867 stdout.read_line(&mut info_line).await?;
868
869 let len = info_line.trim_end().parse().with_context(|| {
870 format!("invalid object size output from cat-file {info_line}")
871 })?;
872 let mut text = vec![0; len];
873 stdout.read_exact(&mut text).await?;
874 stdout.read_exact(&mut newline).await?;
875 let text = String::from_utf8_lossy(&text).to_string();
876
877 let mut old_text = None;
878 let mut new_text = None;
879 match status_code {
880 StatusCode::Modified => {
881 info_line.clear();
882 stdout.read_line(&mut info_line).await?;
883 let len = info_line.trim_end().parse().with_context(|| {
884 format!("invalid object size output from cat-file {}", info_line)
885 })?;
886 let mut parent_text = vec![0; len];
887 stdout.read_exact(&mut parent_text).await?;
888 stdout.read_exact(&mut newline).await?;
889 old_text = Some(String::from_utf8_lossy(&parent_text).to_string());
890 new_text = Some(text);
891 }
892 StatusCode::Added => new_text = Some(text),
893 StatusCode::Deleted => old_text = Some(text),
894 _ => continue,
895 }
896
897 files.push(CommitFile {
898 path: RepoPath(Arc::from(rel_path)),
899 old_text,
900 new_text,
901 })
902 }
903
904 Ok(CommitDiff { files })
905 })
906 .boxed()
907 }
908
909 fn reset(
910 &self,
911 commit: String,
912 mode: ResetMode,
913 env: Arc<HashMap<String, String>>,
914 ) -> BoxFuture<'_, Result<()>> {
915 async move {
916 let working_directory = self.working_directory();
917
918 let mode_flag = match mode {
919 ResetMode::Mixed => "--mixed",
920 ResetMode::Soft => "--soft",
921 };
922
923 let output = new_smol_command(&self.any_git_binary_path)
924 .envs(env.iter())
925 .current_dir(&working_directory?)
926 .args(["reset", mode_flag, &commit])
927 .output()
928 .await?;
929 anyhow::ensure!(
930 output.status.success(),
931 "Failed to reset:\n{}",
932 String::from_utf8_lossy(&output.stderr),
933 );
934 Ok(())
935 }
936 .boxed()
937 }
938
939 fn checkout_files(
940 &self,
941 commit: String,
942 paths: Vec<RepoPath>,
943 env: Arc<HashMap<String, String>>,
944 ) -> BoxFuture<'_, Result<()>> {
945 let working_directory = self.working_directory();
946 let git_binary_path = self.any_git_binary_path.clone();
947 async move {
948 if paths.is_empty() {
949 return Ok(());
950 }
951
952 let output = new_smol_command(&git_binary_path)
953 .current_dir(&working_directory?)
954 .envs(env.iter())
955 .args(["checkout", &commit, "--"])
956 .args(paths.iter().map(|path| path.as_unix_str()))
957 .output()
958 .await?;
959 anyhow::ensure!(
960 output.status.success(),
961 "Failed to checkout files:\n{}",
962 String::from_utf8_lossy(&output.stderr),
963 );
964 Ok(())
965 }
966 .boxed()
967 }
968
969 fn load_index_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>> {
970 // https://git-scm.com/book/en/v2/Git-Internals-Git-Objects
971 const GIT_MODE_SYMLINK: u32 = 0o120000;
972
973 let repo = self.repository.clone();
974 self.executor
975 .spawn(async move {
976 fn logic(repo: &git2::Repository, path: &RepoPath) -> Result<Option<String>> {
977 // This check is required because index.get_path() unwraps internally :(
978 let mut index = repo.index()?;
979 index.read(false)?;
980
981 const STAGE_NORMAL: i32 = 0;
982 let path = path.as_std_path();
983 // `RepoPath` contains a `RelPath` which normalizes `.` into an empty path
984 // `get_path` unwraps on empty paths though, so undo that normalization here
985 let path = if path.components().next().is_none() {
986 ".".as_ref()
987 } else {
988 path
989 };
990 let oid = match index.get_path(path, STAGE_NORMAL) {
991 Some(entry) if entry.mode != GIT_MODE_SYMLINK => entry.id,
992 _ => return Ok(None),
993 };
994
995 let content = repo.find_blob(oid)?.content().to_owned();
996 Ok(String::from_utf8(content).ok())
997 }
998
999 match logic(&repo.lock(), &path) {
1000 Ok(value) => return value,
1001 Err(err) => log::error!("Error loading index text: {:?}", err),
1002 }
1003 None
1004 })
1005 .boxed()
1006 }
1007
1008 fn load_committed_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>> {
1009 let repo = self.repository.clone();
1010 self.executor
1011 .spawn(async move {
1012 let repo = repo.lock();
1013 let head = repo.head().ok()?.peel_to_tree().log_err()?;
1014 let entry = head.get_path(path.as_std_path()).ok()?;
1015 if entry.filemode() == i32::from(git2::FileMode::Link) {
1016 return None;
1017 }
1018 let content = repo.find_blob(entry.id()).log_err()?.content().to_owned();
1019 String::from_utf8(content).ok()
1020 })
1021 .boxed()
1022 }
1023
1024 fn load_blob_content(&self, oid: Oid) -> BoxFuture<'_, Result<String>> {
1025 let repo = self.repository.clone();
1026 self.executor
1027 .spawn(async move {
1028 let repo = repo.lock();
1029 let content = repo.find_blob(oid.0)?.content().to_owned();
1030 Ok(String::from_utf8(content)?)
1031 })
1032 .boxed()
1033 }
1034
1035 fn set_index_text(
1036 &self,
1037 path: RepoPath,
1038 content: Option<String>,
1039 env: Arc<HashMap<String, String>>,
1040 is_executable: bool,
1041 ) -> BoxFuture<'_, anyhow::Result<()>> {
1042 let working_directory = self.working_directory();
1043 let git_binary_path = self.any_git_binary_path.clone();
1044 self.executor
1045 .spawn(async move {
1046 let working_directory = working_directory?;
1047 let mode = if is_executable { "100755" } else { "100644" };
1048
1049 if let Some(content) = content {
1050 let mut child = new_smol_command(&git_binary_path)
1051 .current_dir(&working_directory)
1052 .envs(env.iter())
1053 .args(["hash-object", "-w", "--stdin"])
1054 .stdin(Stdio::piped())
1055 .stdout(Stdio::piped())
1056 .spawn()?;
1057 let mut stdin = child.stdin.take().unwrap();
1058 stdin.write_all(content.as_bytes()).await?;
1059 stdin.flush().await?;
1060 drop(stdin);
1061 let output = child.output().await?.stdout;
1062 let sha = str::from_utf8(&output)?.trim();
1063
1064 log::debug!("indexing SHA: {sha}, path {path:?}");
1065
1066 let output = new_smol_command(&git_binary_path)
1067 .current_dir(&working_directory)
1068 .envs(env.iter())
1069 .args(["update-index", "--add", "--cacheinfo", mode, sha])
1070 .arg(path.as_unix_str())
1071 .output()
1072 .await?;
1073
1074 anyhow::ensure!(
1075 output.status.success(),
1076 "Failed to stage:\n{}",
1077 String::from_utf8_lossy(&output.stderr)
1078 );
1079 } else {
1080 log::debug!("removing path {path:?} from the index");
1081 let output = new_smol_command(&git_binary_path)
1082 .current_dir(&working_directory)
1083 .envs(env.iter())
1084 .args(["update-index", "--force-remove"])
1085 .arg(path.as_unix_str())
1086 .output()
1087 .await?;
1088 anyhow::ensure!(
1089 output.status.success(),
1090 "Failed to unstage:\n{}",
1091 String::from_utf8_lossy(&output.stderr)
1092 );
1093 }
1094
1095 Ok(())
1096 })
1097 .boxed()
1098 }
1099
1100 fn remote_url(&self, name: &str) -> BoxFuture<'_, Option<String>> {
1101 let repo = self.repository.clone();
1102 let name = name.to_owned();
1103 self.executor
1104 .spawn(async move {
1105 let repo = repo.lock();
1106 let remote = repo.find_remote(&name).ok()?;
1107 remote.url().map(|url| url.to_string())
1108 })
1109 .boxed()
1110 }
1111
1112 fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<'_, Result<Vec<Option<String>>>> {
1113 let working_directory = self.working_directory();
1114 let git_binary_path = self.any_git_binary_path.clone();
1115 self.executor
1116 .spawn(async move {
1117 let working_directory = working_directory?;
1118 let mut process = new_smol_command(&git_binary_path)
1119 .current_dir(&working_directory)
1120 .args([
1121 "--no-optional-locks",
1122 "cat-file",
1123 "--batch-check=%(objectname)",
1124 ])
1125 .stdin(Stdio::piped())
1126 .stdout(Stdio::piped())
1127 .stderr(Stdio::piped())
1128 .spawn()?;
1129
1130 let stdin = process
1131 .stdin
1132 .take()
1133 .context("no stdin for git cat-file subprocess")?;
1134 let mut stdin = BufWriter::new(stdin);
1135 for rev in &revs {
1136 stdin.write_all(rev.as_bytes()).await?;
1137 stdin.write_all(b"\n").await?;
1138 }
1139 stdin.flush().await?;
1140 drop(stdin);
1141
1142 let output = process.output().await?;
1143 let output = std::str::from_utf8(&output.stdout)?;
1144 let shas = output
1145 .lines()
1146 .map(|line| {
1147 if line.ends_with("missing") {
1148 None
1149 } else {
1150 Some(line.to_string())
1151 }
1152 })
1153 .collect::<Vec<_>>();
1154
1155 if shas.len() != revs.len() {
1156 // In an octopus merge, git cat-file still only outputs the first sha from MERGE_HEAD.
1157 bail!("unexpected number of shas")
1158 }
1159
1160 Ok(shas)
1161 })
1162 .boxed()
1163 }
1164
1165 fn merge_message(&self) -> BoxFuture<'_, Option<String>> {
1166 let path = self.path().join("MERGE_MSG");
1167 self.executor
1168 .spawn(async move { std::fs::read_to_string(&path).ok() })
1169 .boxed()
1170 }
1171
1172 fn status(&self, path_prefixes: &[RepoPath]) -> Task<Result<GitStatus>> {
1173 let git_binary_path = self.any_git_binary_path.clone();
1174 let working_directory = match self.working_directory() {
1175 Ok(working_directory) => working_directory,
1176 Err(e) => return Task::ready(Err(e)),
1177 };
1178 let args = git_status_args(path_prefixes);
1179 log::debug!("Checking for git status in {path_prefixes:?}");
1180 self.executor.spawn(async move {
1181 let output = new_smol_command(&git_binary_path)
1182 .current_dir(working_directory)
1183 .args(args)
1184 .output()
1185 .await?;
1186 if output.status.success() {
1187 let stdout = String::from_utf8_lossy(&output.stdout);
1188 stdout.parse()
1189 } else {
1190 let stderr = String::from_utf8_lossy(&output.stderr);
1191 anyhow::bail!("git status failed: {stderr}");
1192 }
1193 })
1194 }
1195
1196 fn diff_tree(&self, request: DiffTreeType) -> BoxFuture<'_, Result<TreeDiff>> {
1197 let git_binary_path = self.any_git_binary_path.clone();
1198 let working_directory = match self.working_directory() {
1199 Ok(working_directory) => working_directory,
1200 Err(e) => return Task::ready(Err(e)).boxed(),
1201 };
1202
1203 let mut args = vec![
1204 OsString::from("--no-optional-locks"),
1205 OsString::from("diff-tree"),
1206 OsString::from("-r"),
1207 OsString::from("-z"),
1208 OsString::from("--no-renames"),
1209 ];
1210 match request {
1211 DiffTreeType::MergeBase { base, head } => {
1212 args.push("--merge-base".into());
1213 args.push(OsString::from(base.as_str()));
1214 args.push(OsString::from(head.as_str()));
1215 }
1216 DiffTreeType::Since { base, head } => {
1217 args.push(OsString::from(base.as_str()));
1218 args.push(OsString::from(head.as_str()));
1219 }
1220 }
1221
1222 self.executor
1223 .spawn(async move {
1224 let output = new_smol_command(&git_binary_path)
1225 .current_dir(working_directory)
1226 .args(args)
1227 .output()
1228 .await?;
1229 if output.status.success() {
1230 let stdout = String::from_utf8_lossy(&output.stdout);
1231 stdout.parse()
1232 } else {
1233 let stderr = String::from_utf8_lossy(&output.stderr);
1234 anyhow::bail!("git status failed: {stderr}");
1235 }
1236 })
1237 .boxed()
1238 }
1239
1240 fn stash_entries(&self) -> BoxFuture<'_, Result<GitStash>> {
1241 let git_binary_path = self.any_git_binary_path.clone();
1242 let working_directory = self.working_directory();
1243 self.executor
1244 .spawn(async move {
1245 let output = new_smol_command(&git_binary_path)
1246 .current_dir(working_directory?)
1247 .args(&["stash", "list", "--pretty=format:%gd%x00%H%x00%ct%x00%s"])
1248 .output()
1249 .await?;
1250 if output.status.success() {
1251 let stdout = String::from_utf8_lossy(&output.stdout);
1252 stdout.parse()
1253 } else {
1254 let stderr = String::from_utf8_lossy(&output.stderr);
1255 anyhow::bail!("git status failed: {stderr}");
1256 }
1257 })
1258 .boxed()
1259 }
1260
1261 fn branches(&self) -> BoxFuture<'_, Result<Vec<Branch>>> {
1262 let working_directory = self.working_directory();
1263 let git_binary_path = self.any_git_binary_path.clone();
1264 self.executor
1265 .spawn(async move {
1266 let fields = [
1267 "%(HEAD)",
1268 "%(objectname)",
1269 "%(parent)",
1270 "%(refname)",
1271 "%(upstream)",
1272 "%(upstream:track)",
1273 "%(committerdate:unix)",
1274 "%(authorname)",
1275 "%(contents:subject)",
1276 ]
1277 .join("%00");
1278 let args = vec![
1279 "for-each-ref",
1280 "refs/heads/**/*",
1281 "refs/remotes/**/*",
1282 "--format",
1283 &fields,
1284 ];
1285 let working_directory = working_directory?;
1286 let output = new_smol_command(&git_binary_path)
1287 .current_dir(&working_directory)
1288 .args(args)
1289 .output()
1290 .await?;
1291
1292 anyhow::ensure!(
1293 output.status.success(),
1294 "Failed to git git branches:\n{}",
1295 String::from_utf8_lossy(&output.stderr)
1296 );
1297
1298 let input = String::from_utf8_lossy(&output.stdout);
1299
1300 let mut branches = parse_branch_input(&input)?;
1301 if branches.is_empty() {
1302 let args = vec!["symbolic-ref", "--quiet", "HEAD"];
1303
1304 let output = new_smol_command(&git_binary_path)
1305 .current_dir(&working_directory)
1306 .args(args)
1307 .output()
1308 .await?;
1309
1310 // git symbolic-ref returns a non-0 exit code if HEAD points
1311 // to something other than a branch
1312 if output.status.success() {
1313 let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
1314
1315 branches.push(Branch {
1316 ref_name: name.into(),
1317 is_head: true,
1318 upstream: None,
1319 most_recent_commit: None,
1320 });
1321 }
1322 }
1323
1324 Ok(branches)
1325 })
1326 .boxed()
1327 }
1328
1329 fn worktrees(&self) -> BoxFuture<'_, Result<Vec<Worktree>>> {
1330 let git_binary_path = self.any_git_binary_path.clone();
1331 let working_directory = self.working_directory();
1332 self.executor
1333 .spawn(async move {
1334 let output = new_smol_command(&git_binary_path)
1335 .current_dir(working_directory?)
1336 .args(&["--no-optional-locks", "worktree", "list", "--porcelain"])
1337 .output()
1338 .await?;
1339 if output.status.success() {
1340 let stdout = String::from_utf8_lossy(&output.stdout);
1341 Ok(parse_worktrees_from_str(&stdout))
1342 } else {
1343 let stderr = String::from_utf8_lossy(&output.stderr);
1344 anyhow::bail!("git worktree list failed: {stderr}");
1345 }
1346 })
1347 .boxed()
1348 }
1349
1350 fn create_worktree(
1351 &self,
1352 name: String,
1353 directory: PathBuf,
1354 from_commit: Option<String>,
1355 ) -> BoxFuture<'_, Result<()>> {
1356 let git_binary_path = self.any_git_binary_path.clone();
1357 let working_directory = self.working_directory();
1358 let final_path = directory.join(&name);
1359 let mut args = vec![
1360 OsString::from("--no-optional-locks"),
1361 OsString::from("worktree"),
1362 OsString::from("add"),
1363 OsString::from(final_path.as_os_str()),
1364 ];
1365 if let Some(from_commit) = from_commit {
1366 args.extend([
1367 OsString::from("-b"),
1368 OsString::from(name.as_str()),
1369 OsString::from(from_commit),
1370 ]);
1371 }
1372 self.executor
1373 .spawn(async move {
1374 let output = new_smol_command(&git_binary_path)
1375 .current_dir(working_directory?)
1376 .args(args)
1377 .output()
1378 .await?;
1379 if output.status.success() {
1380 Ok(())
1381 } else {
1382 let stderr = String::from_utf8_lossy(&output.stderr);
1383 anyhow::bail!("git worktree list failed: {stderr}");
1384 }
1385 })
1386 .boxed()
1387 }
1388
1389 fn change_branch(&self, name: String) -> BoxFuture<'_, Result<()>> {
1390 let repo = self.repository.clone();
1391 let working_directory = self.working_directory();
1392 let git_binary_path = self.any_git_binary_path.clone();
1393 let executor = self.executor.clone();
1394 let branch = self.executor.spawn(async move {
1395 let repo = repo.lock();
1396 let branch = if let Ok(branch) = repo.find_branch(&name, BranchType::Local) {
1397 branch
1398 } else if let Ok(revision) = repo.find_branch(&name, BranchType::Remote) {
1399 let (_, branch_name) = name.split_once("/").context("Unexpected branch format")?;
1400
1401 let revision = revision.get();
1402 let branch_commit = revision.peel_to_commit()?;
1403 let mut branch = match repo.branch(&branch_name, &branch_commit, false) {
1404 Ok(branch) => branch,
1405 Err(err) if err.code() == ErrorCode::Exists => {
1406 repo.find_branch(&branch_name, BranchType::Local)?
1407 }
1408 Err(err) => {
1409 return Err(err.into());
1410 }
1411 };
1412
1413 branch.set_upstream(Some(&name))?;
1414 branch
1415 } else {
1416 anyhow::bail!("Branch '{}' not found", name);
1417 };
1418
1419 Ok(branch
1420 .name()?
1421 .context("cannot checkout anonymous branch")?
1422 .to_string())
1423 });
1424
1425 self.executor
1426 .spawn(async move {
1427 let branch = branch.await?;
1428 GitBinary::new(git_binary_path, working_directory?, executor)
1429 .run(&["checkout", &branch])
1430 .await?;
1431 anyhow::Ok(())
1432 })
1433 .boxed()
1434 }
1435
1436 fn create_branch(
1437 &self,
1438 name: String,
1439 base_branch: Option<String>,
1440 ) -> BoxFuture<'_, Result<()>> {
1441 let git_binary_path = self.any_git_binary_path.clone();
1442 let working_directory = self.working_directory();
1443 let executor = self.executor.clone();
1444
1445 self.executor
1446 .spawn(async move {
1447 let mut args = vec!["switch", "-c", &name];
1448 let base_branch_str;
1449 if let Some(ref base) = base_branch {
1450 base_branch_str = base.clone();
1451 args.push(&base_branch_str);
1452 }
1453
1454 GitBinary::new(git_binary_path, working_directory?, executor)
1455 .run(&args)
1456 .await?;
1457 anyhow::Ok(())
1458 })
1459 .boxed()
1460 }
1461
1462 fn rename_branch(&self, branch: String, new_name: String) -> BoxFuture<'_, Result<()>> {
1463 let git_binary_path = self.any_git_binary_path.clone();
1464 let working_directory = self.working_directory();
1465 let executor = self.executor.clone();
1466
1467 self.executor
1468 .spawn(async move {
1469 GitBinary::new(git_binary_path, working_directory?, executor)
1470 .run(&["branch", "-m", &branch, &new_name])
1471 .await?;
1472 anyhow::Ok(())
1473 })
1474 .boxed()
1475 }
1476
1477 fn delete_branch(&self, name: String) -> BoxFuture<'_, Result<()>> {
1478 let git_binary_path = self.any_git_binary_path.clone();
1479 let working_directory = self.working_directory();
1480 let executor = self.executor.clone();
1481
1482 self.executor
1483 .spawn(async move {
1484 GitBinary::new(git_binary_path, working_directory?, executor)
1485 .run(&["branch", "-d", &name])
1486 .await?;
1487 anyhow::Ok(())
1488 })
1489 .boxed()
1490 }
1491
1492 fn blame(&self, path: RepoPath, content: Rope) -> BoxFuture<'_, Result<crate::blame::Blame>> {
1493 let working_directory = self.working_directory();
1494 let git_binary_path = self.any_git_binary_path.clone();
1495 let executor = self.executor.clone();
1496
1497 async move {
1498 let remote_url = if let Some(remote_url) = self.remote_url("upstream").await {
1499 Some(remote_url)
1500 } else if let Some(remote_url) = self.remote_url("origin").await {
1501 Some(remote_url)
1502 } else {
1503 None
1504 };
1505 executor
1506 .spawn(async move {
1507 crate::blame::Blame::for_path(
1508 &git_binary_path,
1509 &working_directory?,
1510 &path,
1511 &content,
1512 remote_url,
1513 )
1514 .await
1515 })
1516 .await
1517 }
1518 .boxed()
1519 }
1520
1521 fn file_history(&self, path: RepoPath) -> BoxFuture<'_, Result<FileHistory>> {
1522 self.file_history_paginated(path, 0, None)
1523 }
1524
1525 fn file_history_paginated(
1526 &self,
1527 path: RepoPath,
1528 skip: usize,
1529 limit: Option<usize>,
1530 ) -> BoxFuture<'_, Result<FileHistory>> {
1531 let working_directory = self.working_directory();
1532 let git_binary_path = self.any_git_binary_path.clone();
1533 self.executor
1534 .spawn(async move {
1535 let working_directory = working_directory?;
1536 // Use a unique delimiter with a hardcoded UUID to separate commits
1537 // This essentially eliminates any chance of encountering the delimiter in actual commit data
1538 let commit_delimiter =
1539 concat!("<<COMMIT_END-", "3f8a9c2e-7d4b-4e1a-9f6c-8b5d2a1e4c3f>>",);
1540
1541 let format_string = format!(
1542 "--pretty=format:%H%x00%s%x00%B%x00%at%x00%an%x00%ae{}",
1543 commit_delimiter
1544 );
1545
1546 let mut args = vec!["--no-optional-locks", "log", "--follow", &format_string];
1547
1548 let skip_str;
1549 let limit_str;
1550 if skip > 0 {
1551 skip_str = skip.to_string();
1552 args.push("--skip");
1553 args.push(&skip_str);
1554 }
1555 if let Some(n) = limit {
1556 limit_str = n.to_string();
1557 args.push("-n");
1558 args.push(&limit_str);
1559 }
1560
1561 args.push("--");
1562
1563 let output = new_smol_command(&git_binary_path)
1564 .current_dir(&working_directory)
1565 .args(&args)
1566 .arg(path.as_unix_str())
1567 .output()
1568 .await?;
1569
1570 if !output.status.success() {
1571 let stderr = String::from_utf8_lossy(&output.stderr);
1572 bail!("git log failed: {stderr}");
1573 }
1574
1575 let stdout = std::str::from_utf8(&output.stdout)?;
1576 let mut entries = Vec::new();
1577
1578 for commit_block in stdout.split(commit_delimiter) {
1579 let commit_block = commit_block.trim();
1580 if commit_block.is_empty() {
1581 continue;
1582 }
1583
1584 let fields: Vec<&str> = commit_block.split('\0').collect();
1585 if fields.len() >= 6 {
1586 let sha = fields[0].trim().to_string().into();
1587 let subject = fields[1].trim().to_string().into();
1588 let message = fields[2].trim().to_string().into();
1589 let commit_timestamp = fields[3].trim().parse().unwrap_or(0);
1590 let author_name = fields[4].trim().to_string().into();
1591 let author_email = fields[5].trim().to_string().into();
1592
1593 entries.push(FileHistoryEntry {
1594 sha,
1595 subject,
1596 message,
1597 commit_timestamp,
1598 author_name,
1599 author_email,
1600 });
1601 }
1602 }
1603
1604 Ok(FileHistory { entries, path })
1605 })
1606 .boxed()
1607 }
1608
1609 fn diff(&self, diff: DiffType) -> BoxFuture<'_, Result<String>> {
1610 let working_directory = self.working_directory();
1611 let git_binary_path = self.any_git_binary_path.clone();
1612 self.executor
1613 .spawn(async move {
1614 let args = match diff {
1615 DiffType::HeadToIndex => Some("--staged"),
1616 DiffType::HeadToWorktree => None,
1617 };
1618
1619 let output = new_smol_command(&git_binary_path)
1620 .current_dir(&working_directory?)
1621 .args(["diff"])
1622 .args(args)
1623 .output()
1624 .await?;
1625
1626 anyhow::ensure!(
1627 output.status.success(),
1628 "Failed to run git diff:\n{}",
1629 String::from_utf8_lossy(&output.stderr)
1630 );
1631 Ok(String::from_utf8_lossy(&output.stdout).to_string())
1632 })
1633 .boxed()
1634 }
1635
1636 fn stage_paths(
1637 &self,
1638 paths: Vec<RepoPath>,
1639 env: Arc<HashMap<String, String>>,
1640 ) -> BoxFuture<'_, Result<()>> {
1641 let working_directory = self.working_directory();
1642 let git_binary_path = self.any_git_binary_path.clone();
1643 self.executor
1644 .spawn(async move {
1645 if !paths.is_empty() {
1646 let output = new_smol_command(&git_binary_path)
1647 .current_dir(&working_directory?)
1648 .envs(env.iter())
1649 .args(["update-index", "--add", "--remove", "--"])
1650 .args(paths.iter().map(|p| p.as_unix_str()))
1651 .output()
1652 .await?;
1653 anyhow::ensure!(
1654 output.status.success(),
1655 "Failed to stage paths:\n{}",
1656 String::from_utf8_lossy(&output.stderr),
1657 );
1658 }
1659 Ok(())
1660 })
1661 .boxed()
1662 }
1663
1664 fn unstage_paths(
1665 &self,
1666 paths: Vec<RepoPath>,
1667 env: Arc<HashMap<String, String>>,
1668 ) -> BoxFuture<'_, Result<()>> {
1669 let working_directory = self.working_directory();
1670 let git_binary_path = self.any_git_binary_path.clone();
1671
1672 self.executor
1673 .spawn(async move {
1674 if !paths.is_empty() {
1675 let output = new_smol_command(&git_binary_path)
1676 .current_dir(&working_directory?)
1677 .envs(env.iter())
1678 .args(["reset", "--quiet", "--"])
1679 .args(paths.iter().map(|p| p.as_std_path()))
1680 .output()
1681 .await?;
1682
1683 anyhow::ensure!(
1684 output.status.success(),
1685 "Failed to unstage:\n{}",
1686 String::from_utf8_lossy(&output.stderr),
1687 );
1688 }
1689 Ok(())
1690 })
1691 .boxed()
1692 }
1693
1694 fn stash_paths(
1695 &self,
1696 paths: Vec<RepoPath>,
1697 env: Arc<HashMap<String, String>>,
1698 ) -> BoxFuture<'_, Result<()>> {
1699 let working_directory = self.working_directory();
1700 let git_binary_path = self.any_git_binary_path.clone();
1701 self.executor
1702 .spawn(async move {
1703 let mut cmd = new_smol_command(&git_binary_path);
1704 cmd.current_dir(&working_directory?)
1705 .envs(env.iter())
1706 .args(["stash", "push", "--quiet"])
1707 .arg("--include-untracked");
1708
1709 cmd.args(paths.iter().map(|p| p.as_unix_str()));
1710
1711 let output = cmd.output().await?;
1712
1713 anyhow::ensure!(
1714 output.status.success(),
1715 "Failed to stash:\n{}",
1716 String::from_utf8_lossy(&output.stderr)
1717 );
1718 Ok(())
1719 })
1720 .boxed()
1721 }
1722
1723 fn stash_pop(
1724 &self,
1725 index: Option<usize>,
1726 env: Arc<HashMap<String, String>>,
1727 ) -> BoxFuture<'_, Result<()>> {
1728 let working_directory = self.working_directory();
1729 let git_binary_path = self.any_git_binary_path.clone();
1730 self.executor
1731 .spawn(async move {
1732 let mut cmd = new_smol_command(git_binary_path);
1733 let mut args = vec!["stash".to_string(), "pop".to_string()];
1734 if let Some(index) = index {
1735 args.push(format!("stash@{{{}}}", index));
1736 }
1737 cmd.current_dir(&working_directory?)
1738 .envs(env.iter())
1739 .args(args);
1740
1741 let output = cmd.output().await?;
1742
1743 anyhow::ensure!(
1744 output.status.success(),
1745 "Failed to stash pop:\n{}",
1746 String::from_utf8_lossy(&output.stderr)
1747 );
1748 Ok(())
1749 })
1750 .boxed()
1751 }
1752
1753 fn stash_apply(
1754 &self,
1755 index: Option<usize>,
1756 env: Arc<HashMap<String, String>>,
1757 ) -> BoxFuture<'_, Result<()>> {
1758 let working_directory = self.working_directory();
1759 let git_binary_path = self.any_git_binary_path.clone();
1760 self.executor
1761 .spawn(async move {
1762 let mut cmd = new_smol_command(git_binary_path);
1763 let mut args = vec!["stash".to_string(), "apply".to_string()];
1764 if let Some(index) = index {
1765 args.push(format!("stash@{{{}}}", index));
1766 }
1767 cmd.current_dir(&working_directory?)
1768 .envs(env.iter())
1769 .args(args);
1770
1771 let output = cmd.output().await?;
1772
1773 anyhow::ensure!(
1774 output.status.success(),
1775 "Failed to apply stash:\n{}",
1776 String::from_utf8_lossy(&output.stderr)
1777 );
1778 Ok(())
1779 })
1780 .boxed()
1781 }
1782
1783 fn stash_drop(
1784 &self,
1785 index: Option<usize>,
1786 env: Arc<HashMap<String, String>>,
1787 ) -> BoxFuture<'_, Result<()>> {
1788 let working_directory = self.working_directory();
1789 let git_binary_path = self.any_git_binary_path.clone();
1790 self.executor
1791 .spawn(async move {
1792 let mut cmd = new_smol_command(git_binary_path);
1793 let mut args = vec!["stash".to_string(), "drop".to_string()];
1794 if let Some(index) = index {
1795 args.push(format!("stash@{{{}}}", index));
1796 }
1797 cmd.current_dir(&working_directory?)
1798 .envs(env.iter())
1799 .args(args);
1800
1801 let output = cmd.output().await?;
1802
1803 anyhow::ensure!(
1804 output.status.success(),
1805 "Failed to stash drop:\n{}",
1806 String::from_utf8_lossy(&output.stderr)
1807 );
1808 Ok(())
1809 })
1810 .boxed()
1811 }
1812
1813 fn commit(
1814 &self,
1815 message: SharedString,
1816 name_and_email: Option<(SharedString, SharedString)>,
1817 options: CommitOptions,
1818 ask_pass: AskPassDelegate,
1819 env: Arc<HashMap<String, String>>,
1820 ) -> BoxFuture<'_, Result<()>> {
1821 let working_directory = self.working_directory();
1822 let git_binary_path = self.any_git_binary_path.clone();
1823 let executor = self.executor.clone();
1824 // Note: Do not spawn this command on the background thread, it might pop open the credential helper
1825 // which we want to block on.
1826 async move {
1827 let mut cmd = new_smol_command(git_binary_path);
1828 cmd.current_dir(&working_directory?)
1829 .envs(env.iter())
1830 .args(["commit", "--quiet", "-m"])
1831 .arg(&message.to_string())
1832 .arg("--cleanup=strip")
1833 .arg("--no-verify")
1834 .stdout(smol::process::Stdio::piped())
1835 .stderr(smol::process::Stdio::piped());
1836
1837 if options.amend {
1838 cmd.arg("--amend");
1839 }
1840
1841 if options.signoff {
1842 cmd.arg("--signoff");
1843 }
1844
1845 if let Some((name, email)) = name_and_email {
1846 cmd.arg("--author").arg(&format!("{name} <{email}>"));
1847 }
1848
1849 run_git_command(env, ask_pass, cmd, &executor).await?;
1850
1851 Ok(())
1852 }
1853 .boxed()
1854 }
1855
1856 fn push(
1857 &self,
1858 branch_name: String,
1859 remote_name: String,
1860 options: Option<PushOptions>,
1861 ask_pass: AskPassDelegate,
1862 env: Arc<HashMap<String, String>>,
1863 cx: AsyncApp,
1864 ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
1865 let working_directory = self.working_directory();
1866 let executor = cx.background_executor().clone();
1867 let git_binary_path = self.system_git_binary_path.clone();
1868 // Note: Do not spawn this command on the background thread, it might pop open the credential helper
1869 // which we want to block on.
1870 async move {
1871 let git_binary_path = git_binary_path.context("git not found on $PATH, can't push")?;
1872 let working_directory = working_directory?;
1873 let mut command = new_smol_command(git_binary_path);
1874 command
1875 .envs(env.iter())
1876 .current_dir(&working_directory)
1877 .args(["push"])
1878 .args(options.map(|option| match option {
1879 PushOptions::SetUpstream => "--set-upstream",
1880 PushOptions::Force => "--force-with-lease",
1881 }))
1882 .arg(remote_name)
1883 .arg(format!("{}:{}", branch_name, branch_name))
1884 .stdin(smol::process::Stdio::null())
1885 .stdout(smol::process::Stdio::piped())
1886 .stderr(smol::process::Stdio::piped());
1887
1888 run_git_command(env, ask_pass, command, &executor).await
1889 }
1890 .boxed()
1891 }
1892
1893 fn pull(
1894 &self,
1895 branch_name: Option<String>,
1896 remote_name: String,
1897 rebase: bool,
1898 ask_pass: AskPassDelegate,
1899 env: Arc<HashMap<String, String>>,
1900 cx: AsyncApp,
1901 ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
1902 let working_directory = self.working_directory();
1903 let executor = cx.background_executor().clone();
1904 let git_binary_path = self.system_git_binary_path.clone();
1905 // Note: Do not spawn this command on the background thread, it might pop open the credential helper
1906 // which we want to block on.
1907 async move {
1908 let git_binary_path = git_binary_path.context("git not found on $PATH, can't pull")?;
1909 let mut command = new_smol_command(git_binary_path);
1910 command
1911 .envs(env.iter())
1912 .current_dir(&working_directory?)
1913 .arg("pull");
1914
1915 if rebase {
1916 command.arg("--rebase");
1917 }
1918
1919 command
1920 .arg(remote_name)
1921 .args(branch_name)
1922 .stdout(smol::process::Stdio::piped())
1923 .stderr(smol::process::Stdio::piped());
1924
1925 run_git_command(env, ask_pass, command, &executor).await
1926 }
1927 .boxed()
1928 }
1929
1930 fn fetch(
1931 &self,
1932 fetch_options: FetchOptions,
1933 ask_pass: AskPassDelegate,
1934 env: Arc<HashMap<String, String>>,
1935 cx: AsyncApp,
1936 ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
1937 let working_directory = self.working_directory();
1938 let remote_name = format!("{}", fetch_options);
1939 let git_binary_path = self.system_git_binary_path.clone();
1940 let executor = cx.background_executor().clone();
1941 // Note: Do not spawn this command on the background thread, it might pop open the credential helper
1942 // which we want to block on.
1943 async move {
1944 let git_binary_path = git_binary_path.context("git not found on $PATH, can't fetch")?;
1945 let mut command = new_smol_command(git_binary_path);
1946 command
1947 .envs(env.iter())
1948 .current_dir(&working_directory?)
1949 .args(["fetch", &remote_name])
1950 .stdout(smol::process::Stdio::piped())
1951 .stderr(smol::process::Stdio::piped());
1952
1953 run_git_command(env, ask_pass, command, &executor).await
1954 }
1955 .boxed()
1956 }
1957
1958 fn get_push_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
1959 let working_directory = self.working_directory();
1960 let git_binary_path = self.any_git_binary_path.clone();
1961 self.executor
1962 .spawn(async move {
1963 let working_directory = working_directory?;
1964 let output = new_smol_command(&git_binary_path)
1965 .current_dir(&working_directory)
1966 .args(["rev-parse", "--abbrev-ref"])
1967 .arg(format!("{branch}@{{push}}"))
1968 .output()
1969 .await?;
1970 if !output.status.success() {
1971 return Ok(None);
1972 }
1973 let remote_name = String::from_utf8_lossy(&output.stdout)
1974 .split('/')
1975 .next()
1976 .map(|name| Remote {
1977 name: name.trim().to_string().into(),
1978 });
1979
1980 Ok(remote_name)
1981 })
1982 .boxed()
1983 }
1984
1985 fn get_branch_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
1986 let working_directory = self.working_directory();
1987 let git_binary_path = self.any_git_binary_path.clone();
1988 self.executor
1989 .spawn(async move {
1990 let working_directory = working_directory?;
1991 let output = new_smol_command(&git_binary_path)
1992 .current_dir(&working_directory)
1993 .args(["config", "--get"])
1994 .arg(format!("branch.{branch}.remote"))
1995 .output()
1996 .await?;
1997 if !output.status.success() {
1998 return Ok(None);
1999 }
2000
2001 let remote_name = String::from_utf8_lossy(&output.stdout);
2002 return Ok(Some(Remote {
2003 name: remote_name.trim().to_string().into(),
2004 }));
2005 })
2006 .boxed()
2007 }
2008
2009 fn get_all_remotes(&self) -> BoxFuture<'_, Result<Vec<Remote>>> {
2010 let working_directory = self.working_directory();
2011 let git_binary_path = self.any_git_binary_path.clone();
2012 self.executor
2013 .spawn(async move {
2014 let working_directory = working_directory?;
2015 let output = new_smol_command(&git_binary_path)
2016 .current_dir(&working_directory)
2017 .args(["remote", "-v"])
2018 .output()
2019 .await?;
2020
2021 anyhow::ensure!(
2022 output.status.success(),
2023 "Failed to get all remotes:\n{}",
2024 String::from_utf8_lossy(&output.stderr)
2025 );
2026 let remote_names: HashSet<Remote> = String::from_utf8_lossy(&output.stdout)
2027 .lines()
2028 .filter(|line| !line.is_empty())
2029 .filter_map(|line| {
2030 let mut split_line = line.split_whitespace();
2031 let remote_name = split_line.next()?;
2032
2033 Some(Remote {
2034 name: remote_name.trim().to_string().into(),
2035 })
2036 })
2037 .collect();
2038
2039 Ok(remote_names.into_iter().collect())
2040 })
2041 .boxed()
2042 }
2043
2044 fn remove_remote(&self, name: String) -> BoxFuture<'_, Result<()>> {
2045 let repo = self.repository.clone();
2046 self.executor
2047 .spawn(async move {
2048 let repo = repo.lock();
2049 repo.remote_delete(&name)?;
2050
2051 Ok(())
2052 })
2053 .boxed()
2054 }
2055
2056 fn create_remote(&self, name: String, url: String) -> BoxFuture<'_, Result<()>> {
2057 let repo = self.repository.clone();
2058 self.executor
2059 .spawn(async move {
2060 let repo = repo.lock();
2061 repo.remote(&name, url.as_ref())?;
2062 Ok(())
2063 })
2064 .boxed()
2065 }
2066
2067 fn check_for_pushed_commit(&self) -> BoxFuture<'_, Result<Vec<SharedString>>> {
2068 let working_directory = self.working_directory();
2069 let git_binary_path = self.any_git_binary_path.clone();
2070 self.executor
2071 .spawn(async move {
2072 let working_directory = working_directory?;
2073 let git_cmd = async |args: &[&str]| -> Result<String> {
2074 let output = new_smol_command(&git_binary_path)
2075 .current_dir(&working_directory)
2076 .args(args)
2077 .output()
2078 .await?;
2079 anyhow::ensure!(
2080 output.status.success(),
2081 String::from_utf8_lossy(&output.stderr).to_string()
2082 );
2083 Ok(String::from_utf8(output.stdout)?)
2084 };
2085
2086 let head = git_cmd(&["rev-parse", "HEAD"])
2087 .await
2088 .context("Failed to get HEAD")?
2089 .trim()
2090 .to_owned();
2091
2092 let mut remote_branches = vec![];
2093 let mut add_if_matching = async |remote_head: &str| {
2094 if let Ok(merge_base) = git_cmd(&["merge-base", &head, remote_head]).await
2095 && merge_base.trim() == head
2096 && let Some(s) = remote_head.strip_prefix("refs/remotes/")
2097 {
2098 remote_branches.push(s.to_owned().into());
2099 }
2100 };
2101
2102 // check the main branch of each remote
2103 let remotes = git_cmd(&["remote"])
2104 .await
2105 .context("Failed to get remotes")?;
2106 for remote in remotes.lines() {
2107 if let Ok(remote_head) =
2108 git_cmd(&["symbolic-ref", &format!("refs/remotes/{remote}/HEAD")]).await
2109 {
2110 add_if_matching(remote_head.trim()).await;
2111 }
2112 }
2113
2114 // ... and the remote branch that the checked-out one is tracking
2115 if let Ok(remote_head) =
2116 git_cmd(&["rev-parse", "--symbolic-full-name", "@{u}"]).await
2117 {
2118 add_if_matching(remote_head.trim()).await;
2119 }
2120
2121 Ok(remote_branches)
2122 })
2123 .boxed()
2124 }
2125
2126 fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>> {
2127 let working_directory = self.working_directory();
2128 let git_binary_path = self.any_git_binary_path.clone();
2129 let executor = self.executor.clone();
2130 self.executor
2131 .spawn(async move {
2132 let working_directory = working_directory?;
2133 let mut git = GitBinary::new(git_binary_path, working_directory.clone(), executor)
2134 .envs(checkpoint_author_envs());
2135 git.with_temp_index(async |git| {
2136 let head_sha = git.run(&["rev-parse", "HEAD"]).await.ok();
2137 let mut excludes = exclude_files(git).await?;
2138
2139 git.run(&["add", "--all"]).await?;
2140 let tree = git.run(&["write-tree"]).await?;
2141 let checkpoint_sha = if let Some(head_sha) = head_sha.as_deref() {
2142 git.run(&["commit-tree", &tree, "-p", head_sha, "-m", "Checkpoint"])
2143 .await?
2144 } else {
2145 git.run(&["commit-tree", &tree, "-m", "Checkpoint"]).await?
2146 };
2147
2148 excludes.restore_original().await?;
2149
2150 Ok(GitRepositoryCheckpoint {
2151 commit_sha: checkpoint_sha.parse()?,
2152 })
2153 })
2154 .await
2155 })
2156 .boxed()
2157 }
2158
2159 fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>> {
2160 let working_directory = self.working_directory();
2161 let git_binary_path = self.any_git_binary_path.clone();
2162
2163 let executor = self.executor.clone();
2164 self.executor
2165 .spawn(async move {
2166 let working_directory = working_directory?;
2167
2168 let git = GitBinary::new(git_binary_path, working_directory, executor);
2169 git.run(&[
2170 "restore",
2171 "--source",
2172 &checkpoint.commit_sha.to_string(),
2173 "--worktree",
2174 ".",
2175 ])
2176 .await?;
2177
2178 // TODO: We don't track binary and large files anymore,
2179 // so the following call would delete them.
2180 // Implement an alternative way to track files added by agent.
2181 //
2182 // git.with_temp_index(async move |git| {
2183 // git.run(&["read-tree", &checkpoint.commit_sha.to_string()])
2184 // .await?;
2185 // git.run(&["clean", "-d", "--force"]).await
2186 // })
2187 // .await?;
2188
2189 Ok(())
2190 })
2191 .boxed()
2192 }
2193
2194 fn compare_checkpoints(
2195 &self,
2196 left: GitRepositoryCheckpoint,
2197 right: GitRepositoryCheckpoint,
2198 ) -> BoxFuture<'_, Result<bool>> {
2199 let working_directory = self.working_directory();
2200 let git_binary_path = self.any_git_binary_path.clone();
2201
2202 let executor = self.executor.clone();
2203 self.executor
2204 .spawn(async move {
2205 let working_directory = working_directory?;
2206 let git = GitBinary::new(git_binary_path, working_directory, executor);
2207 let result = git
2208 .run(&[
2209 "diff-tree",
2210 "--quiet",
2211 &left.commit_sha.to_string(),
2212 &right.commit_sha.to_string(),
2213 ])
2214 .await;
2215 match result {
2216 Ok(_) => Ok(true),
2217 Err(error) => {
2218 if let Some(GitBinaryCommandError { status, .. }) =
2219 error.downcast_ref::<GitBinaryCommandError>()
2220 && status.code() == Some(1)
2221 {
2222 return Ok(false);
2223 }
2224
2225 Err(error)
2226 }
2227 }
2228 })
2229 .boxed()
2230 }
2231
2232 fn diff_checkpoints(
2233 &self,
2234 base_checkpoint: GitRepositoryCheckpoint,
2235 target_checkpoint: GitRepositoryCheckpoint,
2236 ) -> BoxFuture<'_, Result<String>> {
2237 let working_directory = self.working_directory();
2238 let git_binary_path = self.any_git_binary_path.clone();
2239
2240 let executor = self.executor.clone();
2241 self.executor
2242 .spawn(async move {
2243 let working_directory = working_directory?;
2244 let git = GitBinary::new(git_binary_path, working_directory, executor);
2245 git.run(&[
2246 "diff",
2247 "--find-renames",
2248 "--patch",
2249 &base_checkpoint.commit_sha.to_string(),
2250 &target_checkpoint.commit_sha.to_string(),
2251 ])
2252 .await
2253 })
2254 .boxed()
2255 }
2256
2257 fn default_branch(&self) -> BoxFuture<'_, Result<Option<SharedString>>> {
2258 let working_directory = self.working_directory();
2259 let git_binary_path = self.any_git_binary_path.clone();
2260
2261 let executor = self.executor.clone();
2262 self.executor
2263 .spawn(async move {
2264 let working_directory = working_directory?;
2265 let git = GitBinary::new(git_binary_path, working_directory, executor);
2266
2267 if let Ok(output) = git
2268 .run(&["symbolic-ref", "refs/remotes/upstream/HEAD"])
2269 .await
2270 {
2271 let output = output
2272 .strip_prefix("refs/remotes/upstream/")
2273 .map(|s| SharedString::from(s.to_owned()));
2274 return Ok(output);
2275 }
2276
2277 if let Ok(output) = git.run(&["symbolic-ref", "refs/remotes/origin/HEAD"]).await {
2278 return Ok(output
2279 .strip_prefix("refs/remotes/origin/")
2280 .map(|s| SharedString::from(s.to_owned())));
2281 }
2282
2283 if let Ok(default_branch) = git.run(&["config", "init.defaultBranch"]).await {
2284 if git.run(&["rev-parse", &default_branch]).await.is_ok() {
2285 return Ok(Some(default_branch.into()));
2286 }
2287 }
2288
2289 if git.run(&["rev-parse", "master"]).await.is_ok() {
2290 return Ok(Some("master".into()));
2291 }
2292
2293 Ok(None)
2294 })
2295 .boxed()
2296 }
2297
2298 fn run_hook(
2299 &self,
2300 hook: RunHook,
2301 env: Arc<HashMap<String, String>>,
2302 ) -> BoxFuture<'_, Result<()>> {
2303 let working_directory = self.working_directory();
2304 let git_binary_path = self.any_git_binary_path.clone();
2305 let executor = self.executor.clone();
2306 self.executor
2307 .spawn(async move {
2308 let working_directory = working_directory?;
2309 let git = GitBinary::new(git_binary_path, working_directory, executor)
2310 .envs(HashMap::clone(&env));
2311 git.run(&["hook", "run", "--ignore-missing", hook.as_str()])
2312 .await?;
2313 Ok(())
2314 })
2315 .boxed()
2316 }
2317}
2318
2319fn git_status_args(path_prefixes: &[RepoPath]) -> Vec<OsString> {
2320 let mut args = vec![
2321 OsString::from("--no-optional-locks"),
2322 OsString::from("status"),
2323 OsString::from("--porcelain=v1"),
2324 OsString::from("--untracked-files=all"),
2325 OsString::from("--no-renames"),
2326 OsString::from("-z"),
2327 ];
2328 args.extend(
2329 path_prefixes
2330 .iter()
2331 .map(|path_prefix| path_prefix.as_std_path().into()),
2332 );
2333 args.extend(path_prefixes.iter().map(|path_prefix| {
2334 if path_prefix.is_empty() {
2335 Path::new(".").into()
2336 } else {
2337 path_prefix.as_std_path().into()
2338 }
2339 }));
2340 args
2341}
2342
2343/// Temporarily git-ignore commonly ignored files and files over 2MB
2344async fn exclude_files(git: &GitBinary) -> Result<GitExcludeOverride> {
2345 const MAX_SIZE: u64 = 2 * 1024 * 1024; // 2 MB
2346 let mut excludes = git.with_exclude_overrides().await?;
2347 excludes
2348 .add_excludes(include_str!("./checkpoint.gitignore"))
2349 .await?;
2350
2351 let working_directory = git.working_directory.clone();
2352 let untracked_files = git.list_untracked_files().await?;
2353 let excluded_paths = untracked_files.into_iter().map(|path| {
2354 let working_directory = working_directory.clone();
2355 smol::spawn(async move {
2356 let full_path = working_directory.join(path.clone());
2357 match smol::fs::metadata(&full_path).await {
2358 Ok(metadata) if metadata.is_file() && metadata.len() >= MAX_SIZE => {
2359 Some(PathBuf::from("/").join(path.clone()))
2360 }
2361 _ => None,
2362 }
2363 })
2364 });
2365
2366 let excluded_paths = futures::future::join_all(excluded_paths).await;
2367 let excluded_paths = excluded_paths.into_iter().flatten().collect::<Vec<_>>();
2368
2369 if !excluded_paths.is_empty() {
2370 let exclude_patterns = excluded_paths
2371 .into_iter()
2372 .map(|path| path.to_string_lossy().into_owned())
2373 .collect::<Vec<_>>()
2374 .join("\n");
2375 excludes.add_excludes(&exclude_patterns).await?;
2376 }
2377
2378 Ok(excludes)
2379}
2380
2381struct GitBinary {
2382 git_binary_path: PathBuf,
2383 working_directory: PathBuf,
2384 executor: BackgroundExecutor,
2385 index_file_path: Option<PathBuf>,
2386 envs: HashMap<String, String>,
2387}
2388
2389impl GitBinary {
2390 fn new(
2391 git_binary_path: PathBuf,
2392 working_directory: PathBuf,
2393 executor: BackgroundExecutor,
2394 ) -> Self {
2395 Self {
2396 git_binary_path,
2397 working_directory,
2398 executor,
2399 index_file_path: None,
2400 envs: HashMap::default(),
2401 }
2402 }
2403
2404 async fn list_untracked_files(&self) -> Result<Vec<PathBuf>> {
2405 let status_output = self
2406 .run(&["status", "--porcelain=v1", "--untracked-files=all", "-z"])
2407 .await?;
2408
2409 let paths = status_output
2410 .split('\0')
2411 .filter(|entry| entry.len() >= 3 && entry.starts_with("?? "))
2412 .map(|entry| PathBuf::from(&entry[3..]))
2413 .collect::<Vec<_>>();
2414 Ok(paths)
2415 }
2416
2417 fn envs(mut self, envs: HashMap<String, String>) -> Self {
2418 self.envs = envs;
2419 self
2420 }
2421
2422 pub async fn with_temp_index<R>(
2423 &mut self,
2424 f: impl AsyncFnOnce(&Self) -> Result<R>,
2425 ) -> Result<R> {
2426 let index_file_path = self.path_for_index_id(Uuid::new_v4());
2427
2428 let delete_temp_index = util::defer({
2429 let index_file_path = index_file_path.clone();
2430 let executor = self.executor.clone();
2431 move || {
2432 executor
2433 .spawn(async move {
2434 smol::fs::remove_file(index_file_path).await.log_err();
2435 })
2436 .detach();
2437 }
2438 });
2439
2440 // Copy the default index file so that Git doesn't have to rebuild the
2441 // whole index from scratch. This might fail if this is an empty repository.
2442 smol::fs::copy(
2443 self.working_directory.join(".git").join("index"),
2444 &index_file_path,
2445 )
2446 .await
2447 .ok();
2448
2449 self.index_file_path = Some(index_file_path.clone());
2450 let result = f(self).await;
2451 self.index_file_path = None;
2452 let result = result?;
2453
2454 smol::fs::remove_file(index_file_path).await.ok();
2455 delete_temp_index.abort();
2456
2457 Ok(result)
2458 }
2459
2460 pub async fn with_exclude_overrides(&self) -> Result<GitExcludeOverride> {
2461 let path = self
2462 .working_directory
2463 .join(".git")
2464 .join("info")
2465 .join("exclude");
2466
2467 GitExcludeOverride::new(path).await
2468 }
2469
2470 fn path_for_index_id(&self, id: Uuid) -> PathBuf {
2471 self.working_directory
2472 .join(".git")
2473 .join(format!("index-{}.tmp", id))
2474 }
2475
2476 pub async fn run<S>(&self, args: impl IntoIterator<Item = S>) -> Result<String>
2477 where
2478 S: AsRef<OsStr>,
2479 {
2480 let mut stdout = self.run_raw(args).await?;
2481 if stdout.chars().last() == Some('\n') {
2482 stdout.pop();
2483 }
2484 Ok(stdout)
2485 }
2486
2487 /// Returns the result of the command without trimming the trailing newline.
2488 pub async fn run_raw<S>(&self, args: impl IntoIterator<Item = S>) -> Result<String>
2489 where
2490 S: AsRef<OsStr>,
2491 {
2492 let mut command = self.build_command(args);
2493 let output = command.output().await?;
2494 anyhow::ensure!(
2495 output.status.success(),
2496 GitBinaryCommandError {
2497 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
2498 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
2499 status: output.status,
2500 }
2501 );
2502 Ok(String::from_utf8(output.stdout)?)
2503 }
2504
2505 fn build_command<S>(&self, args: impl IntoIterator<Item = S>) -> smol::process::Command
2506 where
2507 S: AsRef<OsStr>,
2508 {
2509 let mut command = new_smol_command(&self.git_binary_path);
2510 command.current_dir(&self.working_directory);
2511 command.args(args);
2512 if let Some(index_file_path) = self.index_file_path.as_ref() {
2513 command.env("GIT_INDEX_FILE", index_file_path);
2514 }
2515 command.envs(&self.envs);
2516 command
2517 }
2518}
2519
2520#[derive(Error, Debug)]
2521#[error("Git command failed:\n{stdout}{stderr}\n")]
2522struct GitBinaryCommandError {
2523 stdout: String,
2524 stderr: String,
2525 status: ExitStatus,
2526}
2527
2528async fn run_git_command(
2529 env: Arc<HashMap<String, String>>,
2530 ask_pass: AskPassDelegate,
2531 mut command: smol::process::Command,
2532 executor: &BackgroundExecutor,
2533) -> Result<RemoteCommandOutput> {
2534 if env.contains_key("GIT_ASKPASS") {
2535 let git_process = command.spawn()?;
2536 let output = git_process.output().await?;
2537 anyhow::ensure!(
2538 output.status.success(),
2539 "{}",
2540 String::from_utf8_lossy(&output.stderr)
2541 );
2542 Ok(RemoteCommandOutput {
2543 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
2544 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
2545 })
2546 } else {
2547 let ask_pass = AskPassSession::new(executor, ask_pass).await?;
2548 command
2549 .env("GIT_ASKPASS", ask_pass.script_path())
2550 .env("SSH_ASKPASS", ask_pass.script_path())
2551 .env("SSH_ASKPASS_REQUIRE", "force");
2552 let git_process = command.spawn()?;
2553
2554 run_askpass_command(ask_pass, git_process).await
2555 }
2556}
2557
2558async fn run_askpass_command(
2559 mut ask_pass: AskPassSession,
2560 git_process: smol::process::Child,
2561) -> anyhow::Result<RemoteCommandOutput> {
2562 select_biased! {
2563 result = ask_pass.run().fuse() => {
2564 match result {
2565 AskPassResult::CancelledByUser => {
2566 Err(anyhow!(REMOTE_CANCELLED_BY_USER))?
2567 }
2568 AskPassResult::Timedout => {
2569 Err(anyhow!("Connecting to host timed out"))?
2570 }
2571 }
2572 }
2573 output = git_process.output().fuse() => {
2574 let output = output?;
2575 anyhow::ensure!(
2576 output.status.success(),
2577 "{}",
2578 String::from_utf8_lossy(&output.stderr)
2579 );
2580 Ok(RemoteCommandOutput {
2581 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
2582 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
2583 })
2584 }
2585 }
2586}
2587
2588#[derive(Clone, Ord, Hash, PartialOrd, Eq, PartialEq)]
2589pub struct RepoPath(Arc<RelPath>);
2590
2591impl std::fmt::Debug for RepoPath {
2592 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2593 self.0.fmt(f)
2594 }
2595}
2596
2597impl RepoPath {
2598 pub fn new<S: AsRef<str> + ?Sized>(s: &S) -> Result<Self> {
2599 let rel_path = RelPath::unix(s.as_ref())?;
2600 Ok(Self::from_rel_path(rel_path))
2601 }
2602
2603 pub fn from_std_path(path: &Path, path_style: PathStyle) -> Result<Self> {
2604 let rel_path = RelPath::new(path, path_style)?;
2605 Ok(Self::from_rel_path(&rel_path))
2606 }
2607
2608 pub fn from_proto(proto: &str) -> Result<Self> {
2609 let rel_path = RelPath::from_proto(proto)?;
2610 Ok(Self(rel_path))
2611 }
2612
2613 pub fn from_rel_path(path: &RelPath) -> RepoPath {
2614 Self(Arc::from(path))
2615 }
2616
2617 pub fn as_std_path(&self) -> &Path {
2618 // git2 does not like empty paths and our RelPath infra turns `.` into ``
2619 // so undo that here
2620 if self.is_empty() {
2621 Path::new(".")
2622 } else {
2623 self.0.as_std_path()
2624 }
2625 }
2626}
2627
2628#[cfg(any(test, feature = "test-support"))]
2629pub fn repo_path<S: AsRef<str> + ?Sized>(s: &S) -> RepoPath {
2630 RepoPath(RelPath::unix(s.as_ref()).unwrap().into())
2631}
2632
2633impl AsRef<Arc<RelPath>> for RepoPath {
2634 fn as_ref(&self) -> &Arc<RelPath> {
2635 &self.0
2636 }
2637}
2638
2639impl std::ops::Deref for RepoPath {
2640 type Target = RelPath;
2641
2642 fn deref(&self) -> &Self::Target {
2643 &self.0
2644 }
2645}
2646
2647#[derive(Debug)]
2648pub struct RepoPathDescendants<'a>(pub &'a RepoPath);
2649
2650impl MapSeekTarget<RepoPath> for RepoPathDescendants<'_> {
2651 fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
2652 if key.starts_with(self.0) {
2653 Ordering::Greater
2654 } else {
2655 self.0.cmp(key)
2656 }
2657 }
2658}
2659
2660fn parse_branch_input(input: &str) -> Result<Vec<Branch>> {
2661 let mut branches = Vec::new();
2662 for line in input.split('\n') {
2663 if line.is_empty() {
2664 continue;
2665 }
2666 let mut fields = line.split('\x00');
2667 let Some(head) = fields.next() else {
2668 continue;
2669 };
2670 let Some(head_sha) = fields.next().map(|f| f.to_string().into()) else {
2671 continue;
2672 };
2673 let Some(parent_sha) = fields.next().map(|f| f.to_string()) else {
2674 continue;
2675 };
2676 let Some(ref_name) = fields.next().map(|f| f.to_string().into()) else {
2677 continue;
2678 };
2679 let Some(upstream_name) = fields.next().map(|f| f.to_string()) else {
2680 continue;
2681 };
2682 let Some(upstream_tracking) = fields.next().and_then(|f| parse_upstream_track(f).ok())
2683 else {
2684 continue;
2685 };
2686 let Some(commiterdate) = fields.next().and_then(|f| f.parse::<i64>().ok()) else {
2687 continue;
2688 };
2689 let Some(author_name) = fields.next().map(|f| f.to_string().into()) else {
2690 continue;
2691 };
2692 let Some(subject) = fields.next().map(|f| f.to_string().into()) else {
2693 continue;
2694 };
2695
2696 branches.push(Branch {
2697 is_head: head == "*",
2698 ref_name,
2699 most_recent_commit: Some(CommitSummary {
2700 sha: head_sha,
2701 subject,
2702 commit_timestamp: commiterdate,
2703 author_name: author_name,
2704 has_parent: !parent_sha.is_empty(),
2705 }),
2706 upstream: if upstream_name.is_empty() {
2707 None
2708 } else {
2709 Some(Upstream {
2710 ref_name: upstream_name.into(),
2711 tracking: upstream_tracking,
2712 })
2713 },
2714 })
2715 }
2716
2717 Ok(branches)
2718}
2719
2720fn parse_upstream_track(upstream_track: &str) -> Result<UpstreamTracking> {
2721 if upstream_track.is_empty() {
2722 return Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
2723 ahead: 0,
2724 behind: 0,
2725 }));
2726 }
2727
2728 let upstream_track = upstream_track.strip_prefix("[").context("missing [")?;
2729 let upstream_track = upstream_track.strip_suffix("]").context("missing [")?;
2730 let mut ahead: u32 = 0;
2731 let mut behind: u32 = 0;
2732 for component in upstream_track.split(", ") {
2733 if component == "gone" {
2734 return Ok(UpstreamTracking::Gone);
2735 }
2736 if let Some(ahead_num) = component.strip_prefix("ahead ") {
2737 ahead = ahead_num.parse::<u32>()?;
2738 }
2739 if let Some(behind_num) = component.strip_prefix("behind ") {
2740 behind = behind_num.parse::<u32>()?;
2741 }
2742 }
2743 Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
2744 ahead,
2745 behind,
2746 }))
2747}
2748
2749fn checkpoint_author_envs() -> HashMap<String, String> {
2750 HashMap::from_iter([
2751 ("GIT_AUTHOR_NAME".to_string(), "Zed".to_string()),
2752 ("GIT_AUTHOR_EMAIL".to_string(), "hi@zed.dev".to_string()),
2753 ("GIT_COMMITTER_NAME".to_string(), "Zed".to_string()),
2754 ("GIT_COMMITTER_EMAIL".to_string(), "hi@zed.dev".to_string()),
2755 ])
2756}
2757
2758#[cfg(test)]
2759mod tests {
2760 use super::*;
2761 use gpui::TestAppContext;
2762
2763 fn disable_git_global_config() {
2764 unsafe {
2765 std::env::set_var("GIT_CONFIG_GLOBAL", "");
2766 std::env::set_var("GIT_CONFIG_SYSTEM", "");
2767 }
2768 }
2769
2770 #[gpui::test]
2771 async fn test_checkpoint_basic(cx: &mut TestAppContext) {
2772 disable_git_global_config();
2773
2774 cx.executor().allow_parking();
2775
2776 let repo_dir = tempfile::tempdir().unwrap();
2777
2778 git2::Repository::init(repo_dir.path()).unwrap();
2779 let file_path = repo_dir.path().join("file");
2780 smol::fs::write(&file_path, "initial").await.unwrap();
2781
2782 let repo = RealGitRepository::new(
2783 &repo_dir.path().join(".git"),
2784 None,
2785 Some("git".into()),
2786 cx.executor(),
2787 )
2788 .unwrap();
2789
2790 repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
2791 .await
2792 .unwrap();
2793 repo.commit(
2794 "Initial commit".into(),
2795 None,
2796 CommitOptions::default(),
2797 AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
2798 Arc::new(checkpoint_author_envs()),
2799 )
2800 .await
2801 .unwrap();
2802
2803 smol::fs::write(&file_path, "modified before checkpoint")
2804 .await
2805 .unwrap();
2806 smol::fs::write(repo_dir.path().join("new_file_before_checkpoint"), "1")
2807 .await
2808 .unwrap();
2809 let checkpoint = repo.checkpoint().await.unwrap();
2810
2811 // Ensure the user can't see any branches after creating a checkpoint.
2812 assert_eq!(repo.branches().await.unwrap().len(), 1);
2813
2814 smol::fs::write(&file_path, "modified after checkpoint")
2815 .await
2816 .unwrap();
2817 repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
2818 .await
2819 .unwrap();
2820 repo.commit(
2821 "Commit after checkpoint".into(),
2822 None,
2823 CommitOptions::default(),
2824 AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
2825 Arc::new(checkpoint_author_envs()),
2826 )
2827 .await
2828 .unwrap();
2829
2830 smol::fs::remove_file(repo_dir.path().join("new_file_before_checkpoint"))
2831 .await
2832 .unwrap();
2833 smol::fs::write(repo_dir.path().join("new_file_after_checkpoint"), "2")
2834 .await
2835 .unwrap();
2836
2837 // Ensure checkpoint stays alive even after a Git GC.
2838 repo.gc().await.unwrap();
2839 repo.restore_checkpoint(checkpoint.clone()).await.unwrap();
2840
2841 assert_eq!(
2842 smol::fs::read_to_string(&file_path).await.unwrap(),
2843 "modified before checkpoint"
2844 );
2845 assert_eq!(
2846 smol::fs::read_to_string(repo_dir.path().join("new_file_before_checkpoint"))
2847 .await
2848 .unwrap(),
2849 "1"
2850 );
2851 // See TODO above
2852 // assert_eq!(
2853 // smol::fs::read_to_string(repo_dir.path().join("new_file_after_checkpoint"))
2854 // .await
2855 // .ok(),
2856 // None
2857 // );
2858 }
2859
2860 #[gpui::test]
2861 async fn test_checkpoint_empty_repo(cx: &mut TestAppContext) {
2862 disable_git_global_config();
2863
2864 cx.executor().allow_parking();
2865
2866 let repo_dir = tempfile::tempdir().unwrap();
2867 git2::Repository::init(repo_dir.path()).unwrap();
2868 let repo = RealGitRepository::new(
2869 &repo_dir.path().join(".git"),
2870 None,
2871 Some("git".into()),
2872 cx.executor(),
2873 )
2874 .unwrap();
2875
2876 smol::fs::write(repo_dir.path().join("foo"), "foo")
2877 .await
2878 .unwrap();
2879 let checkpoint_sha = repo.checkpoint().await.unwrap();
2880
2881 // Ensure the user can't see any branches after creating a checkpoint.
2882 assert_eq!(repo.branches().await.unwrap().len(), 1);
2883
2884 smol::fs::write(repo_dir.path().join("foo"), "bar")
2885 .await
2886 .unwrap();
2887 smol::fs::write(repo_dir.path().join("baz"), "qux")
2888 .await
2889 .unwrap();
2890 repo.restore_checkpoint(checkpoint_sha).await.unwrap();
2891 assert_eq!(
2892 smol::fs::read_to_string(repo_dir.path().join("foo"))
2893 .await
2894 .unwrap(),
2895 "foo"
2896 );
2897 // See TODOs above
2898 // assert_eq!(
2899 // smol::fs::read_to_string(repo_dir.path().join("baz"))
2900 // .await
2901 // .ok(),
2902 // None
2903 // );
2904 }
2905
2906 #[gpui::test]
2907 async fn test_compare_checkpoints(cx: &mut TestAppContext) {
2908 disable_git_global_config();
2909
2910 cx.executor().allow_parking();
2911
2912 let repo_dir = tempfile::tempdir().unwrap();
2913 git2::Repository::init(repo_dir.path()).unwrap();
2914 let repo = RealGitRepository::new(
2915 &repo_dir.path().join(".git"),
2916 None,
2917 Some("git".into()),
2918 cx.executor(),
2919 )
2920 .unwrap();
2921
2922 smol::fs::write(repo_dir.path().join("file1"), "content1")
2923 .await
2924 .unwrap();
2925 let checkpoint1 = repo.checkpoint().await.unwrap();
2926
2927 smol::fs::write(repo_dir.path().join("file2"), "content2")
2928 .await
2929 .unwrap();
2930 let checkpoint2 = repo.checkpoint().await.unwrap();
2931
2932 assert!(
2933 !repo
2934 .compare_checkpoints(checkpoint1, checkpoint2.clone())
2935 .await
2936 .unwrap()
2937 );
2938
2939 let checkpoint3 = repo.checkpoint().await.unwrap();
2940 assert!(
2941 repo.compare_checkpoints(checkpoint2, checkpoint3)
2942 .await
2943 .unwrap()
2944 );
2945 }
2946
2947 #[gpui::test]
2948 async fn test_checkpoint_exclude_binary_files(cx: &mut TestAppContext) {
2949 disable_git_global_config();
2950
2951 cx.executor().allow_parking();
2952
2953 let repo_dir = tempfile::tempdir().unwrap();
2954 let text_path = repo_dir.path().join("main.rs");
2955 let bin_path = repo_dir.path().join("binary.o");
2956
2957 git2::Repository::init(repo_dir.path()).unwrap();
2958
2959 smol::fs::write(&text_path, "fn main() {}").await.unwrap();
2960
2961 smol::fs::write(&bin_path, "some binary file here")
2962 .await
2963 .unwrap();
2964
2965 let repo = RealGitRepository::new(
2966 &repo_dir.path().join(".git"),
2967 None,
2968 Some("git".into()),
2969 cx.executor(),
2970 )
2971 .unwrap();
2972
2973 // initial commit
2974 repo.stage_paths(vec![repo_path("main.rs")], Arc::new(HashMap::default()))
2975 .await
2976 .unwrap();
2977 repo.commit(
2978 "Initial commit".into(),
2979 None,
2980 CommitOptions::default(),
2981 AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
2982 Arc::new(checkpoint_author_envs()),
2983 )
2984 .await
2985 .unwrap();
2986
2987 let checkpoint = repo.checkpoint().await.unwrap();
2988
2989 smol::fs::write(&text_path, "fn main() { println!(\"Modified\"); }")
2990 .await
2991 .unwrap();
2992 smol::fs::write(&bin_path, "Modified binary file")
2993 .await
2994 .unwrap();
2995
2996 repo.restore_checkpoint(checkpoint).await.unwrap();
2997
2998 // Text files should be restored to checkpoint state,
2999 // but binaries should not (they aren't tracked)
3000 assert_eq!(
3001 smol::fs::read_to_string(&text_path).await.unwrap(),
3002 "fn main() {}"
3003 );
3004
3005 assert_eq!(
3006 smol::fs::read_to_string(&bin_path).await.unwrap(),
3007 "Modified binary file"
3008 );
3009 }
3010
3011 #[test]
3012 fn test_branches_parsing() {
3013 // suppress "help: octal escapes are not supported, `\0` is always null"
3014 #[allow(clippy::octal_escapes)]
3015 let input = "*\0060964da10574cd9bf06463a53bf6e0769c5c45e\0\0refs/heads/zed-patches\0refs/remotes/origin/zed-patches\0\01733187470\0John Doe\0generated protobuf\n";
3016 assert_eq!(
3017 parse_branch_input(input).unwrap(),
3018 vec![Branch {
3019 is_head: true,
3020 ref_name: "refs/heads/zed-patches".into(),
3021 upstream: Some(Upstream {
3022 ref_name: "refs/remotes/origin/zed-patches".into(),
3023 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3024 ahead: 0,
3025 behind: 0
3026 })
3027 }),
3028 most_recent_commit: Some(CommitSummary {
3029 sha: "060964da10574cd9bf06463a53bf6e0769c5c45e".into(),
3030 subject: "generated protobuf".into(),
3031 commit_timestamp: 1733187470,
3032 author_name: SharedString::new("John Doe"),
3033 has_parent: false,
3034 })
3035 }]
3036 )
3037 }
3038
3039 #[test]
3040 fn test_branches_parsing_containing_refs_with_missing_fields() {
3041 #[allow(clippy::octal_escapes)]
3042 let input = " \090012116c03db04344ab10d50348553aa94f1ea0\0refs/heads/broken\n \0eb0cae33272689bd11030822939dd2701c52f81e\0895951d681e5561478c0acdd6905e8aacdfd2249\0refs/heads/dev\0\0\01762948725\0Zed\0Add feature\n*\0895951d681e5561478c0acdd6905e8aacdfd2249\0\0refs/heads/main\0\0\01762948695\0Zed\0Initial commit\n";
3043
3044 let branches = parse_branch_input(input).unwrap();
3045 assert_eq!(branches.len(), 2);
3046 assert_eq!(
3047 branches,
3048 vec![
3049 Branch {
3050 is_head: false,
3051 ref_name: "refs/heads/dev".into(),
3052 upstream: None,
3053 most_recent_commit: Some(CommitSummary {
3054 sha: "eb0cae33272689bd11030822939dd2701c52f81e".into(),
3055 subject: "Add feature".into(),
3056 commit_timestamp: 1762948725,
3057 author_name: SharedString::new("Zed"),
3058 has_parent: true,
3059 })
3060 },
3061 Branch {
3062 is_head: true,
3063 ref_name: "refs/heads/main".into(),
3064 upstream: None,
3065 most_recent_commit: Some(CommitSummary {
3066 sha: "895951d681e5561478c0acdd6905e8aacdfd2249".into(),
3067 subject: "Initial commit".into(),
3068 commit_timestamp: 1762948695,
3069 author_name: SharedString::new("Zed"),
3070 has_parent: false,
3071 })
3072 }
3073 ]
3074 )
3075 }
3076
3077 impl RealGitRepository {
3078 /// Force a Git garbage collection on the repository.
3079 fn gc(&self) -> BoxFuture<'_, Result<()>> {
3080 let working_directory = self.working_directory();
3081 let git_binary_path = self.any_git_binary_path.clone();
3082 let executor = self.executor.clone();
3083 self.executor
3084 .spawn(async move {
3085 let git_binary_path = git_binary_path.clone();
3086 let working_directory = working_directory?;
3087 let git = GitBinary::new(git_binary_path, working_directory, executor);
3088 git.run(&["gc", "--prune"]).await?;
3089 Ok(())
3090 })
3091 .boxed()
3092 }
3093 }
3094}