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