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