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