repository.rs

   1use crate::commit::parse_git_diff_name_status;
   2use crate::stash::GitStash;
   3use crate::status::{DiffTreeType, GitStatus, StatusCode, TreeDiff};
   4use crate::{Oid, RunHook, SHORT_SHA_LENGTH};
   5use anyhow::{Context as _, Result, anyhow, bail};
   6use collections::HashMap;
   7use futures::channel::oneshot;
   8use futures::future::BoxFuture;
   9use futures::io::BufWriter;
  10use futures::{AsyncWriteExt, FutureExt as _, select_biased};
  11use git2::{BranchType, ErrorCode};
  12use gpui::{AppContext as _, AsyncApp, BackgroundExecutor, SharedString, Task};
  13use parking_lot::Mutex;
  14use rope::Rope;
  15use schemars::JsonSchema;
  16use serde::Deserialize;
  17use smallvec::SmallVec;
  18use smol::channel::Sender;
  19use smol::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
  20use text::LineEnding;
  21
  22use std::collections::HashSet;
  23use std::ffi::{OsStr, OsString};
  24use std::sync::atomic::AtomicBool;
  25
  26use std::process::ExitStatus;
  27use std::str::FromStr;
  28use std::{
  29    cmp::Ordering,
  30    future,
  31    path::{Path, PathBuf},
  32    sync::Arc,
  33};
  34use sum_tree::MapSeekTarget;
  35use thiserror::Error;
  36use util::command::{Stdio, new_command};
  37use util::paths::PathStyle;
  38use util::rel_path::RelPath;
  39use util::{ResultExt, paths};
  40use uuid::Uuid;
  41
  42pub use askpass::{AskPassDelegate, AskPassResult, AskPassSession};
  43
  44pub const REMOTE_CANCELLED_BY_USER: &str = "Operation cancelled by user";
  45
  46/// Format string used in graph log to get initial data for the git graph
  47/// %H - Full commit hash
  48/// %P - Parent hashes
  49/// %D - Ref names
  50/// %x00 - Null byte separator, used to split up commit data
  51static GRAPH_COMMIT_FORMAT: &str = "--format=%H%x00%P%x00%D";
  52
  53/// Used to get commits that match with a search
  54/// %H - Full commit hash
  55static SEARCH_COMMIT_FORMAT: &str = "--format=%H";
  56
  57/// Number of commits to load per chunk for the git graph.
  58pub const GRAPH_CHUNK_SIZE: usize = 1000;
  59
  60/// Default value for the `git.worktree_directory` setting.
  61pub const DEFAULT_WORKTREE_DIRECTORY: &str = "../worktrees";
  62
  63/// Given the git common directory (from `commondir()`), derive the original
  64/// repository's working directory.
  65///
  66/// For a standard checkout, `common_dir` is `<work_dir>/.git`, so the parent
  67/// is the working directory. For a git worktree, `common_dir` is the **main**
  68/// repo's `.git` directory, so the parent is the original repo's working directory.
  69///
  70/// Falls back to returning `common_dir` itself if it doesn't end with `.git`
  71/// (e.g. bare repos or unusual layouts).
  72pub fn original_repo_path_from_common_dir(common_dir: &Path) -> PathBuf {
  73    if common_dir.file_name() == Some(OsStr::new(".git")) {
  74        common_dir
  75            .parent()
  76            .map(|p| p.to_path_buf())
  77            .unwrap_or_else(|| common_dir.to_path_buf())
  78    } else {
  79        common_dir.to_path_buf()
  80    }
  81}
  82
  83/// Commit data needed for the git graph visualization.
  84#[derive(Debug, Clone)]
  85pub struct GraphCommitData {
  86    pub sha: Oid,
  87    /// Most commits have a single parent, so we use a SmallVec to avoid allocations.
  88    pub parents: SmallVec<[Oid; 1]>,
  89    pub author_name: SharedString,
  90    pub author_email: SharedString,
  91    pub commit_timestamp: i64,
  92    pub subject: SharedString,
  93}
  94
  95#[derive(Debug)]
  96pub struct InitialGraphCommitData {
  97    pub sha: Oid,
  98    pub parents: SmallVec<[Oid; 1]>,
  99    pub ref_names: Vec<SharedString>,
 100}
 101
 102struct CommitDataRequest {
 103    sha: Oid,
 104    response_tx: oneshot::Sender<Result<GraphCommitData>>,
 105}
 106
 107pub struct CommitDataReader {
 108    request_tx: smol::channel::Sender<CommitDataRequest>,
 109    _task: Task<()>,
 110}
 111
 112impl CommitDataReader {
 113    pub async fn read(&self, sha: Oid) -> Result<GraphCommitData> {
 114        let (response_tx, response_rx) = oneshot::channel();
 115        self.request_tx
 116            .send(CommitDataRequest { sha, response_tx })
 117            .await
 118            .map_err(|_| anyhow!("commit data reader task closed"))?;
 119        response_rx
 120            .await
 121            .map_err(|_| anyhow!("commit data reader task dropped response"))?
 122    }
 123}
 124
 125fn parse_cat_file_commit(sha: Oid, content: &str) -> Option<GraphCommitData> {
 126    let mut parents = SmallVec::new();
 127    let mut author_name = SharedString::default();
 128    let mut author_email = SharedString::default();
 129    let mut commit_timestamp = 0i64;
 130    let mut in_headers = true;
 131    let mut subject = None;
 132
 133    for line in content.lines() {
 134        if in_headers {
 135            if line.is_empty() {
 136                in_headers = false;
 137                continue;
 138            }
 139
 140            if let Some(parent_sha) = line.strip_prefix("parent ") {
 141                if let Ok(oid) = Oid::from_str(parent_sha.trim()) {
 142                    parents.push(oid);
 143                }
 144            } else if let Some(author_line) = line.strip_prefix("author ") {
 145                if let Some((name_email, _timestamp_tz)) = author_line.rsplit_once(' ') {
 146                    if let Some((name_email, timestamp_str)) = name_email.rsplit_once(' ') {
 147                        if let Ok(ts) = timestamp_str.parse::<i64>() {
 148                            commit_timestamp = ts;
 149                        }
 150                        if let Some((name, email)) = name_email.rsplit_once(" <") {
 151                            author_name = SharedString::from(name.to_string());
 152                            author_email =
 153                                SharedString::from(email.trim_end_matches('>').to_string());
 154                        }
 155                    }
 156                }
 157            }
 158        } else if subject.is_none() {
 159            subject = Some(SharedString::from(line.to_string()));
 160        }
 161    }
 162
 163    Some(GraphCommitData {
 164        sha,
 165        parents,
 166        author_name,
 167        author_email,
 168        commit_timestamp,
 169        subject: subject.unwrap_or_default(),
 170    })
 171}
 172
 173#[derive(Clone, Debug, Hash, PartialEq, Eq)]
 174pub struct Branch {
 175    pub is_head: bool,
 176    pub ref_name: SharedString,
 177    pub upstream: Option<Upstream>,
 178    pub most_recent_commit: Option<CommitSummary>,
 179}
 180
 181impl Branch {
 182    pub fn name(&self) -> &str {
 183        self.ref_name
 184            .as_ref()
 185            .strip_prefix("refs/heads/")
 186            .or_else(|| self.ref_name.as_ref().strip_prefix("refs/remotes/"))
 187            .unwrap_or(self.ref_name.as_ref())
 188    }
 189
 190    pub fn is_remote(&self) -> bool {
 191        self.ref_name.starts_with("refs/remotes/")
 192    }
 193
 194    pub fn remote_name(&self) -> Option<&str> {
 195        self.ref_name
 196            .strip_prefix("refs/remotes/")
 197            .and_then(|stripped| stripped.split("/").next())
 198    }
 199
 200    pub fn tracking_status(&self) -> Option<UpstreamTrackingStatus> {
 201        self.upstream
 202            .as_ref()
 203            .and_then(|upstream| upstream.tracking.status())
 204    }
 205
 206    pub fn priority_key(&self) -> (bool, Option<i64>) {
 207        (
 208            self.is_head,
 209            self.most_recent_commit
 210                .as_ref()
 211                .map(|commit| commit.commit_timestamp),
 212        )
 213    }
 214}
 215
 216#[derive(Clone, Debug, Hash, PartialEq, Eq)]
 217pub struct Worktree {
 218    pub path: PathBuf,
 219    pub ref_name: Option<SharedString>,
 220    // todo(git_worktree) This type should be a Oid
 221    pub sha: SharedString,
 222}
 223
 224impl Worktree {
 225    /// Returns a display name for the worktree, suitable for use in the UI.
 226    ///
 227    /// If the worktree is attached to a branch, returns the branch name.
 228    /// Otherwise, returns the short SHA of the worktree's HEAD commit.
 229    pub fn display_name(&self) -> &str {
 230        match self.ref_name {
 231            Some(ref ref_name) => ref_name
 232                .strip_prefix("refs/heads/")
 233                .or_else(|| ref_name.strip_prefix("refs/remotes/"))
 234                .unwrap_or(ref_name),
 235            // Detached HEAD — show the short SHA as a fallback.
 236            None => &self.sha[..self.sha.len().min(SHORT_SHA_LENGTH)],
 237        }
 238    }
 239}
 240
 241pub fn parse_worktrees_from_str<T: AsRef<str>>(raw_worktrees: T) -> Vec<Worktree> {
 242    let mut worktrees = Vec::new();
 243    let normalized = raw_worktrees.as_ref().replace("\r\n", "\n");
 244    let entries = normalized.split("\n\n");
 245    for entry in entries {
 246        let mut path = None;
 247        let mut sha = None;
 248        let mut ref_name = None;
 249
 250        for line in entry.lines() {
 251            let line = line.trim();
 252            if line.is_empty() {
 253                continue;
 254            }
 255            if let Some(rest) = line.strip_prefix("worktree ") {
 256                path = Some(rest.to_string());
 257            } else if let Some(rest) = line.strip_prefix("HEAD ") {
 258                sha = Some(rest.to_string());
 259            } else if let Some(rest) = line.strip_prefix("branch ") {
 260                ref_name = Some(rest.to_string());
 261            }
 262            // Ignore other lines: detached, bare, locked, prunable, etc.
 263        }
 264
 265        if let (Some(path), Some(sha)) = (path, sha) {
 266            worktrees.push(Worktree {
 267                path: PathBuf::from(path),
 268                ref_name: ref_name.map(Into::into),
 269                sha: sha.into(),
 270            })
 271        }
 272    }
 273
 274    worktrees
 275}
 276
 277#[derive(Clone, Debug, Hash, PartialEq, Eq)]
 278pub struct Upstream {
 279    pub ref_name: SharedString,
 280    pub tracking: UpstreamTracking,
 281}
 282
 283impl Upstream {
 284    pub fn is_remote(&self) -> bool {
 285        self.remote_name().is_some()
 286    }
 287
 288    pub fn remote_name(&self) -> Option<&str> {
 289        self.ref_name
 290            .strip_prefix("refs/remotes/")
 291            .and_then(|stripped| stripped.split("/").next())
 292    }
 293
 294    pub fn stripped_ref_name(&self) -> Option<&str> {
 295        self.ref_name.strip_prefix("refs/remotes/")
 296    }
 297
 298    pub fn branch_name(&self) -> Option<&str> {
 299        self.ref_name
 300            .strip_prefix("refs/remotes/")
 301            .and_then(|stripped| stripped.split_once('/').map(|(_, name)| name))
 302    }
 303}
 304
 305#[derive(Clone, Copy, Default)]
 306pub struct CommitOptions {
 307    pub amend: bool,
 308    pub signoff: bool,
 309}
 310
 311#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
 312pub enum UpstreamTracking {
 313    /// Remote ref not present in local repository.
 314    Gone,
 315    /// Remote ref present in local repository (fetched from remote).
 316    Tracked(UpstreamTrackingStatus),
 317}
 318
 319impl From<UpstreamTrackingStatus> for UpstreamTracking {
 320    fn from(status: UpstreamTrackingStatus) -> Self {
 321        UpstreamTracking::Tracked(status)
 322    }
 323}
 324
 325impl UpstreamTracking {
 326    pub fn is_gone(&self) -> bool {
 327        matches!(self, UpstreamTracking::Gone)
 328    }
 329
 330    pub fn status(&self) -> Option<UpstreamTrackingStatus> {
 331        match self {
 332            UpstreamTracking::Gone => None,
 333            UpstreamTracking::Tracked(status) => Some(*status),
 334        }
 335    }
 336}
 337
 338#[derive(Debug, Clone)]
 339pub struct RemoteCommandOutput {
 340    pub stdout: String,
 341    pub stderr: String,
 342}
 343
 344impl RemoteCommandOutput {
 345    pub fn is_empty(&self) -> bool {
 346        self.stdout.is_empty() && self.stderr.is_empty()
 347    }
 348}
 349
 350#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
 351pub struct UpstreamTrackingStatus {
 352    pub ahead: u32,
 353    pub behind: u32,
 354}
 355
 356#[derive(Clone, Debug, Hash, PartialEq, Eq)]
 357pub struct CommitSummary {
 358    pub sha: SharedString,
 359    pub subject: SharedString,
 360    /// This is a unix timestamp
 361    pub commit_timestamp: i64,
 362    pub author_name: SharedString,
 363    pub has_parent: bool,
 364}
 365
 366#[derive(Clone, Debug, Default, Hash, PartialEq, Eq)]
 367pub struct CommitDetails {
 368    pub sha: SharedString,
 369    pub message: SharedString,
 370    pub commit_timestamp: i64,
 371    pub author_email: SharedString,
 372    pub author_name: SharedString,
 373}
 374
 375#[derive(Clone, Debug, Hash, PartialEq, Eq)]
 376pub struct FileHistoryEntry {
 377    pub sha: SharedString,
 378    pub subject: SharedString,
 379    pub message: SharedString,
 380    pub commit_timestamp: i64,
 381    pub author_name: SharedString,
 382    pub author_email: SharedString,
 383}
 384
 385#[derive(Debug, Clone)]
 386pub struct FileHistory {
 387    pub entries: Vec<FileHistoryEntry>,
 388    pub path: RepoPath,
 389}
 390
 391#[derive(Debug)]
 392pub struct CommitDiff {
 393    pub files: Vec<CommitFile>,
 394}
 395
 396#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
 397pub enum CommitFileStatus {
 398    Added,
 399    Modified,
 400    Deleted,
 401}
 402
 403#[derive(Debug)]
 404pub struct CommitFile {
 405    pub path: RepoPath,
 406    pub old_text: Option<String>,
 407    pub new_text: Option<String>,
 408    pub is_binary: bool,
 409}
 410
 411impl CommitFile {
 412    pub fn status(&self) -> CommitFileStatus {
 413        match (&self.old_text, &self.new_text) {
 414            (None, Some(_)) => CommitFileStatus::Added,
 415            (Some(_), None) => CommitFileStatus::Deleted,
 416            _ => CommitFileStatus::Modified,
 417        }
 418    }
 419}
 420
 421impl CommitDetails {
 422    pub fn short_sha(&self) -> SharedString {
 423        self.sha[..SHORT_SHA_LENGTH].to_string().into()
 424    }
 425}
 426
 427/// Detects if content is binary by checking for NUL bytes in the first 8000 bytes.
 428/// This matches git's binary detection heuristic.
 429pub fn is_binary_content(content: &[u8]) -> bool {
 430    let check_len = content.len().min(8000);
 431    content[..check_len].contains(&0)
 432}
 433
 434#[derive(Debug, Clone, Hash, PartialEq, Eq)]
 435pub struct Remote {
 436    pub name: SharedString,
 437}
 438
 439pub enum ResetMode {
 440    /// Reset the branch pointer, leave index and worktree unchanged (this will make it look like things that were
 441    /// committed are now staged).
 442    Soft,
 443    /// Reset the branch pointer and index, leave worktree unchanged (this makes it look as though things that were
 444    /// committed are now unstaged).
 445    Mixed,
 446}
 447
 448#[derive(Debug, Clone, Hash, PartialEq, Eq)]
 449pub enum FetchOptions {
 450    All,
 451    Remote(Remote),
 452}
 453
 454impl FetchOptions {
 455    pub fn to_proto(&self) -> Option<String> {
 456        match self {
 457            FetchOptions::All => None,
 458            FetchOptions::Remote(remote) => Some(remote.clone().name.into()),
 459        }
 460    }
 461
 462    pub fn from_proto(remote_name: Option<String>) -> Self {
 463        match remote_name {
 464            Some(name) => FetchOptions::Remote(Remote { name: name.into() }),
 465            None => FetchOptions::All,
 466        }
 467    }
 468
 469    pub fn name(&self) -> SharedString {
 470        match self {
 471            Self::All => "Fetch all remotes".into(),
 472            Self::Remote(remote) => remote.name.clone(),
 473        }
 474    }
 475}
 476
 477impl std::fmt::Display for FetchOptions {
 478    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 479        match self {
 480            FetchOptions::All => write!(f, "--all"),
 481            FetchOptions::Remote(remote) => write!(f, "{}", remote.name),
 482        }
 483    }
 484}
 485
 486/// Modifies .git/info/exclude temporarily
 487pub struct GitExcludeOverride {
 488    git_exclude_path: PathBuf,
 489    original_excludes: Option<String>,
 490    added_excludes: Option<String>,
 491}
 492
 493impl GitExcludeOverride {
 494    const START_BLOCK_MARKER: &str = "\n\n#  ====== Auto-added by Zed: =======\n";
 495    const END_BLOCK_MARKER: &str = "\n#  ====== End of auto-added by Zed =======\n";
 496
 497    pub async fn new(git_exclude_path: PathBuf) -> Result<Self> {
 498        let original_excludes =
 499            smol::fs::read_to_string(&git_exclude_path)
 500                .await
 501                .ok()
 502                .map(|content| {
 503                    // Auto-generated lines are normally cleaned up in
 504                    // `restore_original()` or `drop()`, but may stuck in rare cases.
 505                    // Make sure to remove them.
 506                    Self::remove_auto_generated_block(&content)
 507                });
 508
 509        Ok(GitExcludeOverride {
 510            git_exclude_path,
 511            original_excludes,
 512            added_excludes: None,
 513        })
 514    }
 515
 516    pub async fn add_excludes(&mut self, excludes: &str) -> Result<()> {
 517        self.added_excludes = Some(if let Some(ref already_added) = self.added_excludes {
 518            format!("{already_added}\n{excludes}")
 519        } else {
 520            excludes.to_string()
 521        });
 522
 523        let mut content = self.original_excludes.clone().unwrap_or_default();
 524
 525        content.push_str(Self::START_BLOCK_MARKER);
 526        content.push_str(self.added_excludes.as_ref().unwrap());
 527        content.push_str(Self::END_BLOCK_MARKER);
 528
 529        smol::fs::write(&self.git_exclude_path, content).await?;
 530        Ok(())
 531    }
 532
 533    pub async fn restore_original(&mut self) -> Result<()> {
 534        if let Some(ref original) = self.original_excludes {
 535            smol::fs::write(&self.git_exclude_path, original).await?;
 536        } else if self.git_exclude_path.exists() {
 537            smol::fs::remove_file(&self.git_exclude_path).await?;
 538        }
 539
 540        self.added_excludes = None;
 541
 542        Ok(())
 543    }
 544
 545    fn remove_auto_generated_block(content: &str) -> String {
 546        let start_marker = Self::START_BLOCK_MARKER;
 547        let end_marker = Self::END_BLOCK_MARKER;
 548        let mut content = content.to_string();
 549
 550        let start_index = content.find(start_marker);
 551        let end_index = content.rfind(end_marker);
 552
 553        if let (Some(start), Some(end)) = (start_index, end_index) {
 554            if end > start {
 555                content.replace_range(start..end + end_marker.len(), "");
 556            }
 557        }
 558
 559        // Older versions of Zed didn't have end-of-block markers,
 560        // so it's impossible to determine auto-generated lines.
 561        // Conservatively remove the standard list of excludes
 562        let standard_excludes = format!(
 563            "{}{}",
 564            Self::START_BLOCK_MARKER,
 565            include_str!("./checkpoint.gitignore")
 566        );
 567        content = content.replace(&standard_excludes, "");
 568
 569        content
 570    }
 571}
 572
 573impl Drop for GitExcludeOverride {
 574    fn drop(&mut self) {
 575        if self.added_excludes.is_some() {
 576            let git_exclude_path = self.git_exclude_path.clone();
 577            let original_excludes = self.original_excludes.clone();
 578            smol::spawn(async move {
 579                if let Some(original) = original_excludes {
 580                    smol::fs::write(&git_exclude_path, original).await
 581                } else {
 582                    smol::fs::remove_file(&git_exclude_path).await
 583                }
 584            })
 585            .detach();
 586        }
 587    }
 588}
 589
 590#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Copy)]
 591pub enum LogOrder {
 592    #[default]
 593    DateOrder,
 594    TopoOrder,
 595    AuthorDateOrder,
 596    ReverseChronological,
 597}
 598
 599impl LogOrder {
 600    pub fn as_arg(&self) -> &'static str {
 601        match self {
 602            LogOrder::DateOrder => "--date-order",
 603            LogOrder::TopoOrder => "--topo-order",
 604            LogOrder::AuthorDateOrder => "--author-date-order",
 605            LogOrder::ReverseChronological => "--reverse",
 606        }
 607    }
 608}
 609
 610#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
 611pub enum LogSource {
 612    #[default]
 613    All,
 614    Branch(SharedString),
 615    Sha(Oid),
 616}
 617
 618impl LogSource {
 619    fn get_arg(&self) -> Result<&str> {
 620        match self {
 621            LogSource::All => Ok("--all"),
 622            LogSource::Branch(branch) => Ok(branch.as_str()),
 623            LogSource::Sha(oid) => {
 624                str::from_utf8(oid.as_bytes()).context("Failed to build str from sha")
 625            }
 626        }
 627    }
 628}
 629
 630pub struct SearchCommitArgs {
 631    pub query: SharedString,
 632    pub case_sensitive: bool,
 633}
 634
 635pub trait GitRepository: Send + Sync {
 636    fn reload_index(&self);
 637
 638    /// Returns the contents of an entry in the repository's index, or None if there is no entry for the given path.
 639    ///
 640    /// Also returns `None` for symlinks.
 641    fn load_index_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>>;
 642
 643    /// 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.
 644    ///
 645    /// Also returns `None` for symlinks.
 646    fn load_committed_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>>;
 647    fn load_blob_content(&self, oid: Oid) -> BoxFuture<'_, Result<String>>;
 648
 649    fn set_index_text(
 650        &self,
 651        path: RepoPath,
 652        content: Option<String>,
 653        env: Arc<HashMap<String, String>>,
 654        is_executable: bool,
 655    ) -> BoxFuture<'_, anyhow::Result<()>>;
 656
 657    /// Returns the URL of the remote with the given name.
 658    fn remote_url(&self, name: &str) -> BoxFuture<'_, Option<String>>;
 659
 660    /// Resolve a list of refs to SHAs.
 661    fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<'_, Result<Vec<Option<String>>>>;
 662
 663    fn head_sha(&self) -> BoxFuture<'_, Option<String>> {
 664        async move {
 665            self.revparse_batch(vec!["HEAD".into()])
 666                .await
 667                .unwrap_or_default()
 668                .into_iter()
 669                .next()
 670                .flatten()
 671        }
 672        .boxed()
 673    }
 674
 675    fn merge_message(&self) -> BoxFuture<'_, Option<String>>;
 676
 677    fn status(&self, path_prefixes: &[RepoPath]) -> Task<Result<GitStatus>>;
 678    fn diff_tree(&self, request: DiffTreeType) -> BoxFuture<'_, Result<TreeDiff>>;
 679
 680    fn stash_entries(&self) -> BoxFuture<'_, Result<GitStash>>;
 681
 682    fn branches(&self) -> BoxFuture<'_, Result<Vec<Branch>>>;
 683
 684    fn change_branch(&self, name: String) -> BoxFuture<'_, Result<()>>;
 685    fn create_branch(&self, name: String, base_branch: Option<String>)
 686    -> BoxFuture<'_, Result<()>>;
 687    fn rename_branch(&self, branch: String, new_name: String) -> BoxFuture<'_, Result<()>>;
 688
 689    fn delete_branch(&self, is_remote: bool, name: String) -> BoxFuture<'_, Result<()>>;
 690
 691    fn worktrees(&self) -> BoxFuture<'_, Result<Vec<Worktree>>>;
 692
 693    fn create_worktree(
 694        &self,
 695        branch_name: String,
 696        path: PathBuf,
 697        from_commit: Option<String>,
 698    ) -> BoxFuture<'_, Result<()>>;
 699
 700    fn remove_worktree(&self, path: PathBuf, force: bool) -> BoxFuture<'_, Result<()>>;
 701
 702    fn rename_worktree(&self, old_path: PathBuf, new_path: PathBuf) -> BoxFuture<'_, Result<()>>;
 703
 704    fn reset(
 705        &self,
 706        commit: String,
 707        mode: ResetMode,
 708        env: Arc<HashMap<String, String>>,
 709    ) -> BoxFuture<'_, Result<()>>;
 710
 711    fn checkout_files(
 712        &self,
 713        commit: String,
 714        paths: Vec<RepoPath>,
 715        env: Arc<HashMap<String, String>>,
 716    ) -> BoxFuture<'_, Result<()>>;
 717
 718    fn show(&self, commit: String) -> BoxFuture<'_, Result<CommitDetails>>;
 719
 720    fn load_commit(&self, commit: String, cx: AsyncApp) -> BoxFuture<'_, Result<CommitDiff>>;
 721    fn blame(
 722        &self,
 723        path: RepoPath,
 724        content: Rope,
 725        line_ending: LineEnding,
 726    ) -> BoxFuture<'_, Result<crate::blame::Blame>>;
 727    fn file_history(&self, path: RepoPath) -> BoxFuture<'_, Result<FileHistory>>;
 728    fn file_history_paginated(
 729        &self,
 730        path: RepoPath,
 731        skip: usize,
 732        limit: Option<usize>,
 733    ) -> BoxFuture<'_, Result<FileHistory>>;
 734
 735    /// Returns the absolute path to the repository. For worktrees, this will be the path to the
 736    /// worktree's gitdir within the main repository (typically `.git/worktrees/<name>`).
 737    fn path(&self) -> PathBuf;
 738
 739    fn main_repository_path(&self) -> PathBuf;
 740
 741    /// Updates the index to match the worktree at the given paths.
 742    ///
 743    /// If any of the paths have been deleted from the worktree, they will be removed from the index if found there.
 744    fn stage_paths(
 745        &self,
 746        paths: Vec<RepoPath>,
 747        env: Arc<HashMap<String, String>>,
 748    ) -> BoxFuture<'_, Result<()>>;
 749    /// Updates the index to match HEAD at the given paths.
 750    ///
 751    /// If any of the paths were previously staged but do not exist in HEAD, they will be removed from the index.
 752    fn unstage_paths(
 753        &self,
 754        paths: Vec<RepoPath>,
 755        env: Arc<HashMap<String, String>>,
 756    ) -> BoxFuture<'_, Result<()>>;
 757
 758    fn run_hook(
 759        &self,
 760        hook: RunHook,
 761        env: Arc<HashMap<String, String>>,
 762    ) -> BoxFuture<'_, Result<()>>;
 763
 764    fn commit(
 765        &self,
 766        message: SharedString,
 767        name_and_email: Option<(SharedString, SharedString)>,
 768        options: CommitOptions,
 769        askpass: AskPassDelegate,
 770        env: Arc<HashMap<String, String>>,
 771    ) -> BoxFuture<'_, Result<()>>;
 772
 773    fn stash_paths(
 774        &self,
 775        paths: Vec<RepoPath>,
 776        env: Arc<HashMap<String, String>>,
 777    ) -> BoxFuture<'_, Result<()>>;
 778
 779    fn stash_pop(
 780        &self,
 781        index: Option<usize>,
 782        env: Arc<HashMap<String, String>>,
 783    ) -> BoxFuture<'_, Result<()>>;
 784
 785    fn stash_apply(
 786        &self,
 787        index: Option<usize>,
 788        env: Arc<HashMap<String, String>>,
 789    ) -> BoxFuture<'_, Result<()>>;
 790
 791    fn stash_drop(
 792        &self,
 793        index: Option<usize>,
 794        env: Arc<HashMap<String, String>>,
 795    ) -> BoxFuture<'_, Result<()>>;
 796
 797    fn push(
 798        &self,
 799        branch_name: String,
 800        remote_branch_name: String,
 801        upstream_name: String,
 802        options: Option<PushOptions>,
 803        askpass: AskPassDelegate,
 804        env: Arc<HashMap<String, String>>,
 805        // This method takes an AsyncApp to ensure it's invoked on the main thread,
 806        // otherwise git-credentials-manager won't work.
 807        cx: AsyncApp,
 808    ) -> BoxFuture<'_, Result<RemoteCommandOutput>>;
 809
 810    fn pull(
 811        &self,
 812        branch_name: Option<String>,
 813        upstream_name: String,
 814        rebase: bool,
 815        askpass: AskPassDelegate,
 816        env: Arc<HashMap<String, String>>,
 817        // This method takes an AsyncApp to ensure it's invoked on the main thread,
 818        // otherwise git-credentials-manager won't work.
 819        cx: AsyncApp,
 820    ) -> BoxFuture<'_, Result<RemoteCommandOutput>>;
 821
 822    fn fetch(
 823        &self,
 824        fetch_options: FetchOptions,
 825        askpass: AskPassDelegate,
 826        env: Arc<HashMap<String, String>>,
 827        // This method takes an AsyncApp to ensure it's invoked on the main thread,
 828        // otherwise git-credentials-manager won't work.
 829        cx: AsyncApp,
 830    ) -> BoxFuture<'_, Result<RemoteCommandOutput>>;
 831
 832    fn get_push_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>>;
 833
 834    fn get_branch_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>>;
 835
 836    fn get_all_remotes(&self) -> BoxFuture<'_, Result<Vec<Remote>>>;
 837
 838    fn remove_remote(&self, name: String) -> BoxFuture<'_, Result<()>>;
 839
 840    fn create_remote(&self, name: String, url: String) -> BoxFuture<'_, Result<()>>;
 841
 842    /// returns a list of remote branches that contain HEAD
 843    fn check_for_pushed_commit(&self) -> BoxFuture<'_, Result<Vec<SharedString>>>;
 844
 845    /// Run git diff
 846    fn diff(&self, diff: DiffType) -> BoxFuture<'_, Result<String>>;
 847
 848    fn diff_stat(
 849        &self,
 850        path_prefixes: &[RepoPath],
 851    ) -> BoxFuture<'_, Result<crate::status::GitDiffStat>>;
 852
 853    /// Creates a checkpoint for the repository.
 854    fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>>;
 855
 856    /// Resets to a previously-created checkpoint.
 857    fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>>;
 858
 859    /// Compares two checkpoints, returning true if they are equal
 860    fn compare_checkpoints(
 861        &self,
 862        left: GitRepositoryCheckpoint,
 863        right: GitRepositoryCheckpoint,
 864    ) -> BoxFuture<'_, Result<bool>>;
 865
 866    /// Computes a diff between two checkpoints.
 867    fn diff_checkpoints(
 868        &self,
 869        base_checkpoint: GitRepositoryCheckpoint,
 870        target_checkpoint: GitRepositoryCheckpoint,
 871    ) -> BoxFuture<'_, Result<String>>;
 872
 873    fn default_branch(
 874        &self,
 875        include_remote_name: bool,
 876    ) -> BoxFuture<'_, Result<Option<SharedString>>>;
 877
 878    /// Runs `git rev-list --parents` to get the commit graph structure.
 879    /// Returns commit SHAs and their parent SHAs for building the graph visualization.
 880    fn initial_graph_data(
 881        &self,
 882        log_source: LogSource,
 883        log_order: LogOrder,
 884        request_tx: Sender<Vec<Arc<InitialGraphCommitData>>>,
 885    ) -> BoxFuture<'_, Result<()>>;
 886
 887    fn search_commits(
 888        &self,
 889        log_source: LogSource,
 890        search_args: SearchCommitArgs,
 891        request_tx: Sender<Oid>,
 892    ) -> BoxFuture<'_, Result<()>>;
 893
 894    fn commit_data_reader(&self) -> Result<CommitDataReader>;
 895
 896    fn set_trusted(&self, trusted: bool);
 897    fn is_trusted(&self) -> bool;
 898}
 899
 900pub enum DiffType {
 901    HeadToIndex,
 902    HeadToWorktree,
 903    MergeBase { base_ref: SharedString },
 904}
 905
 906#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]
 907pub enum PushOptions {
 908    SetUpstream,
 909    Force,
 910}
 911
 912impl std::fmt::Debug for dyn GitRepository {
 913    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 914        f.debug_struct("dyn GitRepository<...>").finish()
 915    }
 916}
 917
 918pub struct RealGitRepository {
 919    pub repository: Arc<Mutex<git2::Repository>>,
 920    pub system_git_binary_path: Option<PathBuf>,
 921    pub any_git_binary_path: PathBuf,
 922    any_git_binary_help_output: Arc<Mutex<Option<SharedString>>>,
 923    executor: BackgroundExecutor,
 924    is_trusted: Arc<AtomicBool>,
 925}
 926
 927impl RealGitRepository {
 928    pub fn new(
 929        dotgit_path: &Path,
 930        bundled_git_binary_path: Option<PathBuf>,
 931        system_git_binary_path: Option<PathBuf>,
 932        executor: BackgroundExecutor,
 933    ) -> Result<Self> {
 934        let any_git_binary_path = system_git_binary_path
 935            .clone()
 936            .or(bundled_git_binary_path)
 937            .context("no git binary available")?;
 938        log::info!(
 939            "opening git repository at {dotgit_path:?} using git binary {any_git_binary_path:?}"
 940        );
 941        let workdir_root = dotgit_path.parent().context(".git has no parent")?;
 942        let repository =
 943            git2::Repository::open(workdir_root).context("creating libgit2 repository")?;
 944        Ok(Self {
 945            repository: Arc::new(Mutex::new(repository)),
 946            system_git_binary_path,
 947            any_git_binary_path,
 948            executor,
 949            any_git_binary_help_output: Arc::new(Mutex::new(None)),
 950            is_trusted: Arc::new(AtomicBool::new(false)),
 951        })
 952    }
 953
 954    fn working_directory(&self) -> Result<PathBuf> {
 955        self.repository
 956            .lock()
 957            .workdir()
 958            .context("failed to read git work directory")
 959            .map(Path::to_path_buf)
 960    }
 961
 962    fn git_binary(&self) -> Result<GitBinary> {
 963        Ok(GitBinary::new(
 964            self.any_git_binary_path.clone(),
 965            self.working_directory()
 966                .with_context(|| "Can't run git commands without a working directory")?,
 967            self.path(),
 968            self.executor.clone(),
 969            self.is_trusted(),
 970        ))
 971    }
 972
 973    async fn any_git_binary_help_output(&self) -> SharedString {
 974        if let Some(output) = self.any_git_binary_help_output.lock().clone() {
 975            return output;
 976        }
 977        let git_binary = self.git_binary();
 978        let output: SharedString = self
 979            .executor
 980            .spawn(async move { git_binary?.run(&["help", "-a"]).await })
 981            .await
 982            .unwrap_or_default()
 983            .into();
 984        *self.any_git_binary_help_output.lock() = Some(output.clone());
 985        output
 986    }
 987}
 988
 989#[derive(Clone, Debug)]
 990pub struct GitRepositoryCheckpoint {
 991    pub commit_sha: Oid,
 992}
 993
 994#[derive(Debug)]
 995pub struct GitCommitter {
 996    pub name: Option<String>,
 997    pub email: Option<String>,
 998}
 999
1000pub async fn get_git_committer(cx: &AsyncApp) -> GitCommitter {
1001    if cfg!(any(feature = "test-support", test)) {
1002        return GitCommitter {
1003            name: None,
1004            email: None,
1005        };
1006    }
1007
1008    let git_binary_path =
1009        if cfg!(target_os = "macos") && option_env!("ZED_BUNDLE").as_deref() == Some("true") {
1010            cx.update(|cx| {
1011                cx.path_for_auxiliary_executable("git")
1012                    .context("could not find git binary path")
1013                    .log_err()
1014            })
1015        } else {
1016            None
1017        };
1018
1019    let git = GitBinary::new(
1020        git_binary_path.unwrap_or(PathBuf::from("git")),
1021        paths::home_dir().clone(),
1022        paths::home_dir().join(".git"),
1023        cx.background_executor().clone(),
1024        true,
1025    );
1026
1027    cx.background_spawn(async move {
1028        let name = git
1029            .run(&["config", "--global", "user.name"])
1030            .await
1031            .log_err();
1032        let email = git
1033            .run(&["config", "--global", "user.email"])
1034            .await
1035            .log_err();
1036        GitCommitter { name, email }
1037    })
1038    .await
1039}
1040
1041impl GitRepository for RealGitRepository {
1042    fn reload_index(&self) {
1043        if let Ok(mut index) = self.repository.lock().index() {
1044            _ = index.read(false);
1045        }
1046    }
1047
1048    fn path(&self) -> PathBuf {
1049        let repo = self.repository.lock();
1050        repo.path().into()
1051    }
1052
1053    fn main_repository_path(&self) -> PathBuf {
1054        let repo = self.repository.lock();
1055        repo.commondir().into()
1056    }
1057
1058    fn show(&self, commit: String) -> BoxFuture<'_, Result<CommitDetails>> {
1059        let git_binary = self.git_binary();
1060        self.executor
1061            .spawn(async move {
1062                let git = git_binary?;
1063                let output = git
1064                    .build_command(&[
1065                        "show",
1066                        "--no-patch",
1067                        "--format=%H%x00%B%x00%at%x00%ae%x00%an%x00",
1068                        &commit,
1069                    ])
1070                    .output()
1071                    .await?;
1072                let output = std::str::from_utf8(&output.stdout)?;
1073                let fields = output.split('\0').collect::<Vec<_>>();
1074                if fields.len() != 6 {
1075                    bail!("unexpected git-show output for {commit:?}: {output:?}")
1076                }
1077                let sha = fields[0].to_string().into();
1078                let message = fields[1].to_string().into();
1079                let commit_timestamp = fields[2].parse()?;
1080                let author_email = fields[3].to_string().into();
1081                let author_name = fields[4].to_string().into();
1082                Ok(CommitDetails {
1083                    sha,
1084                    message,
1085                    commit_timestamp,
1086                    author_email,
1087                    author_name,
1088                })
1089            })
1090            .boxed()
1091    }
1092
1093    fn load_commit(&self, commit: String, cx: AsyncApp) -> BoxFuture<'_, Result<CommitDiff>> {
1094        if self.repository.lock().workdir().is_none() {
1095            return future::ready(Err(anyhow!("no working directory"))).boxed();
1096        }
1097        let git_binary = self.git_binary();
1098        cx.background_spawn(async move {
1099            let git = git_binary?;
1100            let show_output = git
1101                .build_command(&[
1102                    "show",
1103                    "--format=",
1104                    "-z",
1105                    "--no-renames",
1106                    "--name-status",
1107                    "--first-parent",
1108                ])
1109                .arg(&commit)
1110                .stdin(Stdio::null())
1111                .stdout(Stdio::piped())
1112                .stderr(Stdio::piped())
1113                .output()
1114                .await
1115                .context("starting git show process")?;
1116
1117            let show_stdout = String::from_utf8_lossy(&show_output.stdout);
1118            let changes = parse_git_diff_name_status(&show_stdout);
1119            let parent_sha = format!("{}^", commit);
1120
1121            let mut cat_file_process = git
1122                .build_command(&["cat-file", "--batch=%(objectsize)"])
1123                .stdin(Stdio::piped())
1124                .stdout(Stdio::piped())
1125                .stderr(Stdio::piped())
1126                .spawn()
1127                .context("starting git cat-file process")?;
1128
1129            let mut files = Vec::<CommitFile>::new();
1130            let mut stdin = BufWriter::with_capacity(512, cat_file_process.stdin.take().unwrap());
1131            let mut stdout = BufReader::new(cat_file_process.stdout.take().unwrap());
1132            let mut info_line = String::new();
1133            let mut newline = [b'\0'];
1134            for (path, status_code) in changes {
1135                // git-show outputs `/`-delimited paths even on Windows.
1136                let Some(rel_path) = RelPath::unix(path).log_err() else {
1137                    continue;
1138                };
1139
1140                match status_code {
1141                    StatusCode::Modified => {
1142                        stdin.write_all(commit.as_bytes()).await?;
1143                        stdin.write_all(b":").await?;
1144                        stdin.write_all(path.as_bytes()).await?;
1145                        stdin.write_all(b"\n").await?;
1146                        stdin.write_all(parent_sha.as_bytes()).await?;
1147                        stdin.write_all(b":").await?;
1148                        stdin.write_all(path.as_bytes()).await?;
1149                        stdin.write_all(b"\n").await?;
1150                    }
1151                    StatusCode::Added => {
1152                        stdin.write_all(commit.as_bytes()).await?;
1153                        stdin.write_all(b":").await?;
1154                        stdin.write_all(path.as_bytes()).await?;
1155                        stdin.write_all(b"\n").await?;
1156                    }
1157                    StatusCode::Deleted => {
1158                        stdin.write_all(parent_sha.as_bytes()).await?;
1159                        stdin.write_all(b":").await?;
1160                        stdin.write_all(path.as_bytes()).await?;
1161                        stdin.write_all(b"\n").await?;
1162                    }
1163                    _ => continue,
1164                }
1165                stdin.flush().await?;
1166
1167                info_line.clear();
1168                stdout.read_line(&mut info_line).await?;
1169
1170                let len = info_line.trim_end().parse().with_context(|| {
1171                    format!("invalid object size output from cat-file {info_line}")
1172                })?;
1173                let mut text_bytes = vec![0; len];
1174                stdout.read_exact(&mut text_bytes).await?;
1175                stdout.read_exact(&mut newline).await?;
1176
1177                let mut old_text = None;
1178                let mut new_text = None;
1179                let mut is_binary = is_binary_content(&text_bytes);
1180                let text = if is_binary {
1181                    String::new()
1182                } else {
1183                    String::from_utf8_lossy(&text_bytes).to_string()
1184                };
1185
1186                match status_code {
1187                    StatusCode::Modified => {
1188                        info_line.clear();
1189                        stdout.read_line(&mut info_line).await?;
1190                        let len = info_line.trim_end().parse().with_context(|| {
1191                            format!("invalid object size output from cat-file {}", info_line)
1192                        })?;
1193                        let mut parent_bytes = vec![0; len];
1194                        stdout.read_exact(&mut parent_bytes).await?;
1195                        stdout.read_exact(&mut newline).await?;
1196                        is_binary = is_binary || is_binary_content(&parent_bytes);
1197                        if is_binary {
1198                            old_text = Some(String::new());
1199                            new_text = Some(String::new());
1200                        } else {
1201                            old_text = Some(String::from_utf8_lossy(&parent_bytes).to_string());
1202                            new_text = Some(text);
1203                        }
1204                    }
1205                    StatusCode::Added => new_text = Some(text),
1206                    StatusCode::Deleted => old_text = Some(text),
1207                    _ => continue,
1208                }
1209
1210                files.push(CommitFile {
1211                    path: RepoPath(Arc::from(rel_path)),
1212                    old_text,
1213                    new_text,
1214                    is_binary,
1215                })
1216            }
1217
1218            Ok(CommitDiff { files })
1219        })
1220        .boxed()
1221    }
1222
1223    fn reset(
1224        &self,
1225        commit: String,
1226        mode: ResetMode,
1227        env: Arc<HashMap<String, String>>,
1228    ) -> BoxFuture<'_, Result<()>> {
1229        let git_binary = self.git_binary();
1230        async move {
1231            let mode_flag = match mode {
1232                ResetMode::Mixed => "--mixed",
1233                ResetMode::Soft => "--soft",
1234            };
1235
1236            let git = git_binary?;
1237            let output = git
1238                .build_command(&["reset", mode_flag, &commit])
1239                .envs(env.iter())
1240                .output()
1241                .await?;
1242            anyhow::ensure!(
1243                output.status.success(),
1244                "Failed to reset:\n{}",
1245                String::from_utf8_lossy(&output.stderr),
1246            );
1247            Ok(())
1248        }
1249        .boxed()
1250    }
1251
1252    fn checkout_files(
1253        &self,
1254        commit: String,
1255        paths: Vec<RepoPath>,
1256        env: Arc<HashMap<String, String>>,
1257    ) -> BoxFuture<'_, Result<()>> {
1258        let git_binary = self.git_binary();
1259        async move {
1260            if paths.is_empty() {
1261                return Ok(());
1262            }
1263
1264            let git = git_binary?;
1265            let output = git
1266                .build_command(&["checkout", &commit, "--"])
1267                .envs(env.iter())
1268                .args(paths.iter().map(|path| path.as_unix_str()))
1269                .output()
1270                .await?;
1271            anyhow::ensure!(
1272                output.status.success(),
1273                "Failed to checkout files:\n{}",
1274                String::from_utf8_lossy(&output.stderr),
1275            );
1276            Ok(())
1277        }
1278        .boxed()
1279    }
1280
1281    fn load_index_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>> {
1282        // https://git-scm.com/book/en/v2/Git-Internals-Git-Objects
1283        const GIT_MODE_SYMLINK: u32 = 0o120000;
1284
1285        let repo = self.repository.clone();
1286        self.executor
1287            .spawn(async move {
1288                fn logic(repo: &git2::Repository, path: &RepoPath) -> Result<Option<String>> {
1289                    let mut index = repo.index()?;
1290                    index.read(false)?;
1291
1292                    const STAGE_NORMAL: i32 = 0;
1293                    // git2 unwraps internally on empty paths or `.`
1294                    if path.is_empty() {
1295                        bail!("empty path has no index text");
1296                    }
1297                    let Some(entry) = index.get_path(path.as_std_path(), STAGE_NORMAL) else {
1298                        return Ok(None);
1299                    };
1300                    if entry.mode == GIT_MODE_SYMLINK {
1301                        return Ok(None);
1302                    }
1303
1304                    let content = repo.find_blob(entry.id)?.content().to_owned();
1305                    Ok(String::from_utf8(content).ok())
1306                }
1307
1308                logic(&repo.lock(), &path)
1309                    .context("loading index text")
1310                    .log_err()
1311                    .flatten()
1312            })
1313            .boxed()
1314    }
1315
1316    fn load_committed_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>> {
1317        let repo = self.repository.clone();
1318        self.executor
1319            .spawn(async move {
1320                fn logic(repo: &git2::Repository, path: &RepoPath) -> Result<Option<String>> {
1321                    let head = repo.head()?.peel_to_tree()?;
1322                    // git2 unwraps internally on empty paths or `.`
1323                    if path.is_empty() {
1324                        return Err(anyhow!("empty path has no committed text"));
1325                    }
1326                    let Some(entry) = head.get_path(path.as_std_path()).ok() else {
1327                        return Ok(None);
1328                    };
1329                    if entry.filemode() == i32::from(git2::FileMode::Link) {
1330                        return Ok(None);
1331                    }
1332                    let content = repo.find_blob(entry.id())?.content().to_owned();
1333                    Ok(String::from_utf8(content).ok())
1334                }
1335
1336                logic(&repo.lock(), &path)
1337                    .context("loading committed text")
1338                    .log_err()
1339                    .flatten()
1340            })
1341            .boxed()
1342    }
1343
1344    fn load_blob_content(&self, oid: Oid) -> BoxFuture<'_, Result<String>> {
1345        let repo = self.repository.clone();
1346        self.executor
1347            .spawn(async move {
1348                let repo = repo.lock();
1349                let content = repo.find_blob(oid.0)?.content().to_owned();
1350                Ok(String::from_utf8(content)?)
1351            })
1352            .boxed()
1353    }
1354
1355    fn set_index_text(
1356        &self,
1357        path: RepoPath,
1358        content: Option<String>,
1359        env: Arc<HashMap<String, String>>,
1360        is_executable: bool,
1361    ) -> BoxFuture<'_, anyhow::Result<()>> {
1362        let git_binary = self.git_binary();
1363        self.executor
1364            .spawn(async move {
1365                let git = git_binary?;
1366                let mode = if is_executable { "100755" } else { "100644" };
1367
1368                if let Some(content) = content {
1369                    let mut child = git
1370                        .build_command(&["hash-object", "-w", "--stdin"])
1371                        .envs(env.iter())
1372                        .stdin(Stdio::piped())
1373                        .stdout(Stdio::piped())
1374                        .spawn()?;
1375                    let mut stdin = child.stdin.take().unwrap();
1376                    stdin.write_all(content.as_bytes()).await?;
1377                    stdin.flush().await?;
1378                    drop(stdin);
1379                    let output = child.output().await?.stdout;
1380                    let sha = str::from_utf8(&output)?.trim();
1381
1382                    log::debug!("indexing SHA: {sha}, path {path:?}");
1383
1384                    let output = git
1385                        .build_command(&["update-index", "--add", "--cacheinfo", mode, sha])
1386                        .envs(env.iter())
1387                        .arg(path.as_unix_str())
1388                        .output()
1389                        .await?;
1390
1391                    anyhow::ensure!(
1392                        output.status.success(),
1393                        "Failed to stage:\n{}",
1394                        String::from_utf8_lossy(&output.stderr)
1395                    );
1396                } else {
1397                    log::debug!("removing path {path:?} from the index");
1398                    let output = git
1399                        .build_command(&["update-index", "--force-remove"])
1400                        .envs(env.iter())
1401                        .arg(path.as_unix_str())
1402                        .output()
1403                        .await?;
1404                    anyhow::ensure!(
1405                        output.status.success(),
1406                        "Failed to unstage:\n{}",
1407                        String::from_utf8_lossy(&output.stderr)
1408                    );
1409                }
1410
1411                Ok(())
1412            })
1413            .boxed()
1414    }
1415
1416    fn remote_url(&self, name: &str) -> BoxFuture<'_, Option<String>> {
1417        let repo = self.repository.clone();
1418        let name = name.to_owned();
1419        self.executor
1420            .spawn(async move {
1421                let repo = repo.lock();
1422                let remote = repo.find_remote(&name).ok()?;
1423                remote.url().map(|url| url.to_string())
1424            })
1425            .boxed()
1426    }
1427
1428    fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<'_, Result<Vec<Option<String>>>> {
1429        let git_binary = self.git_binary();
1430        self.executor
1431            .spawn(async move {
1432                let git = git_binary?;
1433                let mut process = git
1434                    .build_command(&["cat-file", "--batch-check=%(objectname)"])
1435                    .stdin(Stdio::piped())
1436                    .stdout(Stdio::piped())
1437                    .stderr(Stdio::piped())
1438                    .spawn()?;
1439
1440                let stdin = process
1441                    .stdin
1442                    .take()
1443                    .context("no stdin for git cat-file subprocess")?;
1444                let mut stdin = BufWriter::new(stdin);
1445                for rev in &revs {
1446                    stdin.write_all(rev.as_bytes()).await?;
1447                    stdin.write_all(b"\n").await?;
1448                }
1449                stdin.flush().await?;
1450                drop(stdin);
1451
1452                let output = process.output().await?;
1453                let output = std::str::from_utf8(&output.stdout)?;
1454                let shas = output
1455                    .lines()
1456                    .map(|line| {
1457                        if line.ends_with("missing") {
1458                            None
1459                        } else {
1460                            Some(line.to_string())
1461                        }
1462                    })
1463                    .collect::<Vec<_>>();
1464
1465                if shas.len() != revs.len() {
1466                    // In an octopus merge, git cat-file still only outputs the first sha from MERGE_HEAD.
1467                    bail!("unexpected number of shas")
1468                }
1469
1470                Ok(shas)
1471            })
1472            .boxed()
1473    }
1474
1475    fn merge_message(&self) -> BoxFuture<'_, Option<String>> {
1476        let path = self.path().join("MERGE_MSG");
1477        self.executor
1478            .spawn(async move { std::fs::read_to_string(&path).ok() })
1479            .boxed()
1480    }
1481
1482    fn status(&self, path_prefixes: &[RepoPath]) -> Task<Result<GitStatus>> {
1483        let git = match self.git_binary() {
1484            Ok(git) => git,
1485            Err(e) => return Task::ready(Err(e)),
1486        };
1487        let args = git_status_args(path_prefixes);
1488        log::debug!("Checking for git status in {path_prefixes:?}");
1489        self.executor.spawn(async move {
1490            let output = git.build_command(&args).output().await?;
1491            if output.status.success() {
1492                let stdout = String::from_utf8_lossy(&output.stdout);
1493                stdout.parse()
1494            } else {
1495                let stderr = String::from_utf8_lossy(&output.stderr);
1496                anyhow::bail!("git status failed: {stderr}");
1497            }
1498        })
1499    }
1500
1501    fn diff_tree(&self, request: DiffTreeType) -> BoxFuture<'_, Result<TreeDiff>> {
1502        let git = match self.git_binary() {
1503            Ok(git) => git,
1504            Err(e) => return Task::ready(Err(e)).boxed(),
1505        };
1506
1507        let mut args = vec![
1508            OsString::from("diff-tree"),
1509            OsString::from("-r"),
1510            OsString::from("-z"),
1511            OsString::from("--no-renames"),
1512        ];
1513        match request {
1514            DiffTreeType::MergeBase { base, head } => {
1515                args.push("--merge-base".into());
1516                args.push(OsString::from(base.as_str()));
1517                args.push(OsString::from(head.as_str()));
1518            }
1519            DiffTreeType::Since { base, head } => {
1520                args.push(OsString::from(base.as_str()));
1521                args.push(OsString::from(head.as_str()));
1522            }
1523        }
1524
1525        self.executor
1526            .spawn(async move {
1527                let output = git.build_command(&args).output().await?;
1528                if output.status.success() {
1529                    let stdout = String::from_utf8_lossy(&output.stdout);
1530                    stdout.parse()
1531                } else {
1532                    let stderr = String::from_utf8_lossy(&output.stderr);
1533                    anyhow::bail!("git status failed: {stderr}");
1534                }
1535            })
1536            .boxed()
1537    }
1538
1539    fn stash_entries(&self) -> BoxFuture<'_, Result<GitStash>> {
1540        let git_binary = self.git_binary();
1541        self.executor
1542            .spawn(async move {
1543                let git = git_binary?;
1544                let output = git
1545                    .build_command(&["stash", "list", "--pretty=format:%gd%x00%H%x00%ct%x00%s"])
1546                    .output()
1547                    .await?;
1548                if output.status.success() {
1549                    let stdout = String::from_utf8_lossy(&output.stdout);
1550                    stdout.parse()
1551                } else {
1552                    let stderr = String::from_utf8_lossy(&output.stderr);
1553                    anyhow::bail!("git status failed: {stderr}");
1554                }
1555            })
1556            .boxed()
1557    }
1558
1559    fn branches(&self) -> BoxFuture<'_, Result<Vec<Branch>>> {
1560        let git_binary = self.git_binary();
1561        self.executor
1562            .spawn(async move {
1563                let fields = [
1564                    "%(HEAD)",
1565                    "%(objectname)",
1566                    "%(parent)",
1567                    "%(refname)",
1568                    "%(upstream)",
1569                    "%(upstream:track)",
1570                    "%(committerdate:unix)",
1571                    "%(authorname)",
1572                    "%(contents:subject)",
1573                ]
1574                .join("%00");
1575                let args = vec![
1576                    "for-each-ref",
1577                    "refs/heads/**/*",
1578                    "refs/remotes/**/*",
1579                    "--format",
1580                    &fields,
1581                ];
1582                let git = git_binary?;
1583                let output = git.build_command(&args).output().await?;
1584
1585                anyhow::ensure!(
1586                    output.status.success(),
1587                    "Failed to git git branches:\n{}",
1588                    String::from_utf8_lossy(&output.stderr)
1589                );
1590
1591                let input = String::from_utf8_lossy(&output.stdout);
1592
1593                let mut branches = parse_branch_input(&input)?;
1594                if branches.is_empty() {
1595                    let args = vec!["symbolic-ref", "--quiet", "HEAD"];
1596
1597                    let output = git.build_command(&args).output().await?;
1598
1599                    // git symbolic-ref returns a non-0 exit code if HEAD points
1600                    // to something other than a branch
1601                    if output.status.success() {
1602                        let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
1603
1604                        branches.push(Branch {
1605                            ref_name: name.into(),
1606                            is_head: true,
1607                            upstream: None,
1608                            most_recent_commit: None,
1609                        });
1610                    }
1611                }
1612
1613                Ok(branches)
1614            })
1615            .boxed()
1616    }
1617
1618    fn worktrees(&self) -> BoxFuture<'_, Result<Vec<Worktree>>> {
1619        let git_binary = self.git_binary();
1620        self.executor
1621            .spawn(async move {
1622                let git = git_binary?;
1623                let output = git
1624                    .build_command(&["worktree", "list", "--porcelain"])
1625                    .output()
1626                    .await?;
1627                if output.status.success() {
1628                    let stdout = String::from_utf8_lossy(&output.stdout);
1629                    Ok(parse_worktrees_from_str(&stdout))
1630                } else {
1631                    let stderr = String::from_utf8_lossy(&output.stderr);
1632                    anyhow::bail!("git worktree list failed: {stderr}");
1633                }
1634            })
1635            .boxed()
1636    }
1637
1638    fn create_worktree(
1639        &self,
1640        branch_name: String,
1641        path: PathBuf,
1642        from_commit: Option<String>,
1643    ) -> BoxFuture<'_, Result<()>> {
1644        let git_binary = self.git_binary();
1645        let mut args = vec![
1646            OsString::from("worktree"),
1647            OsString::from("add"),
1648            OsString::from("-b"),
1649            OsString::from(branch_name.as_str()),
1650            OsString::from("--"),
1651            OsString::from(path.as_os_str()),
1652        ];
1653        if let Some(from_commit) = from_commit {
1654            args.push(OsString::from(from_commit));
1655        } else {
1656            args.push(OsString::from("HEAD"));
1657        }
1658
1659        self.executor
1660            .spawn(async move {
1661                std::fs::create_dir_all(path.parent().unwrap_or(&path))?;
1662                let git = git_binary?;
1663                let mut command = git.build_command(&args);
1664                command.kill_on_drop(true);
1665                let output = command.output().await?;
1666                if output.status.success() {
1667                    Ok(())
1668                } else {
1669                    let stderr = String::from_utf8_lossy(&output.stderr);
1670                    anyhow::bail!("git worktree add failed: {stderr}");
1671                }
1672            })
1673            .boxed()
1674    }
1675
1676    fn remove_worktree(&self, path: PathBuf, force: bool) -> BoxFuture<'_, Result<()>> {
1677        let git_binary = self.git_binary();
1678
1679        self.executor
1680            .spawn(async move {
1681                let mut args: Vec<OsString> = vec!["worktree".into(), "remove".into()];
1682                if force {
1683                    args.push("--force".into());
1684                }
1685                args.push("--".into());
1686                args.push(path.as_os_str().into());
1687                git_binary?.run(&args).await?;
1688                anyhow::Ok(())
1689            })
1690            .boxed()
1691    }
1692
1693    fn rename_worktree(&self, old_path: PathBuf, new_path: PathBuf) -> BoxFuture<'_, Result<()>> {
1694        let git_binary = self.git_binary();
1695
1696        self.executor
1697            .spawn(async move {
1698                let args: Vec<OsString> = vec![
1699                    "worktree".into(),
1700                    "move".into(),
1701                    "--".into(),
1702                    old_path.as_os_str().into(),
1703                    new_path.as_os_str().into(),
1704                ];
1705                git_binary?.run(&args).await?;
1706                anyhow::Ok(())
1707            })
1708            .boxed()
1709    }
1710
1711    fn change_branch(&self, name: String) -> BoxFuture<'_, Result<()>> {
1712        let repo = self.repository.clone();
1713        let git_binary = self.git_binary();
1714        let branch = self.executor.spawn(async move {
1715            let repo = repo.lock();
1716            let branch = if let Ok(branch) = repo.find_branch(&name, BranchType::Local) {
1717                branch
1718            } else if let Ok(revision) = repo.find_branch(&name, BranchType::Remote) {
1719                let (_, branch_name) = name.split_once("/").context("Unexpected branch format")?;
1720
1721                let revision = revision.get();
1722                let branch_commit = revision.peel_to_commit()?;
1723                let mut branch = match repo.branch(&branch_name, &branch_commit, false) {
1724                    Ok(branch) => branch,
1725                    Err(err) if err.code() == ErrorCode::Exists => {
1726                        repo.find_branch(&branch_name, BranchType::Local)?
1727                    }
1728                    Err(err) => {
1729                        return Err(err.into());
1730                    }
1731                };
1732
1733                branch.set_upstream(Some(&name))?;
1734                branch
1735            } else {
1736                anyhow::bail!("Branch '{}' not found", name);
1737            };
1738
1739            Ok(branch
1740                .name()?
1741                .context("cannot checkout anonymous branch")?
1742                .to_string())
1743        });
1744
1745        self.executor
1746            .spawn(async move {
1747                let branch = branch.await?;
1748                git_binary?.run(&["checkout", &branch]).await?;
1749                anyhow::Ok(())
1750            })
1751            .boxed()
1752    }
1753
1754    fn create_branch(
1755        &self,
1756        name: String,
1757        base_branch: Option<String>,
1758    ) -> BoxFuture<'_, Result<()>> {
1759        let git_binary = self.git_binary();
1760
1761        self.executor
1762            .spawn(async move {
1763                let mut args = vec!["switch", "-c", &name];
1764                let base_branch_str;
1765                if let Some(ref base) = base_branch {
1766                    base_branch_str = base.clone();
1767                    args.push(&base_branch_str);
1768                }
1769
1770                git_binary?.run(&args).await?;
1771                anyhow::Ok(())
1772            })
1773            .boxed()
1774    }
1775
1776    fn rename_branch(&self, branch: String, new_name: String) -> BoxFuture<'_, Result<()>> {
1777        let git_binary = self.git_binary();
1778
1779        self.executor
1780            .spawn(async move {
1781                git_binary?
1782                    .run(&["branch", "-m", &branch, &new_name])
1783                    .await?;
1784                anyhow::Ok(())
1785            })
1786            .boxed()
1787    }
1788
1789    fn delete_branch(&self, is_remote: bool, name: String) -> BoxFuture<'_, Result<()>> {
1790        let git_binary = self.git_binary();
1791
1792        self.executor
1793            .spawn(async move {
1794                git_binary?
1795                    .run(&["branch", if is_remote { "-dr" } else { "-d" }, &name])
1796                    .await?;
1797                anyhow::Ok(())
1798            })
1799            .boxed()
1800    }
1801
1802    fn blame(
1803        &self,
1804        path: RepoPath,
1805        content: Rope,
1806        line_ending: LineEnding,
1807    ) -> BoxFuture<'_, Result<crate::blame::Blame>> {
1808        let git = self.git_binary();
1809
1810        self.executor
1811            .spawn(async move {
1812                crate::blame::Blame::for_path(&git?, &path, &content, line_ending).await
1813            })
1814            .boxed()
1815    }
1816
1817    fn file_history(&self, path: RepoPath) -> BoxFuture<'_, Result<FileHistory>> {
1818        self.file_history_paginated(path, 0, None)
1819    }
1820
1821    fn file_history_paginated(
1822        &self,
1823        path: RepoPath,
1824        skip: usize,
1825        limit: Option<usize>,
1826    ) -> BoxFuture<'_, Result<FileHistory>> {
1827        let git_binary = self.git_binary();
1828        self.executor
1829            .spawn(async move {
1830                let git = git_binary?;
1831                // Use a unique delimiter with a hardcoded UUID to separate commits
1832                // This essentially eliminates any chance of encountering the delimiter in actual commit data
1833                let commit_delimiter =
1834                    concat!("<<COMMIT_END-", "3f8a9c2e-7d4b-4e1a-9f6c-8b5d2a1e4c3f>>",);
1835
1836                let format_string = format!(
1837                    "--pretty=format:%H%x00%s%x00%B%x00%at%x00%an%x00%ae{}",
1838                    commit_delimiter
1839                );
1840
1841                let mut args = vec!["log", "--follow", &format_string];
1842
1843                let skip_str;
1844                let limit_str;
1845                if skip > 0 {
1846                    skip_str = skip.to_string();
1847                    args.push("--skip");
1848                    args.push(&skip_str);
1849                }
1850                if let Some(n) = limit {
1851                    limit_str = n.to_string();
1852                    args.push("-n");
1853                    args.push(&limit_str);
1854                }
1855
1856                args.push("--");
1857
1858                let output = git
1859                    .build_command(&args)
1860                    .arg(path.as_unix_str())
1861                    .output()
1862                    .await?;
1863
1864                if !output.status.success() {
1865                    let stderr = String::from_utf8_lossy(&output.stderr);
1866                    bail!("git log failed: {stderr}");
1867                }
1868
1869                let stdout = std::str::from_utf8(&output.stdout)?;
1870                let mut entries = Vec::new();
1871
1872                for commit_block in stdout.split(commit_delimiter) {
1873                    let commit_block = commit_block.trim();
1874                    if commit_block.is_empty() {
1875                        continue;
1876                    }
1877
1878                    let fields: Vec<&str> = commit_block.split('\0').collect();
1879                    if fields.len() >= 6 {
1880                        let sha = fields[0].trim().to_string().into();
1881                        let subject = fields[1].trim().to_string().into();
1882                        let message = fields[2].trim().to_string().into();
1883                        let commit_timestamp = fields[3].trim().parse().unwrap_or(0);
1884                        let author_name = fields[4].trim().to_string().into();
1885                        let author_email = fields[5].trim().to_string().into();
1886
1887                        entries.push(FileHistoryEntry {
1888                            sha,
1889                            subject,
1890                            message,
1891                            commit_timestamp,
1892                            author_name,
1893                            author_email,
1894                        });
1895                    }
1896                }
1897
1898                Ok(FileHistory { entries, path })
1899            })
1900            .boxed()
1901    }
1902
1903    fn diff(&self, diff: DiffType) -> BoxFuture<'_, Result<String>> {
1904        let git_binary = self.git_binary();
1905        self.executor
1906            .spawn(async move {
1907                let git = git_binary?;
1908                let output = match diff {
1909                    DiffType::HeadToIndex => {
1910                        git.build_command(&["diff", "--staged"]).output().await?
1911                    }
1912                    DiffType::HeadToWorktree => git.build_command(&["diff"]).output().await?,
1913                    DiffType::MergeBase { base_ref } => {
1914                        git.build_command(&["diff", "--merge-base", base_ref.as_ref()])
1915                            .output()
1916                            .await?
1917                    }
1918                };
1919
1920                anyhow::ensure!(
1921                    output.status.success(),
1922                    "Failed to run git diff:\n{}",
1923                    String::from_utf8_lossy(&output.stderr)
1924                );
1925                Ok(String::from_utf8_lossy(&output.stdout).to_string())
1926            })
1927            .boxed()
1928    }
1929
1930    fn diff_stat(
1931        &self,
1932        path_prefixes: &[RepoPath],
1933    ) -> BoxFuture<'_, Result<crate::status::GitDiffStat>> {
1934        let path_prefixes = path_prefixes.to_vec();
1935        let git_binary = self.git_binary();
1936
1937        self.executor
1938            .spawn(async move {
1939                let git_binary = git_binary?;
1940                let mut args: Vec<String> = vec![
1941                    "diff".into(),
1942                    "--numstat".into(),
1943                    "--no-renames".into(),
1944                    "HEAD".into(),
1945                ];
1946                if !path_prefixes.is_empty() {
1947                    args.push("--".into());
1948                    args.extend(
1949                        path_prefixes
1950                            .iter()
1951                            .map(|p| p.as_std_path().to_string_lossy().into_owned()),
1952                    );
1953                }
1954                let output = git_binary.run(&args).await?;
1955                Ok(crate::status::parse_numstat(&output))
1956            })
1957            .boxed()
1958    }
1959
1960    fn stage_paths(
1961        &self,
1962        paths: Vec<RepoPath>,
1963        env: Arc<HashMap<String, String>>,
1964    ) -> BoxFuture<'_, Result<()>> {
1965        let git_binary = self.git_binary();
1966        self.executor
1967            .spawn(async move {
1968                if !paths.is_empty() {
1969                    let git = git_binary?;
1970                    let output = git
1971                        .build_command(&["update-index", "--add", "--remove", "--"])
1972                        .envs(env.iter())
1973                        .args(paths.iter().map(|p| p.as_unix_str()))
1974                        .output()
1975                        .await?;
1976                    anyhow::ensure!(
1977                        output.status.success(),
1978                        "Failed to stage paths:\n{}",
1979                        String::from_utf8_lossy(&output.stderr),
1980                    );
1981                }
1982                Ok(())
1983            })
1984            .boxed()
1985    }
1986
1987    fn unstage_paths(
1988        &self,
1989        paths: Vec<RepoPath>,
1990        env: Arc<HashMap<String, String>>,
1991    ) -> BoxFuture<'_, Result<()>> {
1992        let git_binary = self.git_binary();
1993
1994        self.executor
1995            .spawn(async move {
1996                if !paths.is_empty() {
1997                    let git = git_binary?;
1998                    let output = git
1999                        .build_command(&["reset", "--quiet", "--"])
2000                        .envs(env.iter())
2001                        .args(paths.iter().map(|p| p.as_std_path()))
2002                        .output()
2003                        .await?;
2004
2005                    anyhow::ensure!(
2006                        output.status.success(),
2007                        "Failed to unstage:\n{}",
2008                        String::from_utf8_lossy(&output.stderr),
2009                    );
2010                }
2011                Ok(())
2012            })
2013            .boxed()
2014    }
2015
2016    fn stash_paths(
2017        &self,
2018        paths: Vec<RepoPath>,
2019        env: Arc<HashMap<String, String>>,
2020    ) -> BoxFuture<'_, Result<()>> {
2021        let git_binary = self.git_binary();
2022        self.executor
2023            .spawn(async move {
2024                let git = git_binary?;
2025                let output = git
2026                    .build_command(&["stash", "push", "--quiet", "--include-untracked"])
2027                    .envs(env.iter())
2028                    .args(paths.iter().map(|p| p.as_unix_str()))
2029                    .output()
2030                    .await?;
2031
2032                anyhow::ensure!(
2033                    output.status.success(),
2034                    "Failed to stash:\n{}",
2035                    String::from_utf8_lossy(&output.stderr)
2036                );
2037                Ok(())
2038            })
2039            .boxed()
2040    }
2041
2042    fn stash_pop(
2043        &self,
2044        index: Option<usize>,
2045        env: Arc<HashMap<String, String>>,
2046    ) -> BoxFuture<'_, Result<()>> {
2047        let git_binary = self.git_binary();
2048        self.executor
2049            .spawn(async move {
2050                let git = git_binary?;
2051                let mut args = vec!["stash".to_string(), "pop".to_string()];
2052                if let Some(index) = index {
2053                    args.push(format!("stash@{{{}}}", index));
2054                }
2055                let output = git.build_command(&args).envs(env.iter()).output().await?;
2056
2057                anyhow::ensure!(
2058                    output.status.success(),
2059                    "Failed to stash pop:\n{}",
2060                    String::from_utf8_lossy(&output.stderr)
2061                );
2062                Ok(())
2063            })
2064            .boxed()
2065    }
2066
2067    fn stash_apply(
2068        &self,
2069        index: Option<usize>,
2070        env: Arc<HashMap<String, String>>,
2071    ) -> BoxFuture<'_, Result<()>> {
2072        let git_binary = self.git_binary();
2073        self.executor
2074            .spawn(async move {
2075                let git = git_binary?;
2076                let mut args = vec!["stash".to_string(), "apply".to_string()];
2077                if let Some(index) = index {
2078                    args.push(format!("stash@{{{}}}", index));
2079                }
2080                let output = git.build_command(&args).envs(env.iter()).output().await?;
2081
2082                anyhow::ensure!(
2083                    output.status.success(),
2084                    "Failed to apply stash:\n{}",
2085                    String::from_utf8_lossy(&output.stderr)
2086                );
2087                Ok(())
2088            })
2089            .boxed()
2090    }
2091
2092    fn stash_drop(
2093        &self,
2094        index: Option<usize>,
2095        env: Arc<HashMap<String, String>>,
2096    ) -> BoxFuture<'_, Result<()>> {
2097        let git_binary = self.git_binary();
2098        self.executor
2099            .spawn(async move {
2100                let git = git_binary?;
2101                let mut args = vec!["stash".to_string(), "drop".to_string()];
2102                if let Some(index) = index {
2103                    args.push(format!("stash@{{{}}}", index));
2104                }
2105                let output = git.build_command(&args).envs(env.iter()).output().await?;
2106
2107                anyhow::ensure!(
2108                    output.status.success(),
2109                    "Failed to stash drop:\n{}",
2110                    String::from_utf8_lossy(&output.stderr)
2111                );
2112                Ok(())
2113            })
2114            .boxed()
2115    }
2116
2117    fn commit(
2118        &self,
2119        message: SharedString,
2120        name_and_email: Option<(SharedString, SharedString)>,
2121        options: CommitOptions,
2122        ask_pass: AskPassDelegate,
2123        env: Arc<HashMap<String, String>>,
2124    ) -> BoxFuture<'_, Result<()>> {
2125        let git_binary = self.git_binary();
2126        let executor = self.executor.clone();
2127        // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2128        // which we want to block on.
2129        async move {
2130            let git = git_binary?;
2131            let mut cmd = git.build_command(&["commit", "--quiet", "-m"]);
2132            cmd.envs(env.iter())
2133                .arg(&message.to_string())
2134                .arg("--cleanup=strip")
2135                .arg("--no-verify")
2136                .stdout(Stdio::piped())
2137                .stderr(Stdio::piped());
2138
2139            if options.amend {
2140                cmd.arg("--amend");
2141            }
2142
2143            if options.signoff {
2144                cmd.arg("--signoff");
2145            }
2146
2147            if let Some((name, email)) = name_and_email {
2148                cmd.arg("--author").arg(&format!("{name} <{email}>"));
2149            }
2150
2151            run_git_command(env, ask_pass, cmd, executor).await?;
2152
2153            Ok(())
2154        }
2155        .boxed()
2156    }
2157
2158    fn push(
2159        &self,
2160        branch_name: String,
2161        remote_branch_name: String,
2162        remote_name: String,
2163        options: Option<PushOptions>,
2164        ask_pass: AskPassDelegate,
2165        env: Arc<HashMap<String, String>>,
2166        cx: AsyncApp,
2167    ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
2168        let working_directory = self.working_directory();
2169        let git_directory = self.path();
2170        let executor = cx.background_executor().clone();
2171        let git_binary_path = self.system_git_binary_path.clone();
2172        let is_trusted = self.is_trusted();
2173        // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2174        // which we want to block on.
2175        async move {
2176            let git_binary_path = git_binary_path.context("git not found on $PATH, can't push")?;
2177            let working_directory = working_directory?;
2178            let git = GitBinary::new(
2179                git_binary_path,
2180                working_directory,
2181                git_directory,
2182                executor.clone(),
2183                is_trusted,
2184            );
2185            let mut command = git.build_command(&["push"]);
2186            command
2187                .envs(env.iter())
2188                .args(options.map(|option| match option {
2189                    PushOptions::SetUpstream => "--set-upstream",
2190                    PushOptions::Force => "--force-with-lease",
2191                }))
2192                .arg(remote_name)
2193                .arg(format!("{}:{}", branch_name, remote_branch_name))
2194                .stdin(Stdio::null())
2195                .stdout(Stdio::piped())
2196                .stderr(Stdio::piped());
2197
2198            run_git_command(env, ask_pass, command, executor).await
2199        }
2200        .boxed()
2201    }
2202
2203    fn pull(
2204        &self,
2205        branch_name: Option<String>,
2206        remote_name: String,
2207        rebase: bool,
2208        ask_pass: AskPassDelegate,
2209        env: Arc<HashMap<String, String>>,
2210        cx: AsyncApp,
2211    ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
2212        let working_directory = self.working_directory();
2213        let git_directory = self.path();
2214        let executor = cx.background_executor().clone();
2215        let git_binary_path = self.system_git_binary_path.clone();
2216        let is_trusted = self.is_trusted();
2217        // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2218        // which we want to block on.
2219        async move {
2220            let git_binary_path = git_binary_path.context("git not found on $PATH, can't pull")?;
2221            let working_directory = working_directory?;
2222            let git = GitBinary::new(
2223                git_binary_path,
2224                working_directory,
2225                git_directory,
2226                executor.clone(),
2227                is_trusted,
2228            );
2229            let mut command = git.build_command(&["pull"]);
2230            command.envs(env.iter());
2231
2232            if rebase {
2233                command.arg("--rebase");
2234            }
2235
2236            command
2237                .arg(remote_name)
2238                .args(branch_name)
2239                .stdout(Stdio::piped())
2240                .stderr(Stdio::piped());
2241
2242            run_git_command(env, ask_pass, command, executor).await
2243        }
2244        .boxed()
2245    }
2246
2247    fn fetch(
2248        &self,
2249        fetch_options: FetchOptions,
2250        ask_pass: AskPassDelegate,
2251        env: Arc<HashMap<String, String>>,
2252        cx: AsyncApp,
2253    ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
2254        let working_directory = self.working_directory();
2255        let git_directory = self.path();
2256        let remote_name = format!("{}", fetch_options);
2257        let git_binary_path = self.system_git_binary_path.clone();
2258        let executor = cx.background_executor().clone();
2259        let is_trusted = self.is_trusted();
2260        // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2261        // which we want to block on.
2262        async move {
2263            let git_binary_path = git_binary_path.context("git not found on $PATH, can't fetch")?;
2264            let working_directory = working_directory?;
2265            let git = GitBinary::new(
2266                git_binary_path,
2267                working_directory,
2268                git_directory,
2269                executor.clone(),
2270                is_trusted,
2271            );
2272            let mut command = git.build_command(&["fetch", &remote_name]);
2273            command
2274                .envs(env.iter())
2275                .stdout(Stdio::piped())
2276                .stderr(Stdio::piped());
2277
2278            run_git_command(env, ask_pass, command, executor).await
2279        }
2280        .boxed()
2281    }
2282
2283    fn get_push_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
2284        let git_binary = self.git_binary();
2285        self.executor
2286            .spawn(async move {
2287                let git = git_binary?;
2288                let output = git
2289                    .build_command(&["rev-parse", "--abbrev-ref"])
2290                    .arg(format!("{branch}@{{push}}"))
2291                    .output()
2292                    .await?;
2293                if !output.status.success() {
2294                    return Ok(None);
2295                }
2296                let remote_name = String::from_utf8_lossy(&output.stdout)
2297                    .split('/')
2298                    .next()
2299                    .map(|name| Remote {
2300                        name: name.trim().to_string().into(),
2301                    });
2302
2303                Ok(remote_name)
2304            })
2305            .boxed()
2306    }
2307
2308    fn get_branch_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
2309        let git_binary = self.git_binary();
2310        self.executor
2311            .spawn(async move {
2312                let git = git_binary?;
2313                let output = git
2314                    .build_command(&["config", "--get"])
2315                    .arg(format!("branch.{branch}.remote"))
2316                    .output()
2317                    .await?;
2318                if !output.status.success() {
2319                    return Ok(None);
2320                }
2321
2322                let remote_name = String::from_utf8_lossy(&output.stdout);
2323                return Ok(Some(Remote {
2324                    name: remote_name.trim().to_string().into(),
2325                }));
2326            })
2327            .boxed()
2328    }
2329
2330    fn get_all_remotes(&self) -> BoxFuture<'_, Result<Vec<Remote>>> {
2331        let git_binary = self.git_binary();
2332        self.executor
2333            .spawn(async move {
2334                let git = git_binary?;
2335                let output = git.build_command(&["remote", "-v"]).output().await?;
2336
2337                anyhow::ensure!(
2338                    output.status.success(),
2339                    "Failed to get all remotes:\n{}",
2340                    String::from_utf8_lossy(&output.stderr)
2341                );
2342                let remote_names: HashSet<Remote> = String::from_utf8_lossy(&output.stdout)
2343                    .lines()
2344                    .filter(|line| !line.is_empty())
2345                    .filter_map(|line| {
2346                        let mut split_line = line.split_whitespace();
2347                        let remote_name = split_line.next()?;
2348
2349                        Some(Remote {
2350                            name: remote_name.trim().to_string().into(),
2351                        })
2352                    })
2353                    .collect();
2354
2355                Ok(remote_names.into_iter().collect())
2356            })
2357            .boxed()
2358    }
2359
2360    fn remove_remote(&self, name: String) -> BoxFuture<'_, Result<()>> {
2361        let repo = self.repository.clone();
2362        self.executor
2363            .spawn(async move {
2364                let repo = repo.lock();
2365                repo.remote_delete(&name)?;
2366
2367                Ok(())
2368            })
2369            .boxed()
2370    }
2371
2372    fn create_remote(&self, name: String, url: String) -> BoxFuture<'_, Result<()>> {
2373        let repo = self.repository.clone();
2374        self.executor
2375            .spawn(async move {
2376                let repo = repo.lock();
2377                repo.remote(&name, url.as_ref())?;
2378                Ok(())
2379            })
2380            .boxed()
2381    }
2382
2383    fn check_for_pushed_commit(&self) -> BoxFuture<'_, Result<Vec<SharedString>>> {
2384        let git_binary = self.git_binary();
2385        self.executor
2386            .spawn(async move {
2387                let git = git_binary?;
2388                let git_cmd = async |args: &[&str]| -> Result<String> {
2389                    let output = git.build_command(args).output().await?;
2390                    anyhow::ensure!(
2391                        output.status.success(),
2392                        String::from_utf8_lossy(&output.stderr).to_string()
2393                    );
2394                    Ok(String::from_utf8(output.stdout)?)
2395                };
2396
2397                let head = git_cmd(&["rev-parse", "HEAD"])
2398                    .await
2399                    .context("Failed to get HEAD")?
2400                    .trim()
2401                    .to_owned();
2402
2403                let mut remote_branches = vec![];
2404                let mut add_if_matching = async |remote_head: &str| {
2405                    if let Ok(merge_base) = git_cmd(&["merge-base", &head, remote_head]).await
2406                        && merge_base.trim() == head
2407                        && let Some(s) = remote_head.strip_prefix("refs/remotes/")
2408                    {
2409                        remote_branches.push(s.to_owned().into());
2410                    }
2411                };
2412
2413                // check the main branch of each remote
2414                let remotes = git_cmd(&["remote"])
2415                    .await
2416                    .context("Failed to get remotes")?;
2417                for remote in remotes.lines() {
2418                    if let Ok(remote_head) =
2419                        git_cmd(&["symbolic-ref", &format!("refs/remotes/{remote}/HEAD")]).await
2420                    {
2421                        add_if_matching(remote_head.trim()).await;
2422                    }
2423                }
2424
2425                // ... and the remote branch that the checked-out one is tracking
2426                if let Ok(remote_head) =
2427                    git_cmd(&["rev-parse", "--symbolic-full-name", "@{u}"]).await
2428                {
2429                    add_if_matching(remote_head.trim()).await;
2430                }
2431
2432                Ok(remote_branches)
2433            })
2434            .boxed()
2435    }
2436
2437    fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>> {
2438        let git_binary = self.git_binary();
2439        self.executor
2440            .spawn(async move {
2441                let mut git = git_binary?.envs(checkpoint_author_envs());
2442                git.with_temp_index(async |git| {
2443                    let head_sha = git.run(&["rev-parse", "HEAD"]).await.ok();
2444                    let mut excludes = exclude_files(git).await?;
2445
2446                    git.run(&["add", "--all"]).await?;
2447                    let tree = git.run(&["write-tree"]).await?;
2448                    let checkpoint_sha = if let Some(head_sha) = head_sha.as_deref() {
2449                        git.run(&["commit-tree", &tree, "-p", head_sha, "-m", "Checkpoint"])
2450                            .await?
2451                    } else {
2452                        git.run(&["commit-tree", &tree, "-m", "Checkpoint"]).await?
2453                    };
2454
2455                    excludes.restore_original().await?;
2456
2457                    Ok(GitRepositoryCheckpoint {
2458                        commit_sha: checkpoint_sha.parse()?,
2459                    })
2460                })
2461                .await
2462            })
2463            .boxed()
2464    }
2465
2466    fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>> {
2467        let git_binary = self.git_binary();
2468        self.executor
2469            .spawn(async move {
2470                let git = git_binary?;
2471                git.run(&[
2472                    "restore",
2473                    "--source",
2474                    &checkpoint.commit_sha.to_string(),
2475                    "--worktree",
2476                    ".",
2477                ])
2478                .await?;
2479
2480                // TODO: We don't track binary and large files anymore,
2481                //       so the following call would delete them.
2482                //       Implement an alternative way to track files added by agent.
2483                //
2484                // git.with_temp_index(async move |git| {
2485                //     git.run(&["read-tree", &checkpoint.commit_sha.to_string()])
2486                //         .await?;
2487                //     git.run(&["clean", "-d", "--force"]).await
2488                // })
2489                // .await?;
2490
2491                Ok(())
2492            })
2493            .boxed()
2494    }
2495
2496    fn compare_checkpoints(
2497        &self,
2498        left: GitRepositoryCheckpoint,
2499        right: GitRepositoryCheckpoint,
2500    ) -> BoxFuture<'_, Result<bool>> {
2501        let git_binary = self.git_binary();
2502        self.executor
2503            .spawn(async move {
2504                let git = git_binary?;
2505                let result = git
2506                    .run(&[
2507                        "diff-tree",
2508                        "--quiet",
2509                        &left.commit_sha.to_string(),
2510                        &right.commit_sha.to_string(),
2511                    ])
2512                    .await;
2513                match result {
2514                    Ok(_) => Ok(true),
2515                    Err(error) => {
2516                        if let Some(GitBinaryCommandError { status, .. }) =
2517                            error.downcast_ref::<GitBinaryCommandError>()
2518                            && status.code() == Some(1)
2519                        {
2520                            return Ok(false);
2521                        }
2522
2523                        Err(error)
2524                    }
2525                }
2526            })
2527            .boxed()
2528    }
2529
2530    fn diff_checkpoints(
2531        &self,
2532        base_checkpoint: GitRepositoryCheckpoint,
2533        target_checkpoint: GitRepositoryCheckpoint,
2534    ) -> BoxFuture<'_, Result<String>> {
2535        let git_binary = self.git_binary();
2536        self.executor
2537            .spawn(async move {
2538                let git = git_binary?;
2539                git.run(&[
2540                    "diff",
2541                    "--find-renames",
2542                    "--patch",
2543                    &base_checkpoint.commit_sha.to_string(),
2544                    &target_checkpoint.commit_sha.to_string(),
2545                ])
2546                .await
2547            })
2548            .boxed()
2549    }
2550
2551    fn default_branch(
2552        &self,
2553        include_remote_name: bool,
2554    ) -> BoxFuture<'_, Result<Option<SharedString>>> {
2555        let git_binary = self.git_binary();
2556        self.executor
2557            .spawn(async move {
2558                let git = git_binary?;
2559
2560                let strip_prefix = if include_remote_name {
2561                    "refs/remotes/"
2562                } else {
2563                    "refs/remotes/upstream/"
2564                };
2565
2566                if let Ok(output) = git
2567                    .run(&["symbolic-ref", "refs/remotes/upstream/HEAD"])
2568                    .await
2569                {
2570                    let output = output
2571                        .strip_prefix(strip_prefix)
2572                        .map(|s| SharedString::from(s.to_owned()));
2573                    return Ok(output);
2574                }
2575
2576                let strip_prefix = if include_remote_name {
2577                    "refs/remotes/"
2578                } else {
2579                    "refs/remotes/origin/"
2580                };
2581
2582                if let Ok(output) = git.run(&["symbolic-ref", "refs/remotes/origin/HEAD"]).await {
2583                    return Ok(output
2584                        .strip_prefix(strip_prefix)
2585                        .map(|s| SharedString::from(s.to_owned())));
2586                }
2587
2588                if let Ok(default_branch) = git.run(&["config", "init.defaultBranch"]).await {
2589                    if git.run(&["rev-parse", &default_branch]).await.is_ok() {
2590                        return Ok(Some(default_branch.into()));
2591                    }
2592                }
2593
2594                if git.run(&["rev-parse", "master"]).await.is_ok() {
2595                    return Ok(Some("master".into()));
2596                }
2597
2598                Ok(None)
2599            })
2600            .boxed()
2601    }
2602
2603    fn run_hook(
2604        &self,
2605        hook: RunHook,
2606        env: Arc<HashMap<String, String>>,
2607    ) -> BoxFuture<'_, Result<()>> {
2608        let git_binary = self.git_binary();
2609        let repository = self.repository.clone();
2610        let help_output = self.any_git_binary_help_output();
2611
2612        // Note: Do not spawn these commands on the background thread, as this causes some git hooks to hang.
2613        async move {
2614            let git_binary = git_binary?;
2615
2616            let working_directory = git_binary.working_directory.clone();
2617            if !help_output
2618                .await
2619                .lines()
2620                .any(|line| line.trim().starts_with("hook "))
2621            {
2622                let hook_abs_path = repository.lock().path().join("hooks").join(hook.as_str());
2623                if hook_abs_path.is_file() && git_binary.is_trusted {
2624                    #[allow(clippy::disallowed_methods)]
2625                    let output = new_command(&hook_abs_path)
2626                        .envs(env.iter())
2627                        .current_dir(&working_directory)
2628                        .output()
2629                        .await?;
2630
2631                    if !output.status.success() {
2632                        return Err(GitBinaryCommandError {
2633                            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
2634                            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
2635                            status: output.status,
2636                        }
2637                        .into());
2638                    }
2639                }
2640
2641                return Ok(());
2642            }
2643
2644            if git_binary.is_trusted {
2645                let git_binary = git_binary.envs(HashMap::clone(&env));
2646                git_binary
2647                    .run(&["hook", "run", "--ignore-missing", hook.as_str()])
2648                    .await?;
2649            }
2650            Ok(())
2651        }
2652        .boxed()
2653    }
2654
2655    fn initial_graph_data(
2656        &self,
2657        log_source: LogSource,
2658        log_order: LogOrder,
2659        request_tx: Sender<Vec<Arc<InitialGraphCommitData>>>,
2660    ) -> BoxFuture<'_, Result<()>> {
2661        let git_binary = self.git_binary();
2662
2663        async move {
2664            let git = git_binary?;
2665
2666            let mut command = git.build_command(&[
2667                "log",
2668                GRAPH_COMMIT_FORMAT,
2669                log_order.as_arg(),
2670                log_source.get_arg()?,
2671            ]);
2672            command.stdout(Stdio::piped());
2673            command.stderr(Stdio::null());
2674
2675            let mut child = command.spawn()?;
2676            let stdout = child.stdout.take().context("failed to get stdout")?;
2677            let mut reader = BufReader::new(stdout);
2678
2679            let mut line_buffer = String::new();
2680            let mut lines: Vec<String> = Vec::with_capacity(GRAPH_CHUNK_SIZE);
2681
2682            loop {
2683                line_buffer.clear();
2684                let bytes_read = reader.read_line(&mut line_buffer).await?;
2685
2686                if bytes_read == 0 {
2687                    if !lines.is_empty() {
2688                        let commits = parse_initial_graph_output(lines.iter().map(|s| s.as_str()));
2689                        if request_tx.send(commits).await.is_err() {
2690                            log::warn!(
2691                                "initial_graph_data: receiver dropped while sending commits"
2692                            );
2693                        }
2694                    }
2695                    break;
2696                }
2697
2698                let line = line_buffer.trim_end_matches('\n').to_string();
2699                lines.push(line);
2700
2701                if lines.len() >= GRAPH_CHUNK_SIZE {
2702                    let commits = parse_initial_graph_output(lines.iter().map(|s| s.as_str()));
2703                    if request_tx.send(commits).await.is_err() {
2704                        log::warn!("initial_graph_data: receiver dropped while streaming commits");
2705                        break;
2706                    }
2707                    lines.clear();
2708                }
2709            }
2710
2711            child.status().await?;
2712            Ok(())
2713        }
2714        .boxed()
2715    }
2716
2717    fn search_commits(
2718        &self,
2719        log_source: LogSource,
2720        search_args: SearchCommitArgs,
2721        request_tx: Sender<Oid>,
2722    ) -> BoxFuture<'_, Result<()>> {
2723        let git_binary = self.git_binary();
2724
2725        async move {
2726            let git = git_binary?;
2727
2728            let mut args = vec!["log", SEARCH_COMMIT_FORMAT, log_source.get_arg()?];
2729
2730            args.push("--fixed-strings");
2731
2732            if !search_args.case_sensitive {
2733                args.push("--regexp-ignore-case");
2734            }
2735
2736            args.push("--grep");
2737            args.push(search_args.query.as_str());
2738
2739            let mut command = git.build_command(&args);
2740            command.stdout(Stdio::piped());
2741            command.stderr(Stdio::null());
2742
2743            let mut child = command.spawn()?;
2744            let stdout = child.stdout.take().context("failed to get stdout")?;
2745            let mut reader = BufReader::new(stdout);
2746
2747            let mut line_buffer = String::new();
2748
2749            loop {
2750                line_buffer.clear();
2751                let bytes_read = reader.read_line(&mut line_buffer).await?;
2752
2753                if bytes_read == 0 {
2754                    break;
2755                }
2756
2757                let sha = line_buffer.trim_end_matches('\n');
2758
2759                if let Ok(oid) = Oid::from_str(sha)
2760                    && request_tx.send(oid).await.is_err()
2761                {
2762                    break;
2763                }
2764            }
2765
2766            child.status().await?;
2767            Ok(())
2768        }
2769        .boxed()
2770    }
2771
2772    fn commit_data_reader(&self) -> Result<CommitDataReader> {
2773        let git_binary = self.git_binary()?;
2774
2775        let (request_tx, request_rx) = smol::channel::bounded::<CommitDataRequest>(64);
2776
2777        let task = self.executor.spawn(async move {
2778            if let Err(error) = run_commit_data_reader(git_binary, request_rx).await {
2779                log::error!("commit data reader failed: {error:?}");
2780            }
2781        });
2782
2783        Ok(CommitDataReader {
2784            request_tx,
2785            _task: task,
2786        })
2787    }
2788
2789    fn set_trusted(&self, trusted: bool) {
2790        self.is_trusted
2791            .store(trusted, std::sync::atomic::Ordering::Release);
2792    }
2793
2794    fn is_trusted(&self) -> bool {
2795        self.is_trusted.load(std::sync::atomic::Ordering::Acquire)
2796    }
2797}
2798
2799async fn run_commit_data_reader(
2800    git: GitBinary,
2801    request_rx: smol::channel::Receiver<CommitDataRequest>,
2802) -> Result<()> {
2803    let mut process = git
2804        .build_command(&["cat-file", "--batch"])
2805        .stdin(Stdio::piped())
2806        .stdout(Stdio::piped())
2807        .stderr(Stdio::piped())
2808        .spawn()
2809        .context("starting git cat-file --batch process")?;
2810
2811    let mut stdin = BufWriter::new(process.stdin.take().context("no stdin")?);
2812    let mut stdout = BufReader::new(process.stdout.take().context("no stdout")?);
2813
2814    const MAX_BATCH_SIZE: usize = 64;
2815
2816    while let Ok(first_request) = request_rx.recv().await {
2817        let mut pending_requests = vec![first_request];
2818
2819        while pending_requests.len() < MAX_BATCH_SIZE {
2820            match request_rx.try_recv() {
2821                Ok(request) => pending_requests.push(request),
2822                Err(_) => break,
2823            }
2824        }
2825
2826        for request in &pending_requests {
2827            stdin.write_all(request.sha.to_string().as_bytes()).await?;
2828            stdin.write_all(b"\n").await?;
2829        }
2830        stdin.flush().await?;
2831
2832        for request in pending_requests {
2833            let result = read_single_commit_response(&mut stdout, &request.sha).await;
2834            request.response_tx.send(result).ok();
2835        }
2836    }
2837
2838    drop(stdin);
2839    process.kill().ok();
2840
2841    Ok(())
2842}
2843
2844async fn read_single_commit_response<R: smol::io::AsyncBufRead + Unpin>(
2845    stdout: &mut R,
2846    sha: &Oid,
2847) -> Result<GraphCommitData> {
2848    let mut header_bytes = Vec::new();
2849    stdout.read_until(b'\n', &mut header_bytes).await?;
2850    let header_line = String::from_utf8_lossy(&header_bytes);
2851
2852    let parts: Vec<&str> = header_line.trim().split(' ').collect();
2853    if parts.len() < 3 {
2854        bail!("invalid cat-file header: {header_line}");
2855    }
2856
2857    let object_type = parts[1];
2858    if object_type == "missing" {
2859        bail!("object not found: {}", sha);
2860    }
2861
2862    if object_type != "commit" {
2863        bail!("expected commit object, got {object_type}");
2864    }
2865
2866    let size: usize = parts[2]
2867        .parse()
2868        .with_context(|| format!("invalid object size: {}", parts[2]))?;
2869
2870    let mut content = vec![0u8; size];
2871    stdout.read_exact(&mut content).await?;
2872
2873    let mut newline = [0u8; 1];
2874    stdout.read_exact(&mut newline).await?;
2875
2876    let content_str = String::from_utf8_lossy(&content);
2877    parse_cat_file_commit(*sha, &content_str)
2878        .ok_or_else(|| anyhow!("failed to parse commit {}", sha))
2879}
2880
2881fn parse_initial_graph_output<'a>(
2882    lines: impl Iterator<Item = &'a str>,
2883) -> Vec<Arc<InitialGraphCommitData>> {
2884    lines
2885        .filter(|line| !line.is_empty())
2886        .filter_map(|line| {
2887            // Format: "SHA\x00PARENT1 PARENT2...\x00REF1, REF2, ..."
2888            let mut parts = line.split('\x00');
2889
2890            let sha = Oid::from_str(parts.next()?).ok()?;
2891            let parents_str = parts.next()?;
2892            let parents = parents_str
2893                .split_whitespace()
2894                .filter_map(|p| Oid::from_str(p).ok())
2895                .collect();
2896
2897            let ref_names_str = parts.next().unwrap_or("");
2898            let ref_names = if ref_names_str.is_empty() {
2899                Vec::new()
2900            } else {
2901                ref_names_str
2902                    .split(", ")
2903                    .map(|s| SharedString::from(s.to_string()))
2904                    .collect()
2905            };
2906
2907            Some(Arc::new(InitialGraphCommitData {
2908                sha,
2909                parents,
2910                ref_names,
2911            }))
2912        })
2913        .collect()
2914}
2915
2916fn git_status_args(path_prefixes: &[RepoPath]) -> Vec<OsString> {
2917    let mut args = vec![
2918        OsString::from("status"),
2919        OsString::from("--porcelain=v1"),
2920        OsString::from("--untracked-files=all"),
2921        OsString::from("--no-renames"),
2922        OsString::from("-z"),
2923    ];
2924    args.extend(path_prefixes.iter().map(|path_prefix| {
2925        if path_prefix.is_empty() {
2926            Path::new(".").into()
2927        } else {
2928            path_prefix.as_std_path().into()
2929        }
2930    }));
2931    args
2932}
2933
2934/// Temporarily git-ignore commonly ignored files and files over 2MB
2935async fn exclude_files(git: &GitBinary) -> Result<GitExcludeOverride> {
2936    const MAX_SIZE: u64 = 2 * 1024 * 1024; // 2 MB
2937    let mut excludes = git.with_exclude_overrides().await?;
2938    excludes
2939        .add_excludes(include_str!("./checkpoint.gitignore"))
2940        .await?;
2941
2942    let working_directory = git.working_directory.clone();
2943    let untracked_files = git.list_untracked_files().await?;
2944    let excluded_paths = untracked_files.into_iter().map(|path| {
2945        let working_directory = working_directory.clone();
2946        smol::spawn(async move {
2947            let full_path = working_directory.join(path.clone());
2948            match smol::fs::metadata(&full_path).await {
2949                Ok(metadata) if metadata.is_file() && metadata.len() >= MAX_SIZE => {
2950                    Some(PathBuf::from("/").join(path.clone()))
2951                }
2952                _ => None,
2953            }
2954        })
2955    });
2956
2957    let excluded_paths = futures::future::join_all(excluded_paths).await;
2958    let excluded_paths = excluded_paths.into_iter().flatten().collect::<Vec<_>>();
2959
2960    if !excluded_paths.is_empty() {
2961        let exclude_patterns = excluded_paths
2962            .into_iter()
2963            .map(|path| path.to_string_lossy().into_owned())
2964            .collect::<Vec<_>>()
2965            .join("\n");
2966        excludes.add_excludes(&exclude_patterns).await?;
2967    }
2968
2969    Ok(excludes)
2970}
2971
2972pub(crate) struct GitBinary {
2973    git_binary_path: PathBuf,
2974    working_directory: PathBuf,
2975    git_directory: PathBuf,
2976    executor: BackgroundExecutor,
2977    index_file_path: Option<PathBuf>,
2978    envs: HashMap<String, String>,
2979    is_trusted: bool,
2980}
2981
2982impl GitBinary {
2983    pub(crate) fn new(
2984        git_binary_path: PathBuf,
2985        working_directory: PathBuf,
2986        git_directory: PathBuf,
2987        executor: BackgroundExecutor,
2988        is_trusted: bool,
2989    ) -> Self {
2990        Self {
2991            git_binary_path,
2992            working_directory,
2993            git_directory,
2994            executor,
2995            index_file_path: None,
2996            envs: HashMap::default(),
2997            is_trusted,
2998        }
2999    }
3000
3001    async fn list_untracked_files(&self) -> Result<Vec<PathBuf>> {
3002        let status_output = self
3003            .run(&["status", "--porcelain=v1", "--untracked-files=all", "-z"])
3004            .await?;
3005
3006        let paths = status_output
3007            .split('\0')
3008            .filter(|entry| entry.len() >= 3 && entry.starts_with("?? "))
3009            .map(|entry| PathBuf::from(&entry[3..]))
3010            .collect::<Vec<_>>();
3011        Ok(paths)
3012    }
3013
3014    fn envs(mut self, envs: HashMap<String, String>) -> Self {
3015        self.envs = envs;
3016        self
3017    }
3018
3019    pub async fn with_temp_index<R>(
3020        &mut self,
3021        f: impl AsyncFnOnce(&Self) -> Result<R>,
3022    ) -> Result<R> {
3023        let index_file_path = self.path_for_index_id(Uuid::new_v4());
3024
3025        let delete_temp_index = util::defer({
3026            let index_file_path = index_file_path.clone();
3027            let executor = self.executor.clone();
3028            move || {
3029                executor
3030                    .spawn(async move {
3031                        smol::fs::remove_file(index_file_path).await.log_err();
3032                    })
3033                    .detach();
3034            }
3035        });
3036
3037        // Copy the default index file so that Git doesn't have to rebuild the
3038        // whole index from scratch. This might fail if this is an empty repository.
3039        smol::fs::copy(self.git_directory.join("index"), &index_file_path)
3040            .await
3041            .ok();
3042
3043        self.index_file_path = Some(index_file_path.clone());
3044        let result = f(self).await;
3045        self.index_file_path = None;
3046        let result = result?;
3047
3048        smol::fs::remove_file(index_file_path).await.ok();
3049        delete_temp_index.abort();
3050
3051        Ok(result)
3052    }
3053
3054    pub async fn with_exclude_overrides(&self) -> Result<GitExcludeOverride> {
3055        let path = self.git_directory.join("info").join("exclude");
3056
3057        GitExcludeOverride::new(path).await
3058    }
3059
3060    fn path_for_index_id(&self, id: Uuid) -> PathBuf {
3061        self.git_directory.join(format!("index-{}.tmp", id))
3062    }
3063
3064    pub async fn run<S>(&self, args: &[S]) -> Result<String>
3065    where
3066        S: AsRef<OsStr>,
3067    {
3068        let mut stdout = self.run_raw(args).await?;
3069        if stdout.chars().last() == Some('\n') {
3070            stdout.pop();
3071        }
3072        Ok(stdout)
3073    }
3074
3075    /// Returns the result of the command without trimming the trailing newline.
3076    pub async fn run_raw<S>(&self, args: &[S]) -> Result<String>
3077    where
3078        S: AsRef<OsStr>,
3079    {
3080        let mut command = self.build_command(args);
3081        let output = command.output().await?;
3082        anyhow::ensure!(
3083            output.status.success(),
3084            GitBinaryCommandError {
3085                stdout: String::from_utf8_lossy(&output.stdout).to_string(),
3086                stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3087                status: output.status,
3088            }
3089        );
3090        Ok(String::from_utf8(output.stdout)?)
3091    }
3092
3093    #[allow(clippy::disallowed_methods)]
3094    pub(crate) fn build_command<S>(&self, args: &[S]) -> util::command::Command
3095    where
3096        S: AsRef<OsStr>,
3097    {
3098        let mut command = new_command(&self.git_binary_path);
3099        command.current_dir(&self.working_directory);
3100        command.args(["-c", "core.fsmonitor=false"]);
3101        command.arg("--no-optional-locks");
3102        command.arg("--no-pager");
3103
3104        if !self.is_trusted {
3105            command.args(["-c", "core.hooksPath=/dev/null"]);
3106            command.args(["-c", "core.sshCommand=ssh"]);
3107            command.args(["-c", "credential.helper="]);
3108            command.args(["-c", "protocol.ext.allow=never"]);
3109            command.args(["-c", "diff.external="]);
3110        }
3111        command.args(args);
3112
3113        // If the `diff` command is being used, we'll want to add the
3114        // `--no-ext-diff` flag when working on an untrusted repository,
3115        // preventing any external diff programs from being invoked.
3116        if !self.is_trusted && args.iter().any(|arg| arg.as_ref() == "diff") {
3117            command.arg("--no-ext-diff");
3118        }
3119
3120        if let Some(index_file_path) = self.index_file_path.as_ref() {
3121            command.env("GIT_INDEX_FILE", index_file_path);
3122        }
3123        command.envs(&self.envs);
3124        command
3125    }
3126}
3127
3128#[derive(Error, Debug)]
3129#[error("Git command failed:\n{stdout}{stderr}\n")]
3130struct GitBinaryCommandError {
3131    stdout: String,
3132    stderr: String,
3133    status: ExitStatus,
3134}
3135
3136async fn run_git_command(
3137    env: Arc<HashMap<String, String>>,
3138    ask_pass: AskPassDelegate,
3139    mut command: util::command::Command,
3140    executor: BackgroundExecutor,
3141) -> Result<RemoteCommandOutput> {
3142    if env.contains_key("GIT_ASKPASS") {
3143        let git_process = command.spawn()?;
3144        let output = git_process.output().await?;
3145        anyhow::ensure!(
3146            output.status.success(),
3147            "{}",
3148            String::from_utf8_lossy(&output.stderr)
3149        );
3150        Ok(RemoteCommandOutput {
3151            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
3152            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3153        })
3154    } else {
3155        let ask_pass = AskPassSession::new(executor, ask_pass).await?;
3156        command
3157            .env("GIT_ASKPASS", ask_pass.script_path())
3158            .env("SSH_ASKPASS", ask_pass.script_path())
3159            .env("SSH_ASKPASS_REQUIRE", "force");
3160        let git_process = command.spawn()?;
3161
3162        run_askpass_command(ask_pass, git_process).await
3163    }
3164}
3165
3166async fn run_askpass_command(
3167    mut ask_pass: AskPassSession,
3168    git_process: util::command::Child,
3169) -> anyhow::Result<RemoteCommandOutput> {
3170    select_biased! {
3171        result = ask_pass.run().fuse() => {
3172            match result {
3173                AskPassResult::CancelledByUser => {
3174                    Err(anyhow!(REMOTE_CANCELLED_BY_USER))?
3175                }
3176                AskPassResult::Timedout => {
3177                    Err(anyhow!("Connecting to host timed out"))?
3178                }
3179            }
3180        }
3181        output = git_process.output().fuse() => {
3182            let output = output?;
3183            anyhow::ensure!(
3184                output.status.success(),
3185                "{}",
3186                String::from_utf8_lossy(&output.stderr)
3187            );
3188            Ok(RemoteCommandOutput {
3189                stdout: String::from_utf8_lossy(&output.stdout).to_string(),
3190                stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3191            })
3192        }
3193    }
3194}
3195
3196#[derive(Clone, Ord, Hash, PartialOrd, Eq, PartialEq)]
3197pub struct RepoPath(Arc<RelPath>);
3198
3199impl std::fmt::Debug for RepoPath {
3200    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3201        self.0.fmt(f)
3202    }
3203}
3204
3205impl RepoPath {
3206    pub fn new<S: AsRef<str> + ?Sized>(s: &S) -> Result<Self> {
3207        let rel_path = RelPath::unix(s.as_ref())?;
3208        Ok(Self::from_rel_path(rel_path))
3209    }
3210
3211    pub fn from_std_path(path: &Path, path_style: PathStyle) -> Result<Self> {
3212        let rel_path = RelPath::new(path, path_style)?;
3213        Ok(Self::from_rel_path(&rel_path))
3214    }
3215
3216    pub fn from_proto(proto: &str) -> Result<Self> {
3217        let rel_path = RelPath::from_proto(proto)?;
3218        Ok(Self(rel_path))
3219    }
3220
3221    pub fn from_rel_path(path: &RelPath) -> RepoPath {
3222        Self(Arc::from(path))
3223    }
3224
3225    pub fn as_std_path(&self) -> &Path {
3226        // git2 does not like empty paths and our RelPath infra turns `.` into ``
3227        // so undo that here
3228        if self.is_empty() {
3229            Path::new(".")
3230        } else {
3231            self.0.as_std_path()
3232        }
3233    }
3234}
3235
3236#[cfg(any(test, feature = "test-support"))]
3237pub fn repo_path<S: AsRef<str> + ?Sized>(s: &S) -> RepoPath {
3238    RepoPath(RelPath::unix(s.as_ref()).unwrap().into())
3239}
3240
3241impl AsRef<Arc<RelPath>> for RepoPath {
3242    fn as_ref(&self) -> &Arc<RelPath> {
3243        &self.0
3244    }
3245}
3246
3247impl std::ops::Deref for RepoPath {
3248    type Target = RelPath;
3249
3250    fn deref(&self) -> &Self::Target {
3251        &self.0
3252    }
3253}
3254
3255#[derive(Debug)]
3256pub struct RepoPathDescendants<'a>(pub &'a RepoPath);
3257
3258impl MapSeekTarget<RepoPath> for RepoPathDescendants<'_> {
3259    fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
3260        if key.starts_with(self.0) {
3261            Ordering::Greater
3262        } else {
3263            self.0.cmp(key)
3264        }
3265    }
3266}
3267
3268fn parse_branch_input(input: &str) -> Result<Vec<Branch>> {
3269    let mut branches = Vec::new();
3270    for line in input.split('\n') {
3271        if line.is_empty() {
3272            continue;
3273        }
3274        let mut fields = line.split('\x00');
3275        let Some(head) = fields.next() else {
3276            continue;
3277        };
3278        let Some(head_sha) = fields.next().map(|f| f.to_string().into()) else {
3279            continue;
3280        };
3281        let Some(parent_sha) = fields.next().map(|f| f.to_string()) else {
3282            continue;
3283        };
3284        let Some(ref_name) = fields.next().map(|f| f.to_string().into()) else {
3285            continue;
3286        };
3287        let Some(upstream_name) = fields.next().map(|f| f.to_string()) else {
3288            continue;
3289        };
3290        let Some(upstream_tracking) = fields.next().and_then(|f| parse_upstream_track(f).ok())
3291        else {
3292            continue;
3293        };
3294        let Some(commiterdate) = fields.next().and_then(|f| f.parse::<i64>().ok()) else {
3295            continue;
3296        };
3297        let Some(author_name) = fields.next().map(|f| f.to_string().into()) else {
3298            continue;
3299        };
3300        let Some(subject) = fields.next().map(|f| f.to_string().into()) else {
3301            continue;
3302        };
3303
3304        branches.push(Branch {
3305            is_head: head == "*",
3306            ref_name,
3307            most_recent_commit: Some(CommitSummary {
3308                sha: head_sha,
3309                subject,
3310                commit_timestamp: commiterdate,
3311                author_name: author_name,
3312                has_parent: !parent_sha.is_empty(),
3313            }),
3314            upstream: if upstream_name.is_empty() {
3315                None
3316            } else {
3317                Some(Upstream {
3318                    ref_name: upstream_name.into(),
3319                    tracking: upstream_tracking,
3320                })
3321            },
3322        })
3323    }
3324
3325    Ok(branches)
3326}
3327
3328fn parse_upstream_track(upstream_track: &str) -> Result<UpstreamTracking> {
3329    if upstream_track.is_empty() {
3330        return Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
3331            ahead: 0,
3332            behind: 0,
3333        }));
3334    }
3335
3336    let upstream_track = upstream_track.strip_prefix("[").context("missing [")?;
3337    let upstream_track = upstream_track.strip_suffix("]").context("missing [")?;
3338    let mut ahead: u32 = 0;
3339    let mut behind: u32 = 0;
3340    for component in upstream_track.split(", ") {
3341        if component == "gone" {
3342            return Ok(UpstreamTracking::Gone);
3343        }
3344        if let Some(ahead_num) = component.strip_prefix("ahead ") {
3345            ahead = ahead_num.parse::<u32>()?;
3346        }
3347        if let Some(behind_num) = component.strip_prefix("behind ") {
3348            behind = behind_num.parse::<u32>()?;
3349        }
3350    }
3351    Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
3352        ahead,
3353        behind,
3354    }))
3355}
3356
3357fn checkpoint_author_envs() -> HashMap<String, String> {
3358    HashMap::from_iter([
3359        ("GIT_AUTHOR_NAME".to_string(), "Zed".to_string()),
3360        ("GIT_AUTHOR_EMAIL".to_string(), "hi@zed.dev".to_string()),
3361        ("GIT_COMMITTER_NAME".to_string(), "Zed".to_string()),
3362        ("GIT_COMMITTER_EMAIL".to_string(), "hi@zed.dev".to_string()),
3363    ])
3364}
3365
3366#[cfg(test)]
3367mod tests {
3368    use std::fs;
3369
3370    use super::*;
3371    use gpui::TestAppContext;
3372
3373    fn disable_git_global_config() {
3374        unsafe {
3375            std::env::set_var("GIT_CONFIG_GLOBAL", "");
3376            std::env::set_var("GIT_CONFIG_SYSTEM", "");
3377        }
3378    }
3379
3380    #[gpui::test]
3381    async fn test_build_command_untrusted_includes_both_safety_args(cx: &mut TestAppContext) {
3382        cx.executor().allow_parking();
3383        let dir = tempfile::tempdir().unwrap();
3384        let git = GitBinary::new(
3385            PathBuf::from("git"),
3386            dir.path().to_path_buf(),
3387            dir.path().join(".git"),
3388            cx.executor(),
3389            false,
3390        );
3391        let output = git
3392            .build_command(&["version"])
3393            .output()
3394            .await
3395            .expect("git version should succeed");
3396        assert!(output.status.success());
3397
3398        let git = GitBinary::new(
3399            PathBuf::from("git"),
3400            dir.path().to_path_buf(),
3401            dir.path().join(".git"),
3402            cx.executor(),
3403            false,
3404        );
3405        let output = git
3406            .build_command(&["config", "--get", "core.fsmonitor"])
3407            .output()
3408            .await
3409            .expect("git config should run");
3410        let stdout = String::from_utf8_lossy(&output.stdout);
3411        assert_eq!(
3412            stdout.trim(),
3413            "false",
3414            "fsmonitor should be disabled for untrusted repos"
3415        );
3416
3417        git2::Repository::init(dir.path()).unwrap();
3418        let git = GitBinary::new(
3419            PathBuf::from("git"),
3420            dir.path().to_path_buf(),
3421            dir.path().join(".git"),
3422            cx.executor(),
3423            false,
3424        );
3425        let output = git
3426            .build_command(&["config", "--get", "core.hooksPath"])
3427            .output()
3428            .await
3429            .expect("git config should run");
3430        let stdout = String::from_utf8_lossy(&output.stdout);
3431        assert_eq!(
3432            stdout.trim(),
3433            "/dev/null",
3434            "hooksPath should be /dev/null for untrusted repos"
3435        );
3436    }
3437
3438    #[gpui::test]
3439    async fn test_build_command_trusted_only_disables_fsmonitor(cx: &mut TestAppContext) {
3440        cx.executor().allow_parking();
3441        let dir = tempfile::tempdir().unwrap();
3442        git2::Repository::init(dir.path()).unwrap();
3443
3444        let git = GitBinary::new(
3445            PathBuf::from("git"),
3446            dir.path().to_path_buf(),
3447            dir.path().join(".git"),
3448            cx.executor(),
3449            true,
3450        );
3451        let output = git
3452            .build_command(&["config", "--get", "core.fsmonitor"])
3453            .output()
3454            .await
3455            .expect("git config should run");
3456        let stdout = String::from_utf8_lossy(&output.stdout);
3457        assert_eq!(
3458            stdout.trim(),
3459            "false",
3460            "fsmonitor should be disabled even for trusted repos"
3461        );
3462
3463        let git = GitBinary::new(
3464            PathBuf::from("git"),
3465            dir.path().to_path_buf(),
3466            dir.path().join(".git"),
3467            cx.executor(),
3468            true,
3469        );
3470        let output = git
3471            .build_command(&["config", "--get", "core.hooksPath"])
3472            .output()
3473            .await
3474            .expect("git config should run");
3475        assert!(
3476            !output.status.success(),
3477            "hooksPath should NOT be overridden for trusted repos"
3478        );
3479    }
3480
3481    #[gpui::test]
3482    async fn test_path_for_index_id_uses_real_git_directory(cx: &mut TestAppContext) {
3483        cx.executor().allow_parking();
3484        let working_directory = PathBuf::from("/code/worktree");
3485        let git_directory = PathBuf::from("/code/repo/.git/modules/worktree");
3486        let git = GitBinary::new(
3487            PathBuf::from("git"),
3488            working_directory,
3489            git_directory.clone(),
3490            cx.executor(),
3491            false,
3492        );
3493
3494        let path = git.path_for_index_id(Uuid::nil());
3495
3496        assert_eq!(
3497            path,
3498            git_directory.join(format!("index-{}.tmp", Uuid::nil()))
3499        );
3500    }
3501
3502    #[gpui::test]
3503    async fn test_checkpoint_basic(cx: &mut TestAppContext) {
3504        disable_git_global_config();
3505
3506        cx.executor().allow_parking();
3507
3508        let repo_dir = tempfile::tempdir().unwrap();
3509
3510        git2::Repository::init(repo_dir.path()).unwrap();
3511        let file_path = repo_dir.path().join("file");
3512        smol::fs::write(&file_path, "initial").await.unwrap();
3513
3514        let repo = RealGitRepository::new(
3515            &repo_dir.path().join(".git"),
3516            None,
3517            Some("git".into()),
3518            cx.executor(),
3519        )
3520        .unwrap();
3521
3522        repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
3523            .await
3524            .unwrap();
3525        repo.commit(
3526            "Initial commit".into(),
3527            None,
3528            CommitOptions::default(),
3529            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3530            Arc::new(checkpoint_author_envs()),
3531        )
3532        .await
3533        .unwrap();
3534
3535        smol::fs::write(&file_path, "modified before checkpoint")
3536            .await
3537            .unwrap();
3538        smol::fs::write(repo_dir.path().join("new_file_before_checkpoint"), "1")
3539            .await
3540            .unwrap();
3541        let checkpoint = repo.checkpoint().await.unwrap();
3542
3543        // Ensure the user can't see any branches after creating a checkpoint.
3544        assert_eq!(repo.branches().await.unwrap().len(), 1);
3545
3546        smol::fs::write(&file_path, "modified after checkpoint")
3547            .await
3548            .unwrap();
3549        repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
3550            .await
3551            .unwrap();
3552        repo.commit(
3553            "Commit after checkpoint".into(),
3554            None,
3555            CommitOptions::default(),
3556            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3557            Arc::new(checkpoint_author_envs()),
3558        )
3559        .await
3560        .unwrap();
3561
3562        smol::fs::remove_file(repo_dir.path().join("new_file_before_checkpoint"))
3563            .await
3564            .unwrap();
3565        smol::fs::write(repo_dir.path().join("new_file_after_checkpoint"), "2")
3566            .await
3567            .unwrap();
3568
3569        // Ensure checkpoint stays alive even after a Git GC.
3570        repo.gc().await.unwrap();
3571        repo.restore_checkpoint(checkpoint.clone()).await.unwrap();
3572
3573        assert_eq!(
3574            smol::fs::read_to_string(&file_path).await.unwrap(),
3575            "modified before checkpoint"
3576        );
3577        assert_eq!(
3578            smol::fs::read_to_string(repo_dir.path().join("new_file_before_checkpoint"))
3579                .await
3580                .unwrap(),
3581            "1"
3582        );
3583        // See TODO above
3584        // assert_eq!(
3585        //     smol::fs::read_to_string(repo_dir.path().join("new_file_after_checkpoint"))
3586        //         .await
3587        //         .ok(),
3588        //     None
3589        // );
3590    }
3591
3592    #[gpui::test]
3593    async fn test_checkpoint_empty_repo(cx: &mut TestAppContext) {
3594        disable_git_global_config();
3595
3596        cx.executor().allow_parking();
3597
3598        let repo_dir = tempfile::tempdir().unwrap();
3599        git2::Repository::init(repo_dir.path()).unwrap();
3600        let repo = RealGitRepository::new(
3601            &repo_dir.path().join(".git"),
3602            None,
3603            Some("git".into()),
3604            cx.executor(),
3605        )
3606        .unwrap();
3607
3608        smol::fs::write(repo_dir.path().join("foo"), "foo")
3609            .await
3610            .unwrap();
3611        let checkpoint_sha = repo.checkpoint().await.unwrap();
3612
3613        // Ensure the user can't see any branches after creating a checkpoint.
3614        assert_eq!(repo.branches().await.unwrap().len(), 1);
3615
3616        smol::fs::write(repo_dir.path().join("foo"), "bar")
3617            .await
3618            .unwrap();
3619        smol::fs::write(repo_dir.path().join("baz"), "qux")
3620            .await
3621            .unwrap();
3622        repo.restore_checkpoint(checkpoint_sha).await.unwrap();
3623        assert_eq!(
3624            smol::fs::read_to_string(repo_dir.path().join("foo"))
3625                .await
3626                .unwrap(),
3627            "foo"
3628        );
3629        // See TODOs above
3630        // assert_eq!(
3631        //     smol::fs::read_to_string(repo_dir.path().join("baz"))
3632        //         .await
3633        //         .ok(),
3634        //     None
3635        // );
3636    }
3637
3638    #[gpui::test]
3639    async fn test_compare_checkpoints(cx: &mut TestAppContext) {
3640        disable_git_global_config();
3641
3642        cx.executor().allow_parking();
3643
3644        let repo_dir = tempfile::tempdir().unwrap();
3645        git2::Repository::init(repo_dir.path()).unwrap();
3646        let repo = RealGitRepository::new(
3647            &repo_dir.path().join(".git"),
3648            None,
3649            Some("git".into()),
3650            cx.executor(),
3651        )
3652        .unwrap();
3653
3654        smol::fs::write(repo_dir.path().join("file1"), "content1")
3655            .await
3656            .unwrap();
3657        let checkpoint1 = repo.checkpoint().await.unwrap();
3658
3659        smol::fs::write(repo_dir.path().join("file2"), "content2")
3660            .await
3661            .unwrap();
3662        let checkpoint2 = repo.checkpoint().await.unwrap();
3663
3664        assert!(
3665            !repo
3666                .compare_checkpoints(checkpoint1, checkpoint2.clone())
3667                .await
3668                .unwrap()
3669        );
3670
3671        let checkpoint3 = repo.checkpoint().await.unwrap();
3672        assert!(
3673            repo.compare_checkpoints(checkpoint2, checkpoint3)
3674                .await
3675                .unwrap()
3676        );
3677    }
3678
3679    #[gpui::test]
3680    async fn test_checkpoint_exclude_binary_files(cx: &mut TestAppContext) {
3681        disable_git_global_config();
3682
3683        cx.executor().allow_parking();
3684
3685        let repo_dir = tempfile::tempdir().unwrap();
3686        let text_path = repo_dir.path().join("main.rs");
3687        let bin_path = repo_dir.path().join("binary.o");
3688
3689        git2::Repository::init(repo_dir.path()).unwrap();
3690
3691        smol::fs::write(&text_path, "fn main() {}").await.unwrap();
3692
3693        smol::fs::write(&bin_path, "some binary file here")
3694            .await
3695            .unwrap();
3696
3697        let repo = RealGitRepository::new(
3698            &repo_dir.path().join(".git"),
3699            None,
3700            Some("git".into()),
3701            cx.executor(),
3702        )
3703        .unwrap();
3704
3705        // initial commit
3706        repo.stage_paths(vec![repo_path("main.rs")], Arc::new(HashMap::default()))
3707            .await
3708            .unwrap();
3709        repo.commit(
3710            "Initial commit".into(),
3711            None,
3712            CommitOptions::default(),
3713            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3714            Arc::new(checkpoint_author_envs()),
3715        )
3716        .await
3717        .unwrap();
3718
3719        let checkpoint = repo.checkpoint().await.unwrap();
3720
3721        smol::fs::write(&text_path, "fn main() { println!(\"Modified\"); }")
3722            .await
3723            .unwrap();
3724        smol::fs::write(&bin_path, "Modified binary file")
3725            .await
3726            .unwrap();
3727
3728        repo.restore_checkpoint(checkpoint).await.unwrap();
3729
3730        // Text files should be restored to checkpoint state,
3731        // but binaries should not (they aren't tracked)
3732        assert_eq!(
3733            smol::fs::read_to_string(&text_path).await.unwrap(),
3734            "fn main() {}"
3735        );
3736
3737        assert_eq!(
3738            smol::fs::read_to_string(&bin_path).await.unwrap(),
3739            "Modified binary file"
3740        );
3741    }
3742
3743    #[test]
3744    fn test_branches_parsing() {
3745        // suppress "help: octal escapes are not supported, `\0` is always null"
3746        #[allow(clippy::octal_escapes)]
3747        let input = "*\0060964da10574cd9bf06463a53bf6e0769c5c45e\0\0refs/heads/zed-patches\0refs/remotes/origin/zed-patches\0\01733187470\0John Doe\0generated protobuf\n";
3748        assert_eq!(
3749            parse_branch_input(input).unwrap(),
3750            vec![Branch {
3751                is_head: true,
3752                ref_name: "refs/heads/zed-patches".into(),
3753                upstream: Some(Upstream {
3754                    ref_name: "refs/remotes/origin/zed-patches".into(),
3755                    tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3756                        ahead: 0,
3757                        behind: 0
3758                    })
3759                }),
3760                most_recent_commit: Some(CommitSummary {
3761                    sha: "060964da10574cd9bf06463a53bf6e0769c5c45e".into(),
3762                    subject: "generated protobuf".into(),
3763                    commit_timestamp: 1733187470,
3764                    author_name: SharedString::new_static("John Doe"),
3765                    has_parent: false,
3766                })
3767            }]
3768        )
3769    }
3770
3771    #[test]
3772    fn test_branches_parsing_containing_refs_with_missing_fields() {
3773        #[allow(clippy::octal_escapes)]
3774        let input = " \090012116c03db04344ab10d50348553aa94f1ea0\0refs/heads/broken\n \0eb0cae33272689bd11030822939dd2701c52f81e\0895951d681e5561478c0acdd6905e8aacdfd2249\0refs/heads/dev\0\0\01762948725\0Zed\0Add feature\n*\0895951d681e5561478c0acdd6905e8aacdfd2249\0\0refs/heads/main\0\0\01762948695\0Zed\0Initial commit\n";
3775
3776        let branches = parse_branch_input(input).unwrap();
3777        assert_eq!(branches.len(), 2);
3778        assert_eq!(
3779            branches,
3780            vec![
3781                Branch {
3782                    is_head: false,
3783                    ref_name: "refs/heads/dev".into(),
3784                    upstream: None,
3785                    most_recent_commit: Some(CommitSummary {
3786                        sha: "eb0cae33272689bd11030822939dd2701c52f81e".into(),
3787                        subject: "Add feature".into(),
3788                        commit_timestamp: 1762948725,
3789                        author_name: SharedString::new_static("Zed"),
3790                        has_parent: true,
3791                    })
3792                },
3793                Branch {
3794                    is_head: true,
3795                    ref_name: "refs/heads/main".into(),
3796                    upstream: None,
3797                    most_recent_commit: Some(CommitSummary {
3798                        sha: "895951d681e5561478c0acdd6905e8aacdfd2249".into(),
3799                        subject: "Initial commit".into(),
3800                        commit_timestamp: 1762948695,
3801                        author_name: SharedString::new_static("Zed"),
3802                        has_parent: false,
3803                    })
3804                }
3805            ]
3806        )
3807    }
3808
3809    #[test]
3810    fn test_upstream_branch_name() {
3811        let upstream = Upstream {
3812            ref_name: "refs/remotes/origin/feature/branch".into(),
3813            tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3814                ahead: 0,
3815                behind: 0,
3816            }),
3817        };
3818        assert_eq!(upstream.branch_name(), Some("feature/branch"));
3819
3820        let upstream = Upstream {
3821            ref_name: "refs/remotes/upstream/main".into(),
3822            tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3823                ahead: 0,
3824                behind: 0,
3825            }),
3826        };
3827        assert_eq!(upstream.branch_name(), Some("main"));
3828
3829        let upstream = Upstream {
3830            ref_name: "refs/heads/local".into(),
3831            tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3832                ahead: 0,
3833                behind: 0,
3834            }),
3835        };
3836        assert_eq!(upstream.branch_name(), None);
3837
3838        // Test case where upstream branch name differs from what might be the local branch name
3839        let upstream = Upstream {
3840            ref_name: "refs/remotes/origin/feature/git-pull-request".into(),
3841            tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3842                ahead: 0,
3843                behind: 0,
3844            }),
3845        };
3846        assert_eq!(upstream.branch_name(), Some("feature/git-pull-request"));
3847    }
3848
3849    #[test]
3850    fn test_parse_worktrees_from_str() {
3851        // Empty input
3852        let result = parse_worktrees_from_str("");
3853        assert!(result.is_empty());
3854
3855        // Single worktree (main)
3856        let input = "worktree /home/user/project\nHEAD abc123def\nbranch refs/heads/main\n\n";
3857        let result = parse_worktrees_from_str(input);
3858        assert_eq!(result.len(), 1);
3859        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3860        assert_eq!(result[0].sha.as_ref(), "abc123def");
3861        assert_eq!(result[0].ref_name, Some("refs/heads/main".into()));
3862
3863        // Multiple worktrees
3864        let input = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n\n\
3865                      worktree /home/user/project-wt\nHEAD def456\nbranch refs/heads/feature\n\n";
3866        let result = parse_worktrees_from_str(input);
3867        assert_eq!(result.len(), 2);
3868        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3869        assert_eq!(result[0].ref_name, Some("refs/heads/main".into()));
3870        assert_eq!(result[1].path, PathBuf::from("/home/user/project-wt"));
3871        assert_eq!(result[1].ref_name, Some("refs/heads/feature".into()));
3872
3873        // Detached HEAD entry (included with ref_name: None)
3874        let input = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n\n\
3875                      worktree /home/user/detached\nHEAD def456\ndetached\n\n";
3876        let result = parse_worktrees_from_str(input);
3877        assert_eq!(result.len(), 2);
3878        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3879        assert_eq!(result[0].ref_name, Some("refs/heads/main".into()));
3880        assert_eq!(result[1].path, PathBuf::from("/home/user/detached"));
3881        assert_eq!(result[1].ref_name, None);
3882        assert_eq!(result[1].sha.as_ref(), "def456");
3883
3884        // Bare repo entry (included with ref_name: None)
3885        let input = "worktree /home/user/bare.git\nHEAD abc123\nbare\n\n\
3886                      worktree /home/user/project\nHEAD def456\nbranch refs/heads/main\n\n";
3887        let result = parse_worktrees_from_str(input);
3888        assert_eq!(result.len(), 2);
3889        assert_eq!(result[0].path, PathBuf::from("/home/user/bare.git"));
3890        assert_eq!(result[0].ref_name, None);
3891        assert_eq!(result[1].path, PathBuf::from("/home/user/project"));
3892        assert_eq!(result[1].ref_name, Some("refs/heads/main".into()));
3893
3894        // Extra porcelain lines (locked, prunable) should be ignored
3895        let input = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n\n\
3896                      worktree /home/user/locked-wt\nHEAD def456\nbranch refs/heads/locked-branch\nlocked\n\n\
3897                      worktree /home/user/prunable-wt\nHEAD 789aaa\nbranch refs/heads/prunable-branch\nprunable\n\n";
3898        let result = parse_worktrees_from_str(input);
3899        assert_eq!(result.len(), 3);
3900        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3901        assert_eq!(result[0].ref_name, Some("refs/heads/main".into()));
3902        assert_eq!(result[1].path, PathBuf::from("/home/user/locked-wt"));
3903        assert_eq!(result[1].ref_name, Some("refs/heads/locked-branch".into()));
3904        assert_eq!(result[2].path, PathBuf::from("/home/user/prunable-wt"));
3905        assert_eq!(
3906            result[2].ref_name,
3907            Some("refs/heads/prunable-branch".into())
3908        );
3909
3910        // Leading/trailing whitespace on lines should be tolerated
3911        let input =
3912            "  worktree /home/user/project  \n  HEAD abc123  \n  branch refs/heads/main  \n\n";
3913        let result = parse_worktrees_from_str(input);
3914        assert_eq!(result.len(), 1);
3915        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3916        assert_eq!(result[0].sha.as_ref(), "abc123");
3917        assert_eq!(result[0].ref_name, Some("refs/heads/main".into()));
3918
3919        // Windows-style line endings should be handled
3920        let input = "worktree /home/user/project\r\nHEAD abc123\r\nbranch refs/heads/main\r\n\r\n";
3921        let result = parse_worktrees_from_str(input);
3922        assert_eq!(result.len(), 1);
3923        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3924        assert_eq!(result[0].sha.as_ref(), "abc123");
3925        assert_eq!(result[0].ref_name, Some("refs/heads/main".into()));
3926    }
3927
3928    #[gpui::test]
3929    async fn test_create_and_list_worktrees(cx: &mut TestAppContext) {
3930        disable_git_global_config();
3931        cx.executor().allow_parking();
3932
3933        let temp_dir = tempfile::tempdir().unwrap();
3934        let repo_dir = temp_dir.path().join("repo");
3935        let worktrees_dir = temp_dir.path().join("worktrees");
3936
3937        fs::create_dir_all(&repo_dir).unwrap();
3938        fs::create_dir_all(&worktrees_dir).unwrap();
3939
3940        git2::Repository::init(&repo_dir).unwrap();
3941
3942        let repo = RealGitRepository::new(
3943            &repo_dir.join(".git"),
3944            None,
3945            Some("git".into()),
3946            cx.executor(),
3947        )
3948        .unwrap();
3949
3950        // Create an initial commit (required for worktrees)
3951        smol::fs::write(repo_dir.join("file.txt"), "content")
3952            .await
3953            .unwrap();
3954        repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
3955            .await
3956            .unwrap();
3957        repo.commit(
3958            "Initial commit".into(),
3959            None,
3960            CommitOptions::default(),
3961            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3962            Arc::new(checkpoint_author_envs()),
3963        )
3964        .await
3965        .unwrap();
3966
3967        // List worktrees — should have just the main one
3968        let worktrees = repo.worktrees().await.unwrap();
3969        assert_eq!(worktrees.len(), 1);
3970        assert_eq!(
3971            worktrees[0].path.canonicalize().unwrap(),
3972            repo_dir.canonicalize().unwrap()
3973        );
3974
3975        let worktree_path = worktrees_dir.join("some-worktree");
3976
3977        // Create a new worktree
3978        repo.create_worktree(
3979            "test-branch".to_string(),
3980            worktree_path.clone(),
3981            Some("HEAD".to_string()),
3982        )
3983        .await
3984        .unwrap();
3985
3986        // List worktrees — should have two
3987        let worktrees = repo.worktrees().await.unwrap();
3988        assert_eq!(worktrees.len(), 2);
3989
3990        let new_worktree = worktrees
3991            .iter()
3992            .find(|w| w.display_name() == "test-branch")
3993            .expect("should find worktree with test-branch");
3994        assert_eq!(
3995            new_worktree.path.canonicalize().unwrap(),
3996            worktree_path.canonicalize().unwrap(),
3997        );
3998    }
3999
4000    #[gpui::test]
4001    async fn test_remove_worktree(cx: &mut TestAppContext) {
4002        disable_git_global_config();
4003        cx.executor().allow_parking();
4004
4005        let temp_dir = tempfile::tempdir().unwrap();
4006        let repo_dir = temp_dir.path().join("repo");
4007        let worktrees_dir = temp_dir.path().join("worktrees");
4008        git2::Repository::init(&repo_dir).unwrap();
4009
4010        let repo = RealGitRepository::new(
4011            &repo_dir.join(".git"),
4012            None,
4013            Some("git".into()),
4014            cx.executor(),
4015        )
4016        .unwrap();
4017
4018        // Create an initial commit
4019        smol::fs::write(repo_dir.join("file.txt"), "content")
4020            .await
4021            .unwrap();
4022        repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
4023            .await
4024            .unwrap();
4025        repo.commit(
4026            "Initial commit".into(),
4027            None,
4028            CommitOptions::default(),
4029            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
4030            Arc::new(checkpoint_author_envs()),
4031        )
4032        .await
4033        .unwrap();
4034
4035        // Create a worktree
4036        let worktree_path = worktrees_dir.join("worktree-to-remove");
4037        repo.create_worktree(
4038            "to-remove".to_string(),
4039            worktree_path.clone(),
4040            Some("HEAD".to_string()),
4041        )
4042        .await
4043        .unwrap();
4044
4045        // Remove the worktree
4046        repo.remove_worktree(worktree_path.clone(), false)
4047            .await
4048            .unwrap();
4049
4050        // Verify the directory is removed
4051        let worktrees = repo.worktrees().await.unwrap();
4052        assert_eq!(worktrees.len(), 1);
4053        assert!(
4054            worktrees.iter().all(|w| w.display_name() != "to-remove"),
4055            "removed worktree should not appear in list"
4056        );
4057        assert!(!worktree_path.exists());
4058
4059        // Create a worktree
4060        let worktree_path = worktrees_dir.join("dirty-wt");
4061        repo.create_worktree(
4062            "dirty-wt".to_string(),
4063            worktree_path.clone(),
4064            Some("HEAD".to_string()),
4065        )
4066        .await
4067        .unwrap();
4068
4069        assert!(worktree_path.exists());
4070
4071        // Add uncommitted changes in the worktree
4072        smol::fs::write(worktree_path.join("dirty-file.txt"), "uncommitted")
4073            .await
4074            .unwrap();
4075
4076        // Non-force removal should fail with dirty worktree
4077        let result = repo.remove_worktree(worktree_path.clone(), false).await;
4078        assert!(
4079            result.is_err(),
4080            "non-force removal of dirty worktree should fail"
4081        );
4082
4083        // Force removal should succeed
4084        repo.remove_worktree(worktree_path.clone(), true)
4085            .await
4086            .unwrap();
4087
4088        let worktrees = repo.worktrees().await.unwrap();
4089        assert_eq!(worktrees.len(), 1);
4090        assert!(!worktree_path.exists());
4091    }
4092
4093    #[gpui::test]
4094    async fn test_rename_worktree(cx: &mut TestAppContext) {
4095        disable_git_global_config();
4096        cx.executor().allow_parking();
4097
4098        let temp_dir = tempfile::tempdir().unwrap();
4099        let repo_dir = temp_dir.path().join("repo");
4100        let worktrees_dir = temp_dir.path().join("worktrees");
4101
4102        git2::Repository::init(&repo_dir).unwrap();
4103
4104        let repo = RealGitRepository::new(
4105            &repo_dir.join(".git"),
4106            None,
4107            Some("git".into()),
4108            cx.executor(),
4109        )
4110        .unwrap();
4111
4112        // Create an initial commit
4113        smol::fs::write(repo_dir.join("file.txt"), "content")
4114            .await
4115            .unwrap();
4116        repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
4117            .await
4118            .unwrap();
4119        repo.commit(
4120            "Initial commit".into(),
4121            None,
4122            CommitOptions::default(),
4123            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
4124            Arc::new(checkpoint_author_envs()),
4125        )
4126        .await
4127        .unwrap();
4128
4129        // Create a worktree
4130        let old_path = worktrees_dir.join("old-worktree-name");
4131        repo.create_worktree(
4132            "old-name".to_string(),
4133            old_path.clone(),
4134            Some("HEAD".to_string()),
4135        )
4136        .await
4137        .unwrap();
4138
4139        assert!(old_path.exists());
4140
4141        // Move the worktree to a new path
4142        let new_path = worktrees_dir.join("new-worktree-name");
4143        repo.rename_worktree(old_path.clone(), new_path.clone())
4144            .await
4145            .unwrap();
4146
4147        // Verify the old path is gone and new path exists
4148        assert!(!old_path.exists());
4149        assert!(new_path.exists());
4150
4151        // Verify it shows up in worktree list at the new path
4152        let worktrees = repo.worktrees().await.unwrap();
4153        assert_eq!(worktrees.len(), 2);
4154        let moved_worktree = worktrees
4155            .iter()
4156            .find(|w| w.display_name() == "old-name")
4157            .expect("should find worktree by branch name");
4158        assert_eq!(
4159            moved_worktree.path.canonicalize().unwrap(),
4160            new_path.canonicalize().unwrap()
4161        );
4162    }
4163
4164    #[test]
4165    fn test_original_repo_path_from_common_dir() {
4166        // Normal repo: common_dir is <work_dir>/.git
4167        assert_eq!(
4168            original_repo_path_from_common_dir(Path::new("/code/zed5/.git")),
4169            PathBuf::from("/code/zed5")
4170        );
4171
4172        // Worktree: common_dir is the main repo's .git
4173        // (same result — that's the point, it always traces back to the original)
4174        assert_eq!(
4175            original_repo_path_from_common_dir(Path::new("/code/zed5/.git")),
4176            PathBuf::from("/code/zed5")
4177        );
4178
4179        // Bare repo: no .git suffix, returns as-is
4180        assert_eq!(
4181            original_repo_path_from_common_dir(Path::new("/code/zed5.git")),
4182            PathBuf::from("/code/zed5.git")
4183        );
4184
4185        // Root-level .git directory
4186        assert_eq!(
4187            original_repo_path_from_common_dir(Path::new("/.git")),
4188            PathBuf::from("/")
4189        );
4190    }
4191
4192    impl RealGitRepository {
4193        /// Force a Git garbage collection on the repository.
4194        fn gc(&self) -> BoxFuture<'_, Result<()>> {
4195            let working_directory = self.working_directory();
4196            let git_directory = self.path();
4197            let git_binary_path = self.any_git_binary_path.clone();
4198            let executor = self.executor.clone();
4199            self.executor
4200                .spawn(async move {
4201                    let git_binary_path = git_binary_path.clone();
4202                    let working_directory = working_directory?;
4203                    let git = GitBinary::new(
4204                        git_binary_path,
4205                        working_directory,
4206                        git_directory,
4207                        executor,
4208                        true,
4209                    );
4210                    git.run(&["gc", "--prune"]).await?;
4211                    Ok(())
4212                })
4213                .boxed()
4214        }
4215    }
4216}