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.clone(), executor)
2247                    .envs(HashMap::clone(&env));
2248
2249                let output = git.run(&["help", "-a"]).await?;
2250                if !output.lines().any(|line| line.trim().starts_with("hook ")) {
2251                    log::warn!(
2252                        "git hook command not available, running the {} hook manually",
2253                        hook.as_str()
2254                    );
2255
2256                    let hook_abs_path = working_directory
2257                        .join(".git")
2258                        .join("hooks")
2259                        .join(hook.as_str());
2260                    if hook_abs_path.is_file() {
2261                        let output = new_smol_command(&hook_abs_path)
2262                            .envs(env.iter())
2263                            .current_dir(&working_directory)
2264                            .output()
2265                            .await?;
2266
2267                        anyhow::ensure!(
2268                            output.status.success(),
2269                            "{} hook failed:\n{}",
2270                            hook.as_str(),
2271                            String::from_utf8_lossy(&output.stderr)
2272                        );
2273                    }
2274
2275                    return Ok(());
2276                }
2277
2278                git.run(&["hook", "run", "--ignore-missing", hook.as_str()])
2279                    .await?;
2280                Ok(())
2281            })
2282            .boxed()
2283    }
2284}
2285
2286fn git_status_args(path_prefixes: &[RepoPath]) -> Vec<OsString> {
2287    let mut args = vec![
2288        OsString::from("--no-optional-locks"),
2289        OsString::from("status"),
2290        OsString::from("--porcelain=v1"),
2291        OsString::from("--untracked-files=all"),
2292        OsString::from("--no-renames"),
2293        OsString::from("-z"),
2294    ];
2295    args.extend(
2296        path_prefixes
2297            .iter()
2298            .map(|path_prefix| path_prefix.as_std_path().into()),
2299    );
2300    args.extend(path_prefixes.iter().map(|path_prefix| {
2301        if path_prefix.is_empty() {
2302            Path::new(".").into()
2303        } else {
2304            path_prefix.as_std_path().into()
2305        }
2306    }));
2307    args
2308}
2309
2310/// Temporarily git-ignore commonly ignored files and files over 2MB
2311async fn exclude_files(git: &GitBinary) -> Result<GitExcludeOverride> {
2312    const MAX_SIZE: u64 = 2 * 1024 * 1024; // 2 MB
2313    let mut excludes = git.with_exclude_overrides().await?;
2314    excludes
2315        .add_excludes(include_str!("./checkpoint.gitignore"))
2316        .await?;
2317
2318    let working_directory = git.working_directory.clone();
2319    let untracked_files = git.list_untracked_files().await?;
2320    let excluded_paths = untracked_files.into_iter().map(|path| {
2321        let working_directory = working_directory.clone();
2322        smol::spawn(async move {
2323            let full_path = working_directory.join(path.clone());
2324            match smol::fs::metadata(&full_path).await {
2325                Ok(metadata) if metadata.is_file() && metadata.len() >= MAX_SIZE => {
2326                    Some(PathBuf::from("/").join(path.clone()))
2327                }
2328                _ => None,
2329            }
2330        })
2331    });
2332
2333    let excluded_paths = futures::future::join_all(excluded_paths).await;
2334    let excluded_paths = excluded_paths.into_iter().flatten().collect::<Vec<_>>();
2335
2336    if !excluded_paths.is_empty() {
2337        let exclude_patterns = excluded_paths
2338            .into_iter()
2339            .map(|path| path.to_string_lossy().into_owned())
2340            .collect::<Vec<_>>()
2341            .join("\n");
2342        excludes.add_excludes(&exclude_patterns).await?;
2343    }
2344
2345    Ok(excludes)
2346}
2347
2348struct GitBinary {
2349    git_binary_path: PathBuf,
2350    working_directory: PathBuf,
2351    executor: BackgroundExecutor,
2352    index_file_path: Option<PathBuf>,
2353    envs: HashMap<String, String>,
2354}
2355
2356impl GitBinary {
2357    fn new(
2358        git_binary_path: PathBuf,
2359        working_directory: PathBuf,
2360        executor: BackgroundExecutor,
2361    ) -> Self {
2362        Self {
2363            git_binary_path,
2364            working_directory,
2365            executor,
2366            index_file_path: None,
2367            envs: HashMap::default(),
2368        }
2369    }
2370
2371    async fn list_untracked_files(&self) -> Result<Vec<PathBuf>> {
2372        let status_output = self
2373            .run(&["status", "--porcelain=v1", "--untracked-files=all", "-z"])
2374            .await?;
2375
2376        let paths = status_output
2377            .split('\0')
2378            .filter(|entry| entry.len() >= 3 && entry.starts_with("?? "))
2379            .map(|entry| PathBuf::from(&entry[3..]))
2380            .collect::<Vec<_>>();
2381        Ok(paths)
2382    }
2383
2384    fn envs(mut self, envs: HashMap<String, String>) -> Self {
2385        self.envs = envs;
2386        self
2387    }
2388
2389    pub async fn with_temp_index<R>(
2390        &mut self,
2391        f: impl AsyncFnOnce(&Self) -> Result<R>,
2392    ) -> Result<R> {
2393        let index_file_path = self.path_for_index_id(Uuid::new_v4());
2394
2395        let delete_temp_index = util::defer({
2396            let index_file_path = index_file_path.clone();
2397            let executor = self.executor.clone();
2398            move || {
2399                executor
2400                    .spawn(async move {
2401                        smol::fs::remove_file(index_file_path).await.log_err();
2402                    })
2403                    .detach();
2404            }
2405        });
2406
2407        // Copy the default index file so that Git doesn't have to rebuild the
2408        // whole index from scratch. This might fail if this is an empty repository.
2409        smol::fs::copy(
2410            self.working_directory.join(".git").join("index"),
2411            &index_file_path,
2412        )
2413        .await
2414        .ok();
2415
2416        self.index_file_path = Some(index_file_path.clone());
2417        let result = f(self).await;
2418        self.index_file_path = None;
2419        let result = result?;
2420
2421        smol::fs::remove_file(index_file_path).await.ok();
2422        delete_temp_index.abort();
2423
2424        Ok(result)
2425    }
2426
2427    pub async fn with_exclude_overrides(&self) -> Result<GitExcludeOverride> {
2428        let path = self
2429            .working_directory
2430            .join(".git")
2431            .join("info")
2432            .join("exclude");
2433
2434        GitExcludeOverride::new(path).await
2435    }
2436
2437    fn path_for_index_id(&self, id: Uuid) -> PathBuf {
2438        self.working_directory
2439            .join(".git")
2440            .join(format!("index-{}.tmp", id))
2441    }
2442
2443    pub async fn run<S>(&self, args: impl IntoIterator<Item = S>) -> Result<String>
2444    where
2445        S: AsRef<OsStr>,
2446    {
2447        let mut stdout = self.run_raw(args).await?;
2448        if stdout.chars().last() == Some('\n') {
2449            stdout.pop();
2450        }
2451        Ok(stdout)
2452    }
2453
2454    /// Returns the result of the command without trimming the trailing newline.
2455    pub async fn run_raw<S>(&self, args: impl IntoIterator<Item = S>) -> Result<String>
2456    where
2457        S: AsRef<OsStr>,
2458    {
2459        let mut command = self.build_command(args);
2460        let output = command.output().await?;
2461        anyhow::ensure!(
2462            output.status.success(),
2463            GitBinaryCommandError {
2464                stdout: String::from_utf8_lossy(&output.stdout).to_string(),
2465                stderr: String::from_utf8_lossy(&output.stderr).to_string(),
2466                status: output.status,
2467            }
2468        );
2469        Ok(String::from_utf8(output.stdout)?)
2470    }
2471
2472    fn build_command<S>(&self, args: impl IntoIterator<Item = S>) -> smol::process::Command
2473    where
2474        S: AsRef<OsStr>,
2475    {
2476        let mut command = new_smol_command(&self.git_binary_path);
2477        command.current_dir(&self.working_directory);
2478        command.args(args);
2479        if let Some(index_file_path) = self.index_file_path.as_ref() {
2480            command.env("GIT_INDEX_FILE", index_file_path);
2481        }
2482        command.envs(&self.envs);
2483        command
2484    }
2485}
2486
2487#[derive(Error, Debug)]
2488#[error("Git command failed:\n{stdout}{stderr}\n")]
2489struct GitBinaryCommandError {
2490    stdout: String,
2491    stderr: String,
2492    status: ExitStatus,
2493}
2494
2495async fn run_git_command(
2496    env: Arc<HashMap<String, String>>,
2497    ask_pass: AskPassDelegate,
2498    mut command: smol::process::Command,
2499    executor: &BackgroundExecutor,
2500) -> Result<RemoteCommandOutput> {
2501    if env.contains_key("GIT_ASKPASS") {
2502        let git_process = command.spawn()?;
2503        let output = git_process.output().await?;
2504        anyhow::ensure!(
2505            output.status.success(),
2506            "{}",
2507            String::from_utf8_lossy(&output.stderr)
2508        );
2509        Ok(RemoteCommandOutput {
2510            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
2511            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
2512        })
2513    } else {
2514        let ask_pass = AskPassSession::new(executor, ask_pass).await?;
2515        command
2516            .env("GIT_ASKPASS", ask_pass.script_path())
2517            .env("SSH_ASKPASS", ask_pass.script_path())
2518            .env("SSH_ASKPASS_REQUIRE", "force");
2519        let git_process = command.spawn()?;
2520
2521        run_askpass_command(ask_pass, git_process).await
2522    }
2523}
2524
2525async fn run_askpass_command(
2526    mut ask_pass: AskPassSession,
2527    git_process: smol::process::Child,
2528) -> anyhow::Result<RemoteCommandOutput> {
2529    select_biased! {
2530        result = ask_pass.run().fuse() => {
2531            match result {
2532                AskPassResult::CancelledByUser => {
2533                    Err(anyhow!(REMOTE_CANCELLED_BY_USER))?
2534                }
2535                AskPassResult::Timedout => {
2536                    Err(anyhow!("Connecting to host timed out"))?
2537                }
2538            }
2539        }
2540        output = git_process.output().fuse() => {
2541            let output = output?;
2542            anyhow::ensure!(
2543                output.status.success(),
2544                "{}",
2545                String::from_utf8_lossy(&output.stderr)
2546            );
2547            Ok(RemoteCommandOutput {
2548                stdout: String::from_utf8_lossy(&output.stdout).to_string(),
2549                stderr: String::from_utf8_lossy(&output.stderr).to_string(),
2550            })
2551        }
2552    }
2553}
2554
2555#[derive(Clone, Ord, Hash, PartialOrd, Eq, PartialEq)]
2556pub struct RepoPath(Arc<RelPath>);
2557
2558impl std::fmt::Debug for RepoPath {
2559    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2560        self.0.fmt(f)
2561    }
2562}
2563
2564impl RepoPath {
2565    pub fn new<S: AsRef<str> + ?Sized>(s: &S) -> Result<Self> {
2566        let rel_path = RelPath::unix(s.as_ref())?;
2567        Ok(Self::from_rel_path(rel_path))
2568    }
2569
2570    pub fn from_std_path(path: &Path, path_style: PathStyle) -> Result<Self> {
2571        let rel_path = RelPath::new(path, path_style)?;
2572        Ok(Self::from_rel_path(&rel_path))
2573    }
2574
2575    pub fn from_proto(proto: &str) -> Result<Self> {
2576        let rel_path = RelPath::from_proto(proto)?;
2577        Ok(Self(rel_path))
2578    }
2579
2580    pub fn from_rel_path(path: &RelPath) -> RepoPath {
2581        Self(Arc::from(path))
2582    }
2583
2584    pub fn as_std_path(&self) -> &Path {
2585        // git2 does not like empty paths and our RelPath infra turns `.` into ``
2586        // so undo that here
2587        if self.is_empty() {
2588            Path::new(".")
2589        } else {
2590            self.0.as_std_path()
2591        }
2592    }
2593}
2594
2595#[cfg(any(test, feature = "test-support"))]
2596pub fn repo_path<S: AsRef<str> + ?Sized>(s: &S) -> RepoPath {
2597    RepoPath(RelPath::unix(s.as_ref()).unwrap().into())
2598}
2599
2600impl AsRef<Arc<RelPath>> for RepoPath {
2601    fn as_ref(&self) -> &Arc<RelPath> {
2602        &self.0
2603    }
2604}
2605
2606impl std::ops::Deref for RepoPath {
2607    type Target = RelPath;
2608
2609    fn deref(&self) -> &Self::Target {
2610        &self.0
2611    }
2612}
2613
2614#[derive(Debug)]
2615pub struct RepoPathDescendants<'a>(pub &'a RepoPath);
2616
2617impl MapSeekTarget<RepoPath> for RepoPathDescendants<'_> {
2618    fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
2619        if key.starts_with(self.0) {
2620            Ordering::Greater
2621        } else {
2622            self.0.cmp(key)
2623        }
2624    }
2625}
2626
2627fn parse_branch_input(input: &str) -> Result<Vec<Branch>> {
2628    let mut branches = Vec::new();
2629    for line in input.split('\n') {
2630        if line.is_empty() {
2631            continue;
2632        }
2633        let mut fields = line.split('\x00');
2634        let Some(head) = fields.next() else {
2635            continue;
2636        };
2637        let Some(head_sha) = fields.next().map(|f| f.to_string().into()) else {
2638            continue;
2639        };
2640        let Some(parent_sha) = fields.next().map(|f| f.to_string()) else {
2641            continue;
2642        };
2643        let Some(ref_name) = fields.next().map(|f| f.to_string().into()) else {
2644            continue;
2645        };
2646        let Some(upstream_name) = fields.next().map(|f| f.to_string()) else {
2647            continue;
2648        };
2649        let Some(upstream_tracking) = fields.next().and_then(|f| parse_upstream_track(f).ok())
2650        else {
2651            continue;
2652        };
2653        let Some(commiterdate) = fields.next().and_then(|f| f.parse::<i64>().ok()) else {
2654            continue;
2655        };
2656        let Some(author_name) = fields.next().map(|f| f.to_string().into()) else {
2657            continue;
2658        };
2659        let Some(subject) = fields.next().map(|f| f.to_string().into()) else {
2660            continue;
2661        };
2662
2663        branches.push(Branch {
2664            is_head: head == "*",
2665            ref_name,
2666            most_recent_commit: Some(CommitSummary {
2667                sha: head_sha,
2668                subject,
2669                commit_timestamp: commiterdate,
2670                author_name: author_name,
2671                has_parent: !parent_sha.is_empty(),
2672            }),
2673            upstream: if upstream_name.is_empty() {
2674                None
2675            } else {
2676                Some(Upstream {
2677                    ref_name: upstream_name.into(),
2678                    tracking: upstream_tracking,
2679                })
2680            },
2681        })
2682    }
2683
2684    Ok(branches)
2685}
2686
2687fn parse_upstream_track(upstream_track: &str) -> Result<UpstreamTracking> {
2688    if upstream_track.is_empty() {
2689        return Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
2690            ahead: 0,
2691            behind: 0,
2692        }));
2693    }
2694
2695    let upstream_track = upstream_track.strip_prefix("[").context("missing [")?;
2696    let upstream_track = upstream_track.strip_suffix("]").context("missing [")?;
2697    let mut ahead: u32 = 0;
2698    let mut behind: u32 = 0;
2699    for component in upstream_track.split(", ") {
2700        if component == "gone" {
2701            return Ok(UpstreamTracking::Gone);
2702        }
2703        if let Some(ahead_num) = component.strip_prefix("ahead ") {
2704            ahead = ahead_num.parse::<u32>()?;
2705        }
2706        if let Some(behind_num) = component.strip_prefix("behind ") {
2707            behind = behind_num.parse::<u32>()?;
2708        }
2709    }
2710    Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
2711        ahead,
2712        behind,
2713    }))
2714}
2715
2716fn checkpoint_author_envs() -> HashMap<String, String> {
2717    HashMap::from_iter([
2718        ("GIT_AUTHOR_NAME".to_string(), "Zed".to_string()),
2719        ("GIT_AUTHOR_EMAIL".to_string(), "hi@zed.dev".to_string()),
2720        ("GIT_COMMITTER_NAME".to_string(), "Zed".to_string()),
2721        ("GIT_COMMITTER_EMAIL".to_string(), "hi@zed.dev".to_string()),
2722    ])
2723}
2724
2725#[cfg(test)]
2726mod tests {
2727    use super::*;
2728    use gpui::TestAppContext;
2729
2730    fn disable_git_global_config() {
2731        unsafe {
2732            std::env::set_var("GIT_CONFIG_GLOBAL", "");
2733            std::env::set_var("GIT_CONFIG_SYSTEM", "");
2734        }
2735    }
2736
2737    #[gpui::test]
2738    async fn test_checkpoint_basic(cx: &mut TestAppContext) {
2739        disable_git_global_config();
2740
2741        cx.executor().allow_parking();
2742
2743        let repo_dir = tempfile::tempdir().unwrap();
2744
2745        git2::Repository::init(repo_dir.path()).unwrap();
2746        let file_path = repo_dir.path().join("file");
2747        smol::fs::write(&file_path, "initial").await.unwrap();
2748
2749        let repo = RealGitRepository::new(
2750            &repo_dir.path().join(".git"),
2751            None,
2752            Some("git".into()),
2753            cx.executor(),
2754        )
2755        .unwrap();
2756
2757        repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
2758            .await
2759            .unwrap();
2760        repo.commit(
2761            "Initial commit".into(),
2762            None,
2763            CommitOptions::default(),
2764            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
2765            Arc::new(checkpoint_author_envs()),
2766        )
2767        .await
2768        .unwrap();
2769
2770        smol::fs::write(&file_path, "modified before checkpoint")
2771            .await
2772            .unwrap();
2773        smol::fs::write(repo_dir.path().join("new_file_before_checkpoint"), "1")
2774            .await
2775            .unwrap();
2776        let checkpoint = repo.checkpoint().await.unwrap();
2777
2778        // Ensure the user can't see any branches after creating a checkpoint.
2779        assert_eq!(repo.branches().await.unwrap().len(), 1);
2780
2781        smol::fs::write(&file_path, "modified after checkpoint")
2782            .await
2783            .unwrap();
2784        repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
2785            .await
2786            .unwrap();
2787        repo.commit(
2788            "Commit after checkpoint".into(),
2789            None,
2790            CommitOptions::default(),
2791            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
2792            Arc::new(checkpoint_author_envs()),
2793        )
2794        .await
2795        .unwrap();
2796
2797        smol::fs::remove_file(repo_dir.path().join("new_file_before_checkpoint"))
2798            .await
2799            .unwrap();
2800        smol::fs::write(repo_dir.path().join("new_file_after_checkpoint"), "2")
2801            .await
2802            .unwrap();
2803
2804        // Ensure checkpoint stays alive even after a Git GC.
2805        repo.gc().await.unwrap();
2806        repo.restore_checkpoint(checkpoint.clone()).await.unwrap();
2807
2808        assert_eq!(
2809            smol::fs::read_to_string(&file_path).await.unwrap(),
2810            "modified before checkpoint"
2811        );
2812        assert_eq!(
2813            smol::fs::read_to_string(repo_dir.path().join("new_file_before_checkpoint"))
2814                .await
2815                .unwrap(),
2816            "1"
2817        );
2818        // See TODO above
2819        // assert_eq!(
2820        //     smol::fs::read_to_string(repo_dir.path().join("new_file_after_checkpoint"))
2821        //         .await
2822        //         .ok(),
2823        //     None
2824        // );
2825    }
2826
2827    #[gpui::test]
2828    async fn test_checkpoint_empty_repo(cx: &mut TestAppContext) {
2829        disable_git_global_config();
2830
2831        cx.executor().allow_parking();
2832
2833        let repo_dir = tempfile::tempdir().unwrap();
2834        git2::Repository::init(repo_dir.path()).unwrap();
2835        let repo = RealGitRepository::new(
2836            &repo_dir.path().join(".git"),
2837            None,
2838            Some("git".into()),
2839            cx.executor(),
2840        )
2841        .unwrap();
2842
2843        smol::fs::write(repo_dir.path().join("foo"), "foo")
2844            .await
2845            .unwrap();
2846        let checkpoint_sha = repo.checkpoint().await.unwrap();
2847
2848        // Ensure the user can't see any branches after creating a checkpoint.
2849        assert_eq!(repo.branches().await.unwrap().len(), 1);
2850
2851        smol::fs::write(repo_dir.path().join("foo"), "bar")
2852            .await
2853            .unwrap();
2854        smol::fs::write(repo_dir.path().join("baz"), "qux")
2855            .await
2856            .unwrap();
2857        repo.restore_checkpoint(checkpoint_sha).await.unwrap();
2858        assert_eq!(
2859            smol::fs::read_to_string(repo_dir.path().join("foo"))
2860                .await
2861                .unwrap(),
2862            "foo"
2863        );
2864        // See TODOs above
2865        // assert_eq!(
2866        //     smol::fs::read_to_string(repo_dir.path().join("baz"))
2867        //         .await
2868        //         .ok(),
2869        //     None
2870        // );
2871    }
2872
2873    #[gpui::test]
2874    async fn test_compare_checkpoints(cx: &mut TestAppContext) {
2875        disable_git_global_config();
2876
2877        cx.executor().allow_parking();
2878
2879        let repo_dir = tempfile::tempdir().unwrap();
2880        git2::Repository::init(repo_dir.path()).unwrap();
2881        let repo = RealGitRepository::new(
2882            &repo_dir.path().join(".git"),
2883            None,
2884            Some("git".into()),
2885            cx.executor(),
2886        )
2887        .unwrap();
2888
2889        smol::fs::write(repo_dir.path().join("file1"), "content1")
2890            .await
2891            .unwrap();
2892        let checkpoint1 = repo.checkpoint().await.unwrap();
2893
2894        smol::fs::write(repo_dir.path().join("file2"), "content2")
2895            .await
2896            .unwrap();
2897        let checkpoint2 = repo.checkpoint().await.unwrap();
2898
2899        assert!(
2900            !repo
2901                .compare_checkpoints(checkpoint1, checkpoint2.clone())
2902                .await
2903                .unwrap()
2904        );
2905
2906        let checkpoint3 = repo.checkpoint().await.unwrap();
2907        assert!(
2908            repo.compare_checkpoints(checkpoint2, checkpoint3)
2909                .await
2910                .unwrap()
2911        );
2912    }
2913
2914    #[gpui::test]
2915    async fn test_checkpoint_exclude_binary_files(cx: &mut TestAppContext) {
2916        disable_git_global_config();
2917
2918        cx.executor().allow_parking();
2919
2920        let repo_dir = tempfile::tempdir().unwrap();
2921        let text_path = repo_dir.path().join("main.rs");
2922        let bin_path = repo_dir.path().join("binary.o");
2923
2924        git2::Repository::init(repo_dir.path()).unwrap();
2925
2926        smol::fs::write(&text_path, "fn main() {}").await.unwrap();
2927
2928        smol::fs::write(&bin_path, "some binary file here")
2929            .await
2930            .unwrap();
2931
2932        let repo = RealGitRepository::new(
2933            &repo_dir.path().join(".git"),
2934            None,
2935            Some("git".into()),
2936            cx.executor(),
2937        )
2938        .unwrap();
2939
2940        // initial commit
2941        repo.stage_paths(vec![repo_path("main.rs")], Arc::new(HashMap::default()))
2942            .await
2943            .unwrap();
2944        repo.commit(
2945            "Initial commit".into(),
2946            None,
2947            CommitOptions::default(),
2948            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
2949            Arc::new(checkpoint_author_envs()),
2950        )
2951        .await
2952        .unwrap();
2953
2954        let checkpoint = repo.checkpoint().await.unwrap();
2955
2956        smol::fs::write(&text_path, "fn main() { println!(\"Modified\"); }")
2957            .await
2958            .unwrap();
2959        smol::fs::write(&bin_path, "Modified binary file")
2960            .await
2961            .unwrap();
2962
2963        repo.restore_checkpoint(checkpoint).await.unwrap();
2964
2965        // Text files should be restored to checkpoint state,
2966        // but binaries should not (they aren't tracked)
2967        assert_eq!(
2968            smol::fs::read_to_string(&text_path).await.unwrap(),
2969            "fn main() {}"
2970        );
2971
2972        assert_eq!(
2973            smol::fs::read_to_string(&bin_path).await.unwrap(),
2974            "Modified binary file"
2975        );
2976    }
2977
2978    #[test]
2979    fn test_branches_parsing() {
2980        // suppress "help: octal escapes are not supported, `\0` is always null"
2981        #[allow(clippy::octal_escapes)]
2982        let input = "*\0060964da10574cd9bf06463a53bf6e0769c5c45e\0\0refs/heads/zed-patches\0refs/remotes/origin/zed-patches\0\01733187470\0John Doe\0generated protobuf\n";
2983        assert_eq!(
2984            parse_branch_input(input).unwrap(),
2985            vec![Branch {
2986                is_head: true,
2987                ref_name: "refs/heads/zed-patches".into(),
2988                upstream: Some(Upstream {
2989                    ref_name: "refs/remotes/origin/zed-patches".into(),
2990                    tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
2991                        ahead: 0,
2992                        behind: 0
2993                    })
2994                }),
2995                most_recent_commit: Some(CommitSummary {
2996                    sha: "060964da10574cd9bf06463a53bf6e0769c5c45e".into(),
2997                    subject: "generated protobuf".into(),
2998                    commit_timestamp: 1733187470,
2999                    author_name: SharedString::new("John Doe"),
3000                    has_parent: false,
3001                })
3002            }]
3003        )
3004    }
3005
3006    #[test]
3007    fn test_branches_parsing_containing_refs_with_missing_fields() {
3008        #[allow(clippy::octal_escapes)]
3009        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";
3010
3011        let branches = parse_branch_input(input).unwrap();
3012        assert_eq!(branches.len(), 2);
3013        assert_eq!(
3014            branches,
3015            vec![
3016                Branch {
3017                    is_head: false,
3018                    ref_name: "refs/heads/dev".into(),
3019                    upstream: None,
3020                    most_recent_commit: Some(CommitSummary {
3021                        sha: "eb0cae33272689bd11030822939dd2701c52f81e".into(),
3022                        subject: "Add feature".into(),
3023                        commit_timestamp: 1762948725,
3024                        author_name: SharedString::new("Zed"),
3025                        has_parent: true,
3026                    })
3027                },
3028                Branch {
3029                    is_head: true,
3030                    ref_name: "refs/heads/main".into(),
3031                    upstream: None,
3032                    most_recent_commit: Some(CommitSummary {
3033                        sha: "895951d681e5561478c0acdd6905e8aacdfd2249".into(),
3034                        subject: "Initial commit".into(),
3035                        commit_timestamp: 1762948695,
3036                        author_name: SharedString::new("Zed"),
3037                        has_parent: false,
3038                    })
3039                }
3040            ]
3041        )
3042    }
3043
3044    impl RealGitRepository {
3045        /// Force a Git garbage collection on the repository.
3046        fn gc(&self) -> BoxFuture<'_, Result<()>> {
3047            let working_directory = self.working_directory();
3048            let git_binary_path = self.any_git_binary_path.clone();
3049            let executor = self.executor.clone();
3050            self.executor
3051                .spawn(async move {
3052                    let git_binary_path = git_binary_path.clone();
3053                    let working_directory = working_directory?;
3054                    let git = GitBinary::new(git_binary_path, working_directory, executor);
3055                    git.run(&["gc", "--prune"]).await?;
3056                    Ok(())
3057                })
3058                .boxed()
3059        }
3060    }
3061}