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