repository.rs

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