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