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