repository.rs

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