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, 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    ) -> Option<Self> {
1004        let any_git_binary_path = system_git_binary_path.clone().or(bundled_git_binary_path)?;
1005        let workdir_root = dotgit_path.parent()?;
1006        let repository = git2::Repository::open(workdir_root).log_err()?;
1007        Some(Self {
1008            repository: Arc::new(Mutex::new(repository)),
1009            system_git_binary_path,
1010            any_git_binary_path,
1011            executor,
1012            any_git_binary_help_output: Arc::new(Mutex::new(None)),
1013            is_trusted: Arc::new(AtomicBool::new(false)),
1014        })
1015    }
1016
1017    fn working_directory(&self) -> Result<PathBuf> {
1018        self.repository
1019            .lock()
1020            .workdir()
1021            .context("failed to read git work directory")
1022            .map(Path::to_path_buf)
1023    }
1024
1025    fn git_binary(&self) -> Result<GitBinary> {
1026        Ok(GitBinary::new(
1027            self.any_git_binary_path.clone(),
1028            self.working_directory()
1029                .with_context(|| "Can't run git commands without a working directory")?,
1030            self.executor.clone(),
1031            self.is_trusted(),
1032        ))
1033    }
1034
1035    async fn any_git_binary_help_output(&self) -> SharedString {
1036        if let Some(output) = self.any_git_binary_help_output.lock().clone() {
1037            return output;
1038        }
1039        let git_binary = self.git_binary();
1040        let output: SharedString = self
1041            .executor
1042            .spawn(async move { git_binary?.run(["help", "-a"]).await })
1043            .await
1044            .unwrap_or_default()
1045            .into();
1046        *self.any_git_binary_help_output.lock() = Some(output.clone());
1047        output
1048    }
1049}
1050
1051#[derive(Clone, Debug)]
1052pub struct GitRepositoryCheckpoint {
1053    pub commit_sha: Oid,
1054}
1055
1056#[derive(Debug)]
1057pub struct GitCommitter {
1058    pub name: Option<String>,
1059    pub email: Option<String>,
1060}
1061
1062pub async fn get_git_committer(cx: &AsyncApp) -> GitCommitter {
1063    if cfg!(any(feature = "test-support", test)) {
1064        return GitCommitter {
1065            name: None,
1066            email: None,
1067        };
1068    }
1069
1070    let git_binary_path =
1071        if cfg!(target_os = "macos") && option_env!("ZED_BUNDLE").as_deref() == Some("true") {
1072            cx.update(|cx| {
1073                cx.path_for_auxiliary_executable("git")
1074                    .context("could not find git binary path")
1075                    .log_err()
1076            })
1077        } else {
1078            None
1079        };
1080
1081    let git = GitBinary::new(
1082        git_binary_path.unwrap_or(PathBuf::from("git")),
1083        paths::home_dir().clone(),
1084        cx.background_executor().clone(),
1085        true,
1086    );
1087
1088    cx.background_spawn(async move {
1089        let name = git.run(["config", "--global", "user.name"]).await.log_err();
1090        let email = git
1091            .run(["config", "--global", "user.email"])
1092            .await
1093            .log_err();
1094        GitCommitter { name, email }
1095    })
1096    .await
1097}
1098
1099impl GitRepository for RealGitRepository {
1100    fn reload_index(&self) {
1101        if let Ok(mut index) = self.repository.lock().index() {
1102            _ = index.read(false);
1103        }
1104    }
1105
1106    fn path(&self) -> PathBuf {
1107        let repo = self.repository.lock();
1108        repo.path().into()
1109    }
1110
1111    fn main_repository_path(&self) -> PathBuf {
1112        let repo = self.repository.lock();
1113        repo.commondir().into()
1114    }
1115
1116    fn show(&self, commit: String) -> BoxFuture<'_, Result<CommitDetails>> {
1117        let git_binary = self.git_binary();
1118        self.executor
1119            .spawn(async move {
1120                let git = git_binary?;
1121                let output = git
1122                    .build_command([
1123                        "--no-optional-locks",
1124                        "show",
1125                        "--no-patch",
1126                        "--format=%H%x00%B%x00%at%x00%ae%x00%an%x00",
1127                        &commit,
1128                    ])
1129                    .output()
1130                    .await?;
1131                let output = std::str::from_utf8(&output.stdout)?;
1132                let fields = output.split('\0').collect::<Vec<_>>();
1133                if fields.len() != 6 {
1134                    bail!("unexpected git-show output for {commit:?}: {output:?}")
1135                }
1136                let sha = fields[0].to_string().into();
1137                let message = fields[1].to_string().into();
1138                let commit_timestamp = fields[2].parse()?;
1139                let author_email = fields[3].to_string().into();
1140                let author_name = fields[4].to_string().into();
1141                Ok(CommitDetails {
1142                    sha,
1143                    message,
1144                    commit_timestamp,
1145                    author_email,
1146                    author_name,
1147                })
1148            })
1149            .boxed()
1150    }
1151
1152    fn load_commit(&self, commit: String, cx: AsyncApp) -> BoxFuture<'_, Result<CommitDiff>> {
1153        if self.repository.lock().workdir().is_none() {
1154            return future::ready(Err(anyhow!("no working directory"))).boxed();
1155        }
1156        let git_binary = self.git_binary();
1157        cx.background_spawn(async move {
1158            let git = git_binary?;
1159            let show_output = git
1160                .build_command([
1161                    "--no-optional-locks",
1162                    "show",
1163                    "--format=",
1164                    "-z",
1165                    "--no-renames",
1166                    "--name-status",
1167                    "--first-parent",
1168                ])
1169                .arg(&commit)
1170                .stdin(Stdio::null())
1171                .stdout(Stdio::piped())
1172                .stderr(Stdio::piped())
1173                .output()
1174                .await
1175                .context("starting git show process")?;
1176
1177            let show_stdout = String::from_utf8_lossy(&show_output.stdout);
1178            let changes = parse_git_diff_name_status(&show_stdout);
1179            let parent_sha = format!("{}^", commit);
1180
1181            let mut cat_file_process = git
1182                .build_command(["--no-optional-locks", "cat-file", "--batch=%(objectsize)"])
1183                .stdin(Stdio::piped())
1184                .stdout(Stdio::piped())
1185                .stderr(Stdio::piped())
1186                .spawn()
1187                .context("starting git cat-file process")?;
1188
1189            let mut files = Vec::<CommitFile>::new();
1190            let mut stdin = BufWriter::with_capacity(512, cat_file_process.stdin.take().unwrap());
1191            let mut stdout = BufReader::new(cat_file_process.stdout.take().unwrap());
1192            let mut info_line = String::new();
1193            let mut newline = [b'\0'];
1194            for (path, status_code) in changes {
1195                // git-show outputs `/`-delimited paths even on Windows.
1196                let Some(rel_path) = RelPath::unix(path).log_err() else {
1197                    continue;
1198                };
1199
1200                match status_code {
1201                    StatusCode::Modified => {
1202                        stdin.write_all(commit.as_bytes()).await?;
1203                        stdin.write_all(b":").await?;
1204                        stdin.write_all(path.as_bytes()).await?;
1205                        stdin.write_all(b"\n").await?;
1206                        stdin.write_all(parent_sha.as_bytes()).await?;
1207                        stdin.write_all(b":").await?;
1208                        stdin.write_all(path.as_bytes()).await?;
1209                        stdin.write_all(b"\n").await?;
1210                    }
1211                    StatusCode::Added => {
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                    }
1217                    StatusCode::Deleted => {
1218                        stdin.write_all(parent_sha.as_bytes()).await?;
1219                        stdin.write_all(b":").await?;
1220                        stdin.write_all(path.as_bytes()).await?;
1221                        stdin.write_all(b"\n").await?;
1222                    }
1223                    _ => continue,
1224                }
1225                stdin.flush().await?;
1226
1227                info_line.clear();
1228                stdout.read_line(&mut info_line).await?;
1229
1230                let len = info_line.trim_end().parse().with_context(|| {
1231                    format!("invalid object size output from cat-file {info_line}")
1232                })?;
1233                let mut text_bytes = vec![0; len];
1234                stdout.read_exact(&mut text_bytes).await?;
1235                stdout.read_exact(&mut newline).await?;
1236
1237                let mut old_text = None;
1238                let mut new_text = None;
1239                let mut is_binary = is_binary_content(&text_bytes);
1240                let text = if is_binary {
1241                    String::new()
1242                } else {
1243                    String::from_utf8_lossy(&text_bytes).to_string()
1244                };
1245
1246                match status_code {
1247                    StatusCode::Modified => {
1248                        info_line.clear();
1249                        stdout.read_line(&mut info_line).await?;
1250                        let len = info_line.trim_end().parse().with_context(|| {
1251                            format!("invalid object size output from cat-file {}", info_line)
1252                        })?;
1253                        let mut parent_bytes = vec![0; len];
1254                        stdout.read_exact(&mut parent_bytes).await?;
1255                        stdout.read_exact(&mut newline).await?;
1256                        is_binary = is_binary || is_binary_content(&parent_bytes);
1257                        if is_binary {
1258                            old_text = Some(String::new());
1259                            new_text = Some(String::new());
1260                        } else {
1261                            old_text = Some(String::from_utf8_lossy(&parent_bytes).to_string());
1262                            new_text = Some(text);
1263                        }
1264                    }
1265                    StatusCode::Added => new_text = Some(text),
1266                    StatusCode::Deleted => old_text = Some(text),
1267                    _ => continue,
1268                }
1269
1270                files.push(CommitFile {
1271                    path: RepoPath(Arc::from(rel_path)),
1272                    old_text,
1273                    new_text,
1274                    is_binary,
1275                })
1276            }
1277
1278            Ok(CommitDiff { files })
1279        })
1280        .boxed()
1281    }
1282
1283    fn reset(
1284        &self,
1285        commit: String,
1286        mode: ResetMode,
1287        env: Arc<HashMap<String, String>>,
1288    ) -> BoxFuture<'_, Result<()>> {
1289        let git_binary = self.git_binary();
1290        async move {
1291            let mode_flag = match mode {
1292                ResetMode::Mixed => "--mixed",
1293                ResetMode::Soft => "--soft",
1294            };
1295
1296            let git = git_binary?;
1297            let output = git
1298                .build_command(["reset", mode_flag, &commit])
1299                .envs(env.iter())
1300                .output()
1301                .await?;
1302            anyhow::ensure!(
1303                output.status.success(),
1304                "Failed to reset:\n{}",
1305                String::from_utf8_lossy(&output.stderr),
1306            );
1307            Ok(())
1308        }
1309        .boxed()
1310    }
1311
1312    fn checkout_files(
1313        &self,
1314        commit: String,
1315        paths: Vec<RepoPath>,
1316        env: Arc<HashMap<String, String>>,
1317    ) -> BoxFuture<'_, Result<()>> {
1318        let git_binary = self.git_binary();
1319        async move {
1320            if paths.is_empty() {
1321                return Ok(());
1322            }
1323
1324            let git = git_binary?;
1325            let output = git
1326                .build_command(["checkout", &commit, "--"])
1327                .envs(env.iter())
1328                .args(paths.iter().map(|path| path.as_unix_str()))
1329                .output()
1330                .await?;
1331            anyhow::ensure!(
1332                output.status.success(),
1333                "Failed to checkout files:\n{}",
1334                String::from_utf8_lossy(&output.stderr),
1335            );
1336            Ok(())
1337        }
1338        .boxed()
1339    }
1340
1341    fn load_index_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>> {
1342        // https://git-scm.com/book/en/v2/Git-Internals-Git-Objects
1343        const GIT_MODE_SYMLINK: u32 = 0o120000;
1344
1345        let repo = self.repository.clone();
1346        self.executor
1347            .spawn(async move {
1348                fn logic(repo: &git2::Repository, path: &RepoPath) -> Result<Option<String>> {
1349                    let mut index = repo.index()?;
1350                    index.read(false)?;
1351
1352                    const STAGE_NORMAL: i32 = 0;
1353                    // git2 unwraps internally on empty paths or `.`
1354                    if path.is_empty() {
1355                        bail!("empty path has no index text");
1356                    }
1357                    let Some(entry) = index.get_path(path.as_std_path(), STAGE_NORMAL) else {
1358                        return Ok(None);
1359                    };
1360                    if entry.mode == GIT_MODE_SYMLINK {
1361                        return Ok(None);
1362                    }
1363
1364                    let content = repo.find_blob(entry.id)?.content().to_owned();
1365                    Ok(String::from_utf8(content).ok())
1366                }
1367
1368                logic(&repo.lock(), &path)
1369                    .context("loading index text")
1370                    .log_err()
1371                    .flatten()
1372            })
1373            .boxed()
1374    }
1375
1376    fn load_committed_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>> {
1377        let repo = self.repository.clone();
1378        self.executor
1379            .spawn(async move {
1380                fn logic(repo: &git2::Repository, path: &RepoPath) -> Result<Option<String>> {
1381                    let head = repo.head()?.peel_to_tree()?;
1382                    // git2 unwraps internally on empty paths or `.`
1383                    if path.is_empty() {
1384                        return Err(anyhow!("empty path has no committed text"));
1385                    }
1386                    let Some(entry) = head.get_path(path.as_std_path()).ok() else {
1387                        return Ok(None);
1388                    };
1389                    if entry.filemode() == i32::from(git2::FileMode::Link) {
1390                        return Ok(None);
1391                    }
1392                    let content = repo.find_blob(entry.id())?.content().to_owned();
1393                    Ok(String::from_utf8(content).ok())
1394                }
1395
1396                logic(&repo.lock(), &path)
1397                    .context("loading committed text")
1398                    .log_err()
1399                    .flatten()
1400            })
1401            .boxed()
1402    }
1403
1404    fn load_blob_content(&self, oid: Oid) -> BoxFuture<'_, Result<String>> {
1405        let repo = self.repository.clone();
1406        self.executor
1407            .spawn(async move {
1408                let repo = repo.lock();
1409                let content = repo.find_blob(oid.0)?.content().to_owned();
1410                Ok(String::from_utf8(content)?)
1411            })
1412            .boxed()
1413    }
1414
1415    fn set_index_text(
1416        &self,
1417        path: RepoPath,
1418        content: Option<String>,
1419        env: Arc<HashMap<String, String>>,
1420        is_executable: bool,
1421    ) -> BoxFuture<'_, anyhow::Result<()>> {
1422        let git_binary = self.git_binary();
1423        self.executor
1424            .spawn(async move {
1425                let git = git_binary?;
1426                let mode = if is_executable { "100755" } else { "100644" };
1427
1428                if let Some(content) = content {
1429                    let mut child = git
1430                        .build_command(["hash-object", "-w", "--stdin"])
1431                        .envs(env.iter())
1432                        .stdin(Stdio::piped())
1433                        .stdout(Stdio::piped())
1434                        .spawn()?;
1435                    let mut stdin = child.stdin.take().unwrap();
1436                    stdin.write_all(content.as_bytes()).await?;
1437                    stdin.flush().await?;
1438                    drop(stdin);
1439                    let output = child.output().await?.stdout;
1440                    let sha = str::from_utf8(&output)?.trim();
1441
1442                    log::debug!("indexing SHA: {sha}, path {path:?}");
1443
1444                    let output = git
1445                        .build_command(["update-index", "--add", "--cacheinfo", mode, sha])
1446                        .envs(env.iter())
1447                        .arg(path.as_unix_str())
1448                        .output()
1449                        .await?;
1450
1451                    anyhow::ensure!(
1452                        output.status.success(),
1453                        "Failed to stage:\n{}",
1454                        String::from_utf8_lossy(&output.stderr)
1455                    );
1456                } else {
1457                    log::debug!("removing path {path:?} from the index");
1458                    let output = git
1459                        .build_command(["update-index", "--force-remove"])
1460                        .envs(env.iter())
1461                        .arg(path.as_unix_str())
1462                        .output()
1463                        .await?;
1464                    anyhow::ensure!(
1465                        output.status.success(),
1466                        "Failed to unstage:\n{}",
1467                        String::from_utf8_lossy(&output.stderr)
1468                    );
1469                }
1470
1471                Ok(())
1472            })
1473            .boxed()
1474    }
1475
1476    fn remote_url(&self, name: &str) -> BoxFuture<'_, Option<String>> {
1477        let repo = self.repository.clone();
1478        let name = name.to_owned();
1479        self.executor
1480            .spawn(async move {
1481                let repo = repo.lock();
1482                let remote = repo.find_remote(&name).ok()?;
1483                remote.url().map(|url| url.to_string())
1484            })
1485            .boxed()
1486    }
1487
1488    fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<'_, Result<Vec<Option<String>>>> {
1489        let git_binary = self.git_binary();
1490        self.executor
1491            .spawn(async move {
1492                let git = git_binary?;
1493                let mut process = git
1494                    .build_command([
1495                        "--no-optional-locks",
1496                        "cat-file",
1497                        "--batch-check=%(objectname)",
1498                    ])
1499                    .stdin(Stdio::piped())
1500                    .stdout(Stdio::piped())
1501                    .stderr(Stdio::piped())
1502                    .spawn()?;
1503
1504                let stdin = process
1505                    .stdin
1506                    .take()
1507                    .context("no stdin for git cat-file subprocess")?;
1508                let mut stdin = BufWriter::new(stdin);
1509                for rev in &revs {
1510                    stdin.write_all(rev.as_bytes()).await?;
1511                    stdin.write_all(b"\n").await?;
1512                }
1513                stdin.flush().await?;
1514                drop(stdin);
1515
1516                let output = process.output().await?;
1517                let output = std::str::from_utf8(&output.stdout)?;
1518                let shas = output
1519                    .lines()
1520                    .map(|line| {
1521                        if line.ends_with("missing") {
1522                            None
1523                        } else {
1524                            Some(line.to_string())
1525                        }
1526                    })
1527                    .collect::<Vec<_>>();
1528
1529                if shas.len() != revs.len() {
1530                    // In an octopus merge, git cat-file still only outputs the first sha from MERGE_HEAD.
1531                    bail!("unexpected number of shas")
1532                }
1533
1534                Ok(shas)
1535            })
1536            .boxed()
1537    }
1538
1539    fn merge_message(&self) -> BoxFuture<'_, Option<String>> {
1540        let path = self.path().join("MERGE_MSG");
1541        self.executor
1542            .spawn(async move { std::fs::read_to_string(&path).ok() })
1543            .boxed()
1544    }
1545
1546    fn status(&self, path_prefixes: &[RepoPath]) -> Task<Result<GitStatus>> {
1547        let git = match self.git_binary() {
1548            Ok(git) => git,
1549            Err(e) => return Task::ready(Err(e)),
1550        };
1551        let args = git_status_args(path_prefixes);
1552        log::debug!("Checking for git status in {path_prefixes:?}");
1553        self.executor.spawn(async move {
1554            let output = git.build_command(args).output().await?;
1555            if output.status.success() {
1556                let stdout = String::from_utf8_lossy(&output.stdout);
1557                stdout.parse()
1558            } else {
1559                let stderr = String::from_utf8_lossy(&output.stderr);
1560                anyhow::bail!("git status failed: {stderr}");
1561            }
1562        })
1563    }
1564
1565    fn diff_tree(&self, request: DiffTreeType) -> BoxFuture<'_, Result<TreeDiff>> {
1566        let git = match self.git_binary() {
1567            Ok(git) => git,
1568            Err(e) => return Task::ready(Err(e)).boxed(),
1569        };
1570
1571        let mut args = vec![
1572            OsString::from("--no-optional-locks"),
1573            OsString::from("diff-tree"),
1574            OsString::from("-r"),
1575            OsString::from("-z"),
1576            OsString::from("--no-renames"),
1577        ];
1578        match request {
1579            DiffTreeType::MergeBase { base, head } => {
1580                args.push("--merge-base".into());
1581                args.push(OsString::from(base.as_str()));
1582                args.push(OsString::from(head.as_str()));
1583            }
1584            DiffTreeType::Since { base, head } => {
1585                args.push(OsString::from(base.as_str()));
1586                args.push(OsString::from(head.as_str()));
1587            }
1588        }
1589
1590        self.executor
1591            .spawn(async move {
1592                let output = git.build_command(args).output().await?;
1593                if output.status.success() {
1594                    let stdout = String::from_utf8_lossy(&output.stdout);
1595                    stdout.parse()
1596                } else {
1597                    let stderr = String::from_utf8_lossy(&output.stderr);
1598                    anyhow::bail!("git status failed: {stderr}");
1599                }
1600            })
1601            .boxed()
1602    }
1603
1604    fn stash_entries(&self) -> BoxFuture<'_, Result<GitStash>> {
1605        let git_binary = self.git_binary();
1606        self.executor
1607            .spawn(async move {
1608                let git = git_binary?;
1609                let output = git
1610                    .build_command(&["stash", "list", "--pretty=format:%gd%x00%H%x00%ct%x00%s"])
1611                    .output()
1612                    .await?;
1613                if output.status.success() {
1614                    let stdout = String::from_utf8_lossy(&output.stdout);
1615                    stdout.parse()
1616                } else {
1617                    let stderr = String::from_utf8_lossy(&output.stderr);
1618                    anyhow::bail!("git status failed: {stderr}");
1619                }
1620            })
1621            .boxed()
1622    }
1623
1624    fn branches(&self) -> BoxFuture<'_, Result<Vec<Branch>>> {
1625        let git_binary = self.git_binary();
1626        self.executor
1627            .spawn(async move {
1628                let fields = [
1629                    "%(HEAD)",
1630                    "%(objectname)",
1631                    "%(parent)",
1632                    "%(refname)",
1633                    "%(upstream)",
1634                    "%(upstream:track)",
1635                    "%(committerdate:unix)",
1636                    "%(authorname)",
1637                    "%(contents:subject)",
1638                ]
1639                .join("%00");
1640                let args = vec![
1641                    "for-each-ref",
1642                    "refs/heads/**/*",
1643                    "refs/remotes/**/*",
1644                    "--format",
1645                    &fields,
1646                ];
1647                let git = git_binary?;
1648                let output = git.build_command(args).output().await?;
1649
1650                anyhow::ensure!(
1651                    output.status.success(),
1652                    "Failed to git git branches:\n{}",
1653                    String::from_utf8_lossy(&output.stderr)
1654                );
1655
1656                let input = String::from_utf8_lossy(&output.stdout);
1657
1658                let mut branches = parse_branch_input(&input)?;
1659                if branches.is_empty() {
1660                    let args = vec!["symbolic-ref", "--quiet", "HEAD"];
1661
1662                    let output = git.build_command(args).output().await?;
1663
1664                    // git symbolic-ref returns a non-0 exit code if HEAD points
1665                    // to something other than a branch
1666                    if output.status.success() {
1667                        let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
1668
1669                        branches.push(Branch {
1670                            ref_name: name.into(),
1671                            is_head: true,
1672                            upstream: None,
1673                            most_recent_commit: None,
1674                        });
1675                    }
1676                }
1677
1678                Ok(branches)
1679            })
1680            .boxed()
1681    }
1682
1683    fn worktrees(&self) -> BoxFuture<'_, Result<Vec<Worktree>>> {
1684        let git_binary = self.git_binary();
1685        self.executor
1686            .spawn(async move {
1687                let git = git_binary?;
1688                let output = git
1689                    .build_command(&["--no-optional-locks", "worktree", "list", "--porcelain"])
1690                    .output()
1691                    .await?;
1692                if output.status.success() {
1693                    let stdout = String::from_utf8_lossy(&output.stdout);
1694                    Ok(parse_worktrees_from_str(&stdout))
1695                } else {
1696                    let stderr = String::from_utf8_lossy(&output.stderr);
1697                    anyhow::bail!("git worktree list failed: {stderr}");
1698                }
1699            })
1700            .boxed()
1701    }
1702
1703    fn create_worktree(
1704        &self,
1705        name: String,
1706        directory: PathBuf,
1707        from_commit: Option<String>,
1708    ) -> BoxFuture<'_, Result<()>> {
1709        let git_binary = self.git_binary();
1710        let final_path = directory.join(&name);
1711        let mut args = vec![
1712            OsString::from("--no-optional-locks"),
1713            OsString::from("worktree"),
1714            OsString::from("add"),
1715            OsString::from("-b"),
1716            OsString::from(name.as_str()),
1717            OsString::from("--"),
1718            OsString::from(final_path.as_os_str()),
1719        ];
1720        if let Some(from_commit) = from_commit {
1721            args.push(OsString::from(from_commit));
1722        } else {
1723            args.push(OsString::from("HEAD"));
1724        }
1725
1726        self.executor
1727            .spawn(async move {
1728                std::fs::create_dir_all(final_path.parent().unwrap_or(&final_path))?;
1729                let git = git_binary?;
1730                let output = git.build_command(args).output().await?;
1731                if output.status.success() {
1732                    Ok(())
1733                } else {
1734                    let stderr = String::from_utf8_lossy(&output.stderr);
1735                    anyhow::bail!("git worktree add failed: {stderr}");
1736                }
1737            })
1738            .boxed()
1739    }
1740
1741    fn remove_worktree(&self, path: PathBuf, force: bool) -> BoxFuture<'_, Result<()>> {
1742        let git_binary = self.git_binary();
1743
1744        self.executor
1745            .spawn(async move {
1746                let mut args: Vec<OsString> = vec![
1747                    "--no-optional-locks".into(),
1748                    "worktree".into(),
1749                    "remove".into(),
1750                ];
1751                if force {
1752                    args.push("--force".into());
1753                }
1754                args.push("--".into());
1755                args.push(path.as_os_str().into());
1756                git_binary?.run(args).await?;
1757                anyhow::Ok(())
1758            })
1759            .boxed()
1760    }
1761
1762    fn rename_worktree(&self, old_path: PathBuf, new_path: PathBuf) -> BoxFuture<'_, Result<()>> {
1763        let git_binary = self.git_binary();
1764
1765        self.executor
1766            .spawn(async move {
1767                let args: Vec<OsString> = vec![
1768                    "--no-optional-locks".into(),
1769                    "worktree".into(),
1770                    "move".into(),
1771                    "--".into(),
1772                    old_path.as_os_str().into(),
1773                    new_path.as_os_str().into(),
1774                ];
1775                git_binary?.run(args).await?;
1776                anyhow::Ok(())
1777            })
1778            .boxed()
1779    }
1780
1781    fn change_branch(&self, name: String) -> BoxFuture<'_, Result<()>> {
1782        let repo = self.repository.clone();
1783        let git_binary = self.git_binary();
1784        let branch = self.executor.spawn(async move {
1785            let repo = repo.lock();
1786            let branch = if let Ok(branch) = repo.find_branch(&name, BranchType::Local) {
1787                branch
1788            } else if let Ok(revision) = repo.find_branch(&name, BranchType::Remote) {
1789                let (_, branch_name) = name.split_once("/").context("Unexpected branch format")?;
1790
1791                let revision = revision.get();
1792                let branch_commit = revision.peel_to_commit()?;
1793                let mut branch = match repo.branch(&branch_name, &branch_commit, false) {
1794                    Ok(branch) => branch,
1795                    Err(err) if err.code() == ErrorCode::Exists => {
1796                        repo.find_branch(&branch_name, BranchType::Local)?
1797                    }
1798                    Err(err) => {
1799                        return Err(err.into());
1800                    }
1801                };
1802
1803                branch.set_upstream(Some(&name))?;
1804                branch
1805            } else {
1806                anyhow::bail!("Branch '{}' not found", name);
1807            };
1808
1809            Ok(branch
1810                .name()?
1811                .context("cannot checkout anonymous branch")?
1812                .to_string())
1813        });
1814
1815        self.executor
1816            .spawn(async move {
1817                let branch = branch.await?;
1818                git_binary?.run(&["checkout", &branch]).await?;
1819                anyhow::Ok(())
1820            })
1821            .boxed()
1822    }
1823
1824    fn create_branch(
1825        &self,
1826        name: String,
1827        base_branch: Option<String>,
1828    ) -> BoxFuture<'_, Result<()>> {
1829        let git_binary = self.git_binary();
1830
1831        self.executor
1832            .spawn(async move {
1833                let mut args = vec!["switch", "-c", &name];
1834                let base_branch_str;
1835                if let Some(ref base) = base_branch {
1836                    base_branch_str = base.clone();
1837                    args.push(&base_branch_str);
1838                }
1839
1840                git_binary?.run(&args).await?;
1841                anyhow::Ok(())
1842            })
1843            .boxed()
1844    }
1845
1846    fn rename_branch(&self, branch: String, new_name: String) -> BoxFuture<'_, Result<()>> {
1847        let git_binary = self.git_binary();
1848
1849        self.executor
1850            .spawn(async move {
1851                git_binary?
1852                    .run(&["branch", "-m", &branch, &new_name])
1853                    .await?;
1854                anyhow::Ok(())
1855            })
1856            .boxed()
1857    }
1858
1859    fn delete_branch(&self, name: String) -> BoxFuture<'_, Result<()>> {
1860        let git_binary = self.git_binary();
1861
1862        self.executor
1863            .spawn(async move {
1864                git_binary?.run(&["branch", "-d", &name]).await?;
1865                anyhow::Ok(())
1866            })
1867            .boxed()
1868    }
1869
1870    fn blame(
1871        &self,
1872        path: RepoPath,
1873        content: Rope,
1874        line_ending: LineEnding,
1875    ) -> BoxFuture<'_, Result<crate::blame::Blame>> {
1876        let git = self.git_binary();
1877
1878        self.executor
1879            .spawn(async move {
1880                crate::blame::Blame::for_path(&git?, &path, &content, line_ending).await
1881            })
1882            .boxed()
1883    }
1884
1885    fn file_history(&self, path: RepoPath) -> BoxFuture<'_, Result<FileHistory>> {
1886        self.file_history_paginated(path, 0, None)
1887    }
1888
1889    fn file_history_paginated(
1890        &self,
1891        path: RepoPath,
1892        skip: usize,
1893        limit: Option<usize>,
1894    ) -> BoxFuture<'_, Result<FileHistory>> {
1895        let git_binary = self.git_binary();
1896        self.executor
1897            .spawn(async move {
1898                let git = git_binary?;
1899                // Use a unique delimiter with a hardcoded UUID to separate commits
1900                // This essentially eliminates any chance of encountering the delimiter in actual commit data
1901                let commit_delimiter =
1902                    concat!("<<COMMIT_END-", "3f8a9c2e-7d4b-4e1a-9f6c-8b5d2a1e4c3f>>",);
1903
1904                let format_string = format!(
1905                    "--pretty=format:%H%x00%s%x00%B%x00%at%x00%an%x00%ae{}",
1906                    commit_delimiter
1907                );
1908
1909                let mut args = vec!["--no-optional-locks", "log", "--follow", &format_string];
1910
1911                let skip_str;
1912                let limit_str;
1913                if skip > 0 {
1914                    skip_str = skip.to_string();
1915                    args.push("--skip");
1916                    args.push(&skip_str);
1917                }
1918                if let Some(n) = limit {
1919                    limit_str = n.to_string();
1920                    args.push("-n");
1921                    args.push(&limit_str);
1922                }
1923
1924                args.push("--");
1925
1926                let output = git
1927                    .build_command(&args)
1928                    .arg(path.as_unix_str())
1929                    .output()
1930                    .await?;
1931
1932                if !output.status.success() {
1933                    let stderr = String::from_utf8_lossy(&output.stderr);
1934                    bail!("git log failed: {stderr}");
1935                }
1936
1937                let stdout = std::str::from_utf8(&output.stdout)?;
1938                let mut entries = Vec::new();
1939
1940                for commit_block in stdout.split(commit_delimiter) {
1941                    let commit_block = commit_block.trim();
1942                    if commit_block.is_empty() {
1943                        continue;
1944                    }
1945
1946                    let fields: Vec<&str> = commit_block.split('\0').collect();
1947                    if fields.len() >= 6 {
1948                        let sha = fields[0].trim().to_string().into();
1949                        let subject = fields[1].trim().to_string().into();
1950                        let message = fields[2].trim().to_string().into();
1951                        let commit_timestamp = fields[3].trim().parse().unwrap_or(0);
1952                        let author_name = fields[4].trim().to_string().into();
1953                        let author_email = fields[5].trim().to_string().into();
1954
1955                        entries.push(FileHistoryEntry {
1956                            sha,
1957                            subject,
1958                            message,
1959                            commit_timestamp,
1960                            author_name,
1961                            author_email,
1962                        });
1963                    }
1964                }
1965
1966                Ok(FileHistory { entries, path })
1967            })
1968            .boxed()
1969    }
1970
1971    fn diff(&self, diff: DiffType) -> BoxFuture<'_, Result<String>> {
1972        let git_binary = self.git_binary();
1973        self.executor
1974            .spawn(async move {
1975                let git = git_binary?;
1976                let output = match diff {
1977                    DiffType::HeadToIndex => {
1978                        git.build_command(["diff", "--staged"]).output().await?
1979                    }
1980                    DiffType::HeadToWorktree => git.build_command(["diff"]).output().await?,
1981                    DiffType::MergeBase { base_ref } => {
1982                        git.build_command(["diff", "--merge-base", base_ref.as_ref()])
1983                            .output()
1984                            .await?
1985                    }
1986                };
1987
1988                anyhow::ensure!(
1989                    output.status.success(),
1990                    "Failed to run git diff:\n{}",
1991                    String::from_utf8_lossy(&output.stderr)
1992                );
1993                Ok(String::from_utf8_lossy(&output.stdout).to_string())
1994            })
1995            .boxed()
1996    }
1997
1998    fn diff_stat(
1999        &self,
2000        path_prefixes: &[RepoPath],
2001    ) -> BoxFuture<'_, Result<crate::status::GitDiffStat>> {
2002        let path_prefixes = path_prefixes.to_vec();
2003        let git_binary = self.git_binary();
2004
2005        self.executor
2006            .spawn(async move {
2007                let git_binary = git_binary?;
2008                let mut args: Vec<String> = vec![
2009                    "diff".into(),
2010                    "--numstat".into(),
2011                    "--no-renames".into(),
2012                    "HEAD".into(),
2013                ];
2014                if !path_prefixes.is_empty() {
2015                    args.push("--".into());
2016                    args.extend(
2017                        path_prefixes
2018                            .iter()
2019                            .map(|p| p.as_std_path().to_string_lossy().into_owned()),
2020                    );
2021                }
2022                let output = git_binary.run(&args).await?;
2023                Ok(crate::status::parse_numstat(&output))
2024            })
2025            .boxed()
2026    }
2027
2028    fn stage_paths(
2029        &self,
2030        paths: Vec<RepoPath>,
2031        env: Arc<HashMap<String, String>>,
2032    ) -> BoxFuture<'_, Result<()>> {
2033        let git_binary = self.git_binary();
2034        self.executor
2035            .spawn(async move {
2036                if !paths.is_empty() {
2037                    let git = git_binary?;
2038                    let output = git
2039                        .build_command(["update-index", "--add", "--remove", "--"])
2040                        .envs(env.iter())
2041                        .args(paths.iter().map(|p| p.as_unix_str()))
2042                        .output()
2043                        .await?;
2044                    anyhow::ensure!(
2045                        output.status.success(),
2046                        "Failed to stage paths:\n{}",
2047                        String::from_utf8_lossy(&output.stderr),
2048                    );
2049                }
2050                Ok(())
2051            })
2052            .boxed()
2053    }
2054
2055    fn unstage_paths(
2056        &self,
2057        paths: Vec<RepoPath>,
2058        env: Arc<HashMap<String, String>>,
2059    ) -> BoxFuture<'_, Result<()>> {
2060        let git_binary = self.git_binary();
2061
2062        self.executor
2063            .spawn(async move {
2064                if !paths.is_empty() {
2065                    let git = git_binary?;
2066                    let output = git
2067                        .build_command(["reset", "--quiet", "--"])
2068                        .envs(env.iter())
2069                        .args(paths.iter().map(|p| p.as_std_path()))
2070                        .output()
2071                        .await?;
2072
2073                    anyhow::ensure!(
2074                        output.status.success(),
2075                        "Failed to unstage:\n{}",
2076                        String::from_utf8_lossy(&output.stderr),
2077                    );
2078                }
2079                Ok(())
2080            })
2081            .boxed()
2082    }
2083
2084    fn stash_paths(
2085        &self,
2086        paths: Vec<RepoPath>,
2087        env: Arc<HashMap<String, String>>,
2088    ) -> BoxFuture<'_, Result<()>> {
2089        let git_binary = self.git_binary();
2090        self.executor
2091            .spawn(async move {
2092                let git = git_binary?;
2093                let output = git
2094                    .build_command(["stash", "push", "--quiet", "--include-untracked"])
2095                    .envs(env.iter())
2096                    .args(paths.iter().map(|p| p.as_unix_str()))
2097                    .output()
2098                    .await?;
2099
2100                anyhow::ensure!(
2101                    output.status.success(),
2102                    "Failed to stash:\n{}",
2103                    String::from_utf8_lossy(&output.stderr)
2104                );
2105                Ok(())
2106            })
2107            .boxed()
2108    }
2109
2110    fn stash_pop(
2111        &self,
2112        index: Option<usize>,
2113        env: Arc<HashMap<String, String>>,
2114    ) -> BoxFuture<'_, Result<()>> {
2115        let git_binary = self.git_binary();
2116        self.executor
2117            .spawn(async move {
2118                let git = git_binary?;
2119                let mut args = vec!["stash".to_string(), "pop".to_string()];
2120                if let Some(index) = index {
2121                    args.push(format!("stash@{{{}}}", index));
2122                }
2123                let output = git.build_command(&args).envs(env.iter()).output().await?;
2124
2125                anyhow::ensure!(
2126                    output.status.success(),
2127                    "Failed to stash pop:\n{}",
2128                    String::from_utf8_lossy(&output.stderr)
2129                );
2130                Ok(())
2131            })
2132            .boxed()
2133    }
2134
2135    fn stash_apply(
2136        &self,
2137        index: Option<usize>,
2138        env: Arc<HashMap<String, String>>,
2139    ) -> BoxFuture<'_, Result<()>> {
2140        let git_binary = self.git_binary();
2141        self.executor
2142            .spawn(async move {
2143                let git = git_binary?;
2144                let mut args = vec!["stash".to_string(), "apply".to_string()];
2145                if let Some(index) = index {
2146                    args.push(format!("stash@{{{}}}", index));
2147                }
2148                let output = git.build_command(&args).envs(env.iter()).output().await?;
2149
2150                anyhow::ensure!(
2151                    output.status.success(),
2152                    "Failed to apply stash:\n{}",
2153                    String::from_utf8_lossy(&output.stderr)
2154                );
2155                Ok(())
2156            })
2157            .boxed()
2158    }
2159
2160    fn stash_drop(
2161        &self,
2162        index: Option<usize>,
2163        env: Arc<HashMap<String, String>>,
2164    ) -> BoxFuture<'_, Result<()>> {
2165        let git_binary = self.git_binary();
2166        self.executor
2167            .spawn(async move {
2168                let git = git_binary?;
2169                let mut args = vec!["stash".to_string(), "drop".to_string()];
2170                if let Some(index) = index {
2171                    args.push(format!("stash@{{{}}}", index));
2172                }
2173                let output = git.build_command(&args).envs(env.iter()).output().await?;
2174
2175                anyhow::ensure!(
2176                    output.status.success(),
2177                    "Failed to stash drop:\n{}",
2178                    String::from_utf8_lossy(&output.stderr)
2179                );
2180                Ok(())
2181            })
2182            .boxed()
2183    }
2184
2185    fn commit(
2186        &self,
2187        message: SharedString,
2188        name_and_email: Option<(SharedString, SharedString)>,
2189        options: CommitOptions,
2190        ask_pass: AskPassDelegate,
2191        env: Arc<HashMap<String, String>>,
2192    ) -> BoxFuture<'_, Result<()>> {
2193        let git_binary = self.git_binary();
2194        let executor = self.executor.clone();
2195        // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2196        // which we want to block on.
2197        async move {
2198            let git = git_binary?;
2199            let mut cmd = git.build_command(["commit", "--quiet", "-m"]);
2200            cmd.envs(env.iter())
2201                .arg(&message.to_string())
2202                .arg("--cleanup=strip")
2203                .arg("--no-verify")
2204                .stdout(Stdio::piped())
2205                .stderr(Stdio::piped());
2206
2207            if options.amend {
2208                cmd.arg("--amend");
2209            }
2210
2211            if options.signoff {
2212                cmd.arg("--signoff");
2213            }
2214
2215            if let Some((name, email)) = name_and_email {
2216                cmd.arg("--author").arg(&format!("{name} <{email}>"));
2217            }
2218
2219            run_git_command(env, ask_pass, cmd, executor).await?;
2220
2221            Ok(())
2222        }
2223        .boxed()
2224    }
2225
2226    fn push(
2227        &self,
2228        branch_name: String,
2229        remote_branch_name: String,
2230        remote_name: String,
2231        options: Option<PushOptions>,
2232        ask_pass: AskPassDelegate,
2233        env: Arc<HashMap<String, String>>,
2234        cx: AsyncApp,
2235    ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
2236        let working_directory = self.working_directory();
2237        let executor = cx.background_executor().clone();
2238        let git_binary_path = self.system_git_binary_path.clone();
2239        let is_trusted = self.is_trusted();
2240        // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2241        // which we want to block on.
2242        async move {
2243            let git_binary_path = git_binary_path.context("git not found on $PATH, can't push")?;
2244            let working_directory = working_directory?;
2245            let git = GitBinary::new(
2246                git_binary_path,
2247                working_directory,
2248                executor.clone(),
2249                is_trusted,
2250            );
2251            let mut command = git.build_command(["push"]);
2252            command
2253                .envs(env.iter())
2254                .args(options.map(|option| match option {
2255                    PushOptions::SetUpstream => "--set-upstream",
2256                    PushOptions::Force => "--force-with-lease",
2257                }))
2258                .arg(remote_name)
2259                .arg(format!("{}:{}", branch_name, remote_branch_name))
2260                .stdin(Stdio::null())
2261                .stdout(Stdio::piped())
2262                .stderr(Stdio::piped());
2263
2264            run_git_command(env, ask_pass, command, executor).await
2265        }
2266        .boxed()
2267    }
2268
2269    fn pull(
2270        &self,
2271        branch_name: Option<String>,
2272        remote_name: String,
2273        rebase: bool,
2274        ask_pass: AskPassDelegate,
2275        env: Arc<HashMap<String, String>>,
2276        cx: AsyncApp,
2277    ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
2278        let working_directory = self.working_directory();
2279        let executor = cx.background_executor().clone();
2280        let git_binary_path = self.system_git_binary_path.clone();
2281        let is_trusted = self.is_trusted();
2282        // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2283        // which we want to block on.
2284        async move {
2285            let git_binary_path = git_binary_path.context("git not found on $PATH, can't pull")?;
2286            let working_directory = working_directory?;
2287            let git = GitBinary::new(
2288                git_binary_path,
2289                working_directory,
2290                executor.clone(),
2291                is_trusted,
2292            );
2293            let mut command = git.build_command(["pull"]);
2294            command.envs(env.iter());
2295
2296            if rebase {
2297                command.arg("--rebase");
2298            }
2299
2300            command
2301                .arg(remote_name)
2302                .args(branch_name)
2303                .stdout(Stdio::piped())
2304                .stderr(Stdio::piped());
2305
2306            run_git_command(env, ask_pass, command, executor).await
2307        }
2308        .boxed()
2309    }
2310
2311    fn fetch(
2312        &self,
2313        fetch_options: FetchOptions,
2314        ask_pass: AskPassDelegate,
2315        env: Arc<HashMap<String, String>>,
2316        cx: AsyncApp,
2317    ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
2318        let working_directory = self.working_directory();
2319        let remote_name = format!("{}", fetch_options);
2320        let git_binary_path = self.system_git_binary_path.clone();
2321        let executor = cx.background_executor().clone();
2322        let is_trusted = self.is_trusted();
2323        // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2324        // which we want to block on.
2325        async move {
2326            let git_binary_path = git_binary_path.context("git not found on $PATH, can't fetch")?;
2327            let working_directory = working_directory?;
2328            let git = GitBinary::new(
2329                git_binary_path,
2330                working_directory,
2331                executor.clone(),
2332                is_trusted,
2333            );
2334            let mut command = git.build_command(["fetch", &remote_name]);
2335            command
2336                .envs(env.iter())
2337                .stdout(Stdio::piped())
2338                .stderr(Stdio::piped());
2339
2340            run_git_command(env, ask_pass, command, executor).await
2341        }
2342        .boxed()
2343    }
2344
2345    fn get_push_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
2346        let git_binary = self.git_binary();
2347        self.executor
2348            .spawn(async move {
2349                let git = git_binary?;
2350                let output = git
2351                    .build_command(["rev-parse", "--abbrev-ref"])
2352                    .arg(format!("{branch}@{{push}}"))
2353                    .output()
2354                    .await?;
2355                if !output.status.success() {
2356                    return Ok(None);
2357                }
2358                let remote_name = String::from_utf8_lossy(&output.stdout)
2359                    .split('/')
2360                    .next()
2361                    .map(|name| Remote {
2362                        name: name.trim().to_string().into(),
2363                    });
2364
2365                Ok(remote_name)
2366            })
2367            .boxed()
2368    }
2369
2370    fn get_branch_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
2371        let git_binary = self.git_binary();
2372        self.executor
2373            .spawn(async move {
2374                let git = git_binary?;
2375                let output = git
2376                    .build_command(["config", "--get"])
2377                    .arg(format!("branch.{branch}.remote"))
2378                    .output()
2379                    .await?;
2380                if !output.status.success() {
2381                    return Ok(None);
2382                }
2383
2384                let remote_name = String::from_utf8_lossy(&output.stdout);
2385                return Ok(Some(Remote {
2386                    name: remote_name.trim().to_string().into(),
2387                }));
2388            })
2389            .boxed()
2390    }
2391
2392    fn get_all_remotes(&self) -> BoxFuture<'_, Result<Vec<Remote>>> {
2393        let git_binary = self.git_binary();
2394        self.executor
2395            .spawn(async move {
2396                let git = git_binary?;
2397                let output = git.build_command(["remote", "-v"]).output().await?;
2398
2399                anyhow::ensure!(
2400                    output.status.success(),
2401                    "Failed to get all remotes:\n{}",
2402                    String::from_utf8_lossy(&output.stderr)
2403                );
2404                let remote_names: HashSet<Remote> = String::from_utf8_lossy(&output.stdout)
2405                    .lines()
2406                    .filter(|line| !line.is_empty())
2407                    .filter_map(|line| {
2408                        let mut split_line = line.split_whitespace();
2409                        let remote_name = split_line.next()?;
2410
2411                        Some(Remote {
2412                            name: remote_name.trim().to_string().into(),
2413                        })
2414                    })
2415                    .collect();
2416
2417                Ok(remote_names.into_iter().collect())
2418            })
2419            .boxed()
2420    }
2421
2422    fn remove_remote(&self, name: String) -> BoxFuture<'_, Result<()>> {
2423        let repo = self.repository.clone();
2424        self.executor
2425            .spawn(async move {
2426                let repo = repo.lock();
2427                repo.remote_delete(&name)?;
2428
2429                Ok(())
2430            })
2431            .boxed()
2432    }
2433
2434    fn create_remote(&self, name: String, url: String) -> BoxFuture<'_, Result<()>> {
2435        let repo = self.repository.clone();
2436        self.executor
2437            .spawn(async move {
2438                let repo = repo.lock();
2439                repo.remote(&name, url.as_ref())?;
2440                Ok(())
2441            })
2442            .boxed()
2443    }
2444
2445    fn check_for_pushed_commit(&self) -> BoxFuture<'_, Result<Vec<SharedString>>> {
2446        let git_binary = self.git_binary();
2447        self.executor
2448            .spawn(async move {
2449                let git = git_binary?;
2450                let git_cmd = async |args: &[&str]| -> Result<String> {
2451                    let output = git.build_command(args).output().await?;
2452                    anyhow::ensure!(
2453                        output.status.success(),
2454                        String::from_utf8_lossy(&output.stderr).to_string()
2455                    );
2456                    Ok(String::from_utf8(output.stdout)?)
2457                };
2458
2459                let head = git_cmd(&["rev-parse", "HEAD"])
2460                    .await
2461                    .context("Failed to get HEAD")?
2462                    .trim()
2463                    .to_owned();
2464
2465                let mut remote_branches = vec![];
2466                let mut add_if_matching = async |remote_head: &str| {
2467                    if let Ok(merge_base) = git_cmd(&["merge-base", &head, remote_head]).await
2468                        && merge_base.trim() == head
2469                        && let Some(s) = remote_head.strip_prefix("refs/remotes/")
2470                    {
2471                        remote_branches.push(s.to_owned().into());
2472                    }
2473                };
2474
2475                // check the main branch of each remote
2476                let remotes = git_cmd(&["remote"])
2477                    .await
2478                    .context("Failed to get remotes")?;
2479                for remote in remotes.lines() {
2480                    if let Ok(remote_head) =
2481                        git_cmd(&["symbolic-ref", &format!("refs/remotes/{remote}/HEAD")]).await
2482                    {
2483                        add_if_matching(remote_head.trim()).await;
2484                    }
2485                }
2486
2487                // ... and the remote branch that the checked-out one is tracking
2488                if let Ok(remote_head) =
2489                    git_cmd(&["rev-parse", "--symbolic-full-name", "@{u}"]).await
2490                {
2491                    add_if_matching(remote_head.trim()).await;
2492                }
2493
2494                Ok(remote_branches)
2495            })
2496            .boxed()
2497    }
2498
2499    fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>> {
2500        let git_binary = self.git_binary();
2501        self.executor
2502            .spawn(async move {
2503                let mut git = git_binary?.envs(checkpoint_author_envs());
2504                git.with_temp_index(async |git| {
2505                    let head_sha = git.run(&["rev-parse", "HEAD"]).await.ok();
2506                    let mut excludes = exclude_files(git).await?;
2507
2508                    git.run(&["add", "--all"]).await?;
2509                    let tree = git.run(&["write-tree"]).await?;
2510                    let checkpoint_sha = if let Some(head_sha) = head_sha.as_deref() {
2511                        git.run(&["commit-tree", &tree, "-p", head_sha, "-m", "Checkpoint"])
2512                            .await?
2513                    } else {
2514                        git.run(&["commit-tree", &tree, "-m", "Checkpoint"]).await?
2515                    };
2516
2517                    excludes.restore_original().await?;
2518
2519                    Ok(GitRepositoryCheckpoint {
2520                        commit_sha: checkpoint_sha.parse()?,
2521                    })
2522                })
2523                .await
2524            })
2525            .boxed()
2526    }
2527
2528    fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>> {
2529        let git_binary = self.git_binary();
2530        self.executor
2531            .spawn(async move {
2532                let git = git_binary?;
2533                git.run(&[
2534                    "restore",
2535                    "--source",
2536                    &checkpoint.commit_sha.to_string(),
2537                    "--worktree",
2538                    ".",
2539                ])
2540                .await?;
2541
2542                // TODO: We don't track binary and large files anymore,
2543                //       so the following call would delete them.
2544                //       Implement an alternative way to track files added by agent.
2545                //
2546                // git.with_temp_index(async move |git| {
2547                //     git.run(&["read-tree", &checkpoint.commit_sha.to_string()])
2548                //         .await?;
2549                //     git.run(&["clean", "-d", "--force"]).await
2550                // })
2551                // .await?;
2552
2553                Ok(())
2554            })
2555            .boxed()
2556    }
2557
2558    fn compare_checkpoints(
2559        &self,
2560        left: GitRepositoryCheckpoint,
2561        right: GitRepositoryCheckpoint,
2562    ) -> BoxFuture<'_, Result<bool>> {
2563        let git_binary = self.git_binary();
2564        self.executor
2565            .spawn(async move {
2566                let git = git_binary?;
2567                let result = git
2568                    .run(&[
2569                        "diff-tree",
2570                        "--quiet",
2571                        &left.commit_sha.to_string(),
2572                        &right.commit_sha.to_string(),
2573                    ])
2574                    .await;
2575                match result {
2576                    Ok(_) => Ok(true),
2577                    Err(error) => {
2578                        if let Some(GitBinaryCommandError { status, .. }) =
2579                            error.downcast_ref::<GitBinaryCommandError>()
2580                            && status.code() == Some(1)
2581                        {
2582                            return Ok(false);
2583                        }
2584
2585                        Err(error)
2586                    }
2587                }
2588            })
2589            .boxed()
2590    }
2591
2592    fn diff_checkpoints(
2593        &self,
2594        base_checkpoint: GitRepositoryCheckpoint,
2595        target_checkpoint: GitRepositoryCheckpoint,
2596    ) -> BoxFuture<'_, Result<String>> {
2597        let git_binary = self.git_binary();
2598        self.executor
2599            .spawn(async move {
2600                let git = git_binary?;
2601                git.run(&[
2602                    "diff",
2603                    "--find-renames",
2604                    "--patch",
2605                    &base_checkpoint.commit_sha.to_string(),
2606                    &target_checkpoint.commit_sha.to_string(),
2607                ])
2608                .await
2609            })
2610            .boxed()
2611    }
2612
2613    fn default_branch(
2614        &self,
2615        include_remote_name: bool,
2616    ) -> BoxFuture<'_, Result<Option<SharedString>>> {
2617        let git_binary = self.git_binary();
2618        self.executor
2619            .spawn(async move {
2620                let git = git_binary?;
2621
2622                let strip_prefix = if include_remote_name {
2623                    "refs/remotes/"
2624                } else {
2625                    "refs/remotes/upstream/"
2626                };
2627
2628                if let Ok(output) = git
2629                    .run(&["symbolic-ref", "refs/remotes/upstream/HEAD"])
2630                    .await
2631                {
2632                    let output = output
2633                        .strip_prefix(strip_prefix)
2634                        .map(|s| SharedString::from(s.to_owned()));
2635                    return Ok(output);
2636                }
2637
2638                let strip_prefix = if include_remote_name {
2639                    "refs/remotes/"
2640                } else {
2641                    "refs/remotes/origin/"
2642                };
2643
2644                if let Ok(output) = git.run(&["symbolic-ref", "refs/remotes/origin/HEAD"]).await {
2645                    return Ok(output
2646                        .strip_prefix(strip_prefix)
2647                        .map(|s| SharedString::from(s.to_owned())));
2648                }
2649
2650                if let Ok(default_branch) = git.run(&["config", "init.defaultBranch"]).await {
2651                    if git.run(&["rev-parse", &default_branch]).await.is_ok() {
2652                        return Ok(Some(default_branch.into()));
2653                    }
2654                }
2655
2656                if git.run(&["rev-parse", "master"]).await.is_ok() {
2657                    return Ok(Some("master".into()));
2658                }
2659
2660                Ok(None)
2661            })
2662            .boxed()
2663    }
2664
2665    fn run_hook(
2666        &self,
2667        hook: RunHook,
2668        env: Arc<HashMap<String, String>>,
2669    ) -> BoxFuture<'_, Result<()>> {
2670        let git_binary = self.git_binary();
2671        let repository = self.repository.clone();
2672        let help_output = self.any_git_binary_help_output();
2673
2674        // Note: Do not spawn these commands on the background thread, as this causes some git hooks to hang.
2675        async move {
2676            let git = git_binary?;
2677
2678            if !git.is_trusted {
2679                bail!("Can't run git commit hooks in restrictive workspace");
2680            }
2681
2682            let working_directory = git.working_directory.clone();
2683            if !help_output
2684                .await
2685                .lines()
2686                .any(|line| line.trim().starts_with("hook "))
2687            {
2688                let hook_abs_path = repository.lock().path().join("hooks").join(hook.as_str());
2689                if hook_abs_path.is_file() {
2690                    #[allow(clippy::disallowed_methods)]
2691                    let output = new_command(&hook_abs_path)
2692                        .envs(env.iter())
2693                        .current_dir(&working_directory)
2694                        .output()
2695                        .await?;
2696
2697                    if !output.status.success() {
2698                        return Err(GitBinaryCommandError {
2699                            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
2700                            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
2701                            status: output.status,
2702                        }
2703                        .into());
2704                    }
2705                }
2706
2707                return Ok(());
2708            }
2709
2710            let git = git.envs(HashMap::clone(&env));
2711            git.run(&["hook", "run", "--ignore-missing", hook.as_str()])
2712                .await?;
2713            Ok(())
2714        }
2715        .boxed()
2716    }
2717
2718    fn initial_graph_data(
2719        &self,
2720        log_source: LogSource,
2721        log_order: LogOrder,
2722        request_tx: Sender<Vec<Arc<InitialGraphCommitData>>>,
2723    ) -> BoxFuture<'_, Result<()>> {
2724        let git_binary = self.git_binary();
2725
2726        async move {
2727            let git = git_binary?;
2728
2729            let mut command = git.build_command([
2730                "log",
2731                GRAPH_COMMIT_FORMAT,
2732                log_order.as_arg(),
2733                log_source.get_arg()?,
2734            ]);
2735            command.stdout(Stdio::piped());
2736            command.stderr(Stdio::null());
2737
2738            let mut child = command.spawn()?;
2739            let stdout = child.stdout.take().context("failed to get stdout")?;
2740            let mut reader = BufReader::new(stdout);
2741
2742            let mut line_buffer = String::new();
2743            let mut lines: Vec<String> = Vec::with_capacity(GRAPH_CHUNK_SIZE);
2744
2745            loop {
2746                line_buffer.clear();
2747                let bytes_read = reader.read_line(&mut line_buffer).await?;
2748
2749                if bytes_read == 0 {
2750                    if !lines.is_empty() {
2751                        let commits = parse_initial_graph_output(lines.iter().map(|s| s.as_str()));
2752                        if request_tx.send(commits).await.is_err() {
2753                            log::warn!(
2754                                "initial_graph_data: receiver dropped while sending commits"
2755                            );
2756                        }
2757                    }
2758                    break;
2759                }
2760
2761                let line = line_buffer.trim_end_matches('\n').to_string();
2762                lines.push(line);
2763
2764                if lines.len() >= GRAPH_CHUNK_SIZE {
2765                    let commits = parse_initial_graph_output(lines.iter().map(|s| s.as_str()));
2766                    if request_tx.send(commits).await.is_err() {
2767                        log::warn!("initial_graph_data: receiver dropped while streaming commits");
2768                        break;
2769                    }
2770                    lines.clear();
2771                }
2772            }
2773
2774            child.status().await?;
2775            Ok(())
2776        }
2777        .boxed()
2778    }
2779
2780    fn commit_data_reader(&self) -> Result<CommitDataReader> {
2781        let git_binary = self.git_binary()?;
2782
2783        let (request_tx, request_rx) = smol::channel::bounded::<CommitDataRequest>(64);
2784
2785        let task = self.executor.spawn(async move {
2786            if let Err(error) = run_commit_data_reader(git_binary, request_rx).await {
2787                log::error!("commit data reader failed: {error:?}");
2788            }
2789        });
2790
2791        Ok(CommitDataReader {
2792            request_tx,
2793            _task: task,
2794        })
2795    }
2796
2797    fn set_trusted(&self, trusted: bool) {
2798        self.is_trusted
2799            .store(trusted, std::sync::atomic::Ordering::Release);
2800    }
2801
2802    fn is_trusted(&self) -> bool {
2803        self.is_trusted.load(std::sync::atomic::Ordering::Acquire)
2804    }
2805}
2806
2807async fn run_commit_data_reader(
2808    git: GitBinary,
2809    request_rx: smol::channel::Receiver<CommitDataRequest>,
2810) -> Result<()> {
2811    let mut process = git
2812        .build_command(["--no-optional-locks", "cat-file", "--batch"])
2813        .stdin(Stdio::piped())
2814        .stdout(Stdio::piped())
2815        .stderr(Stdio::piped())
2816        .spawn()
2817        .context("starting git cat-file --batch process")?;
2818
2819    let mut stdin = BufWriter::new(process.stdin.take().context("no stdin")?);
2820    let mut stdout = BufReader::new(process.stdout.take().context("no stdout")?);
2821
2822    const MAX_BATCH_SIZE: usize = 64;
2823
2824    while let Ok(first_request) = request_rx.recv().await {
2825        let mut pending_requests = vec![first_request];
2826
2827        while pending_requests.len() < MAX_BATCH_SIZE {
2828            match request_rx.try_recv() {
2829                Ok(request) => pending_requests.push(request),
2830                Err(_) => break,
2831            }
2832        }
2833
2834        for request in &pending_requests {
2835            stdin.write_all(request.sha.to_string().as_bytes()).await?;
2836            stdin.write_all(b"\n").await?;
2837        }
2838        stdin.flush().await?;
2839
2840        for request in pending_requests {
2841            let result = read_single_commit_response(&mut stdout, &request.sha).await;
2842            request.response_tx.send(result).ok();
2843        }
2844    }
2845
2846    drop(stdin);
2847    process.kill().ok();
2848
2849    Ok(())
2850}
2851
2852async fn read_single_commit_response<R: smol::io::AsyncBufRead + Unpin>(
2853    stdout: &mut R,
2854    sha: &Oid,
2855) -> Result<GraphCommitData> {
2856    let mut header_bytes = Vec::new();
2857    stdout.read_until(b'\n', &mut header_bytes).await?;
2858    let header_line = String::from_utf8_lossy(&header_bytes);
2859
2860    let parts: Vec<&str> = header_line.trim().split(' ').collect();
2861    if parts.len() < 3 {
2862        bail!("invalid cat-file header: {header_line}");
2863    }
2864
2865    let object_type = parts[1];
2866    if object_type == "missing" {
2867        bail!("object not found: {}", sha);
2868    }
2869
2870    if object_type != "commit" {
2871        bail!("expected commit object, got {object_type}");
2872    }
2873
2874    let size: usize = parts[2]
2875        .parse()
2876        .with_context(|| format!("invalid object size: {}", parts[2]))?;
2877
2878    let mut content = vec![0u8; size];
2879    stdout.read_exact(&mut content).await?;
2880
2881    let mut newline = [0u8; 1];
2882    stdout.read_exact(&mut newline).await?;
2883
2884    let content_str = String::from_utf8_lossy(&content);
2885    parse_cat_file_commit(*sha, &content_str)
2886        .ok_or_else(|| anyhow!("failed to parse commit {}", sha))
2887}
2888
2889fn parse_initial_graph_output<'a>(
2890    lines: impl Iterator<Item = &'a str>,
2891) -> Vec<Arc<InitialGraphCommitData>> {
2892    lines
2893        .filter(|line| !line.is_empty())
2894        .filter_map(|line| {
2895            // Format: "SHA\x00PARENT1 PARENT2...\x00REF1, REF2, ..."
2896            let mut parts = line.split('\x00');
2897
2898            let sha = Oid::from_str(parts.next()?).ok()?;
2899            let parents_str = parts.next()?;
2900            let parents = parents_str
2901                .split_whitespace()
2902                .filter_map(|p| Oid::from_str(p).ok())
2903                .collect();
2904
2905            let ref_names_str = parts.next().unwrap_or("");
2906            let ref_names = if ref_names_str.is_empty() {
2907                Vec::new()
2908            } else {
2909                ref_names_str
2910                    .split(", ")
2911                    .map(|s| SharedString::from(s.to_string()))
2912                    .collect()
2913            };
2914
2915            Some(Arc::new(InitialGraphCommitData {
2916                sha,
2917                parents,
2918                ref_names,
2919            }))
2920        })
2921        .collect()
2922}
2923
2924fn git_status_args(path_prefixes: &[RepoPath]) -> Vec<OsString> {
2925    let mut args = vec![
2926        OsString::from("--no-optional-locks"),
2927        OsString::from("status"),
2928        OsString::from("--porcelain=v1"),
2929        OsString::from("--untracked-files=all"),
2930        OsString::from("--no-renames"),
2931        OsString::from("-z"),
2932    ];
2933    args.extend(path_prefixes.iter().map(|path_prefix| {
2934        if path_prefix.is_empty() {
2935            Path::new(".").into()
2936        } else {
2937            path_prefix.as_std_path().into()
2938        }
2939    }));
2940    args
2941}
2942
2943/// Temporarily git-ignore commonly ignored files and files over 2MB
2944async fn exclude_files(git: &GitBinary) -> Result<GitExcludeOverride> {
2945    const MAX_SIZE: u64 = 2 * 1024 * 1024; // 2 MB
2946    let mut excludes = git.with_exclude_overrides().await?;
2947    excludes
2948        .add_excludes(include_str!("./checkpoint.gitignore"))
2949        .await?;
2950
2951    let working_directory = git.working_directory.clone();
2952    let untracked_files = git.list_untracked_files().await?;
2953    let excluded_paths = untracked_files.into_iter().map(|path| {
2954        let working_directory = working_directory.clone();
2955        smol::spawn(async move {
2956            let full_path = working_directory.join(path.clone());
2957            match smol::fs::metadata(&full_path).await {
2958                Ok(metadata) if metadata.is_file() && metadata.len() >= MAX_SIZE => {
2959                    Some(PathBuf::from("/").join(path.clone()))
2960                }
2961                _ => None,
2962            }
2963        })
2964    });
2965
2966    let excluded_paths = futures::future::join_all(excluded_paths).await;
2967    let excluded_paths = excluded_paths.into_iter().flatten().collect::<Vec<_>>();
2968
2969    if !excluded_paths.is_empty() {
2970        let exclude_patterns = excluded_paths
2971            .into_iter()
2972            .map(|path| path.to_string_lossy().into_owned())
2973            .collect::<Vec<_>>()
2974            .join("\n");
2975        excludes.add_excludes(&exclude_patterns).await?;
2976    }
2977
2978    Ok(excludes)
2979}
2980
2981pub(crate) struct GitBinary {
2982    git_binary_path: PathBuf,
2983    working_directory: PathBuf,
2984    executor: BackgroundExecutor,
2985    index_file_path: Option<PathBuf>,
2986    envs: HashMap<String, String>,
2987    is_trusted: bool,
2988}
2989
2990impl GitBinary {
2991    pub(crate) fn new(
2992        git_binary_path: PathBuf,
2993        working_directory: PathBuf,
2994        executor: BackgroundExecutor,
2995        is_trusted: bool,
2996    ) -> Self {
2997        Self {
2998            git_binary_path,
2999            working_directory,
3000            executor,
3001            index_file_path: None,
3002            envs: HashMap::default(),
3003            is_trusted,
3004        }
3005    }
3006
3007    async fn list_untracked_files(&self) -> Result<Vec<PathBuf>> {
3008        let status_output = self
3009            .run(&["status", "--porcelain=v1", "--untracked-files=all", "-z"])
3010            .await?;
3011
3012        let paths = status_output
3013            .split('\0')
3014            .filter(|entry| entry.len() >= 3 && entry.starts_with("?? "))
3015            .map(|entry| PathBuf::from(&entry[3..]))
3016            .collect::<Vec<_>>();
3017        Ok(paths)
3018    }
3019
3020    fn envs(mut self, envs: HashMap<String, String>) -> Self {
3021        self.envs = envs;
3022        self
3023    }
3024
3025    pub async fn with_temp_index<R>(
3026        &mut self,
3027        f: impl AsyncFnOnce(&Self) -> Result<R>,
3028    ) -> Result<R> {
3029        let index_file_path = self.path_for_index_id(Uuid::new_v4());
3030
3031        let delete_temp_index = util::defer({
3032            let index_file_path = index_file_path.clone();
3033            let executor = self.executor.clone();
3034            move || {
3035                executor
3036                    .spawn(async move {
3037                        smol::fs::remove_file(index_file_path).await.log_err();
3038                    })
3039                    .detach();
3040            }
3041        });
3042
3043        // Copy the default index file so that Git doesn't have to rebuild the
3044        // whole index from scratch. This might fail if this is an empty repository.
3045        smol::fs::copy(
3046            self.working_directory.join(".git").join("index"),
3047            &index_file_path,
3048        )
3049        .await
3050        .ok();
3051
3052        self.index_file_path = Some(index_file_path.clone());
3053        let result = f(self).await;
3054        self.index_file_path = None;
3055        let result = result?;
3056
3057        smol::fs::remove_file(index_file_path).await.ok();
3058        delete_temp_index.abort();
3059
3060        Ok(result)
3061    }
3062
3063    pub async fn with_exclude_overrides(&self) -> Result<GitExcludeOverride> {
3064        let path = self
3065            .working_directory
3066            .join(".git")
3067            .join("info")
3068            .join("exclude");
3069
3070        GitExcludeOverride::new(path).await
3071    }
3072
3073    fn path_for_index_id(&self, id: Uuid) -> PathBuf {
3074        self.working_directory
3075            .join(".git")
3076            .join(format!("index-{}.tmp", id))
3077    }
3078
3079    pub async fn run<S>(&self, args: impl IntoIterator<Item = S>) -> Result<String>
3080    where
3081        S: AsRef<OsStr>,
3082    {
3083        let mut stdout = self.run_raw(args).await?;
3084        if stdout.chars().last() == Some('\n') {
3085            stdout.pop();
3086        }
3087        Ok(stdout)
3088    }
3089
3090    /// Returns the result of the command without trimming the trailing newline.
3091    pub async fn run_raw<S>(&self, args: impl IntoIterator<Item = S>) -> Result<String>
3092    where
3093        S: AsRef<OsStr>,
3094    {
3095        let mut command = self.build_command(args);
3096        let output = command.output().await?;
3097        anyhow::ensure!(
3098            output.status.success(),
3099            GitBinaryCommandError {
3100                stdout: String::from_utf8_lossy(&output.stdout).to_string(),
3101                stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3102                status: output.status,
3103            }
3104        );
3105        Ok(String::from_utf8(output.stdout)?)
3106    }
3107
3108    #[allow(clippy::disallowed_methods)]
3109    pub(crate) fn build_command<S>(
3110        &self,
3111        args: impl IntoIterator<Item = S>,
3112    ) -> util::command::Command
3113    where
3114        S: AsRef<OsStr>,
3115    {
3116        let mut command = new_command(&self.git_binary_path);
3117        command.current_dir(&self.working_directory);
3118        command.args(["-c", "core.fsmonitor=false"]);
3119        if !self.is_trusted {
3120            command.args(["-c", "core.hooksPath=/dev/null"]);
3121        }
3122        command.args(args);
3123        if let Some(index_file_path) = self.index_file_path.as_ref() {
3124            command.env("GIT_INDEX_FILE", index_file_path);
3125        }
3126        command.envs(&self.envs);
3127        command
3128    }
3129}
3130
3131#[derive(Error, Debug)]
3132#[error("Git command failed:\n{stdout}{stderr}\n")]
3133struct GitBinaryCommandError {
3134    stdout: String,
3135    stderr: String,
3136    status: ExitStatus,
3137}
3138
3139async fn run_git_command(
3140    env: Arc<HashMap<String, String>>,
3141    ask_pass: AskPassDelegate,
3142    mut command: util::command::Command,
3143    executor: BackgroundExecutor,
3144) -> Result<RemoteCommandOutput> {
3145    if env.contains_key("GIT_ASKPASS") {
3146        let git_process = command.spawn()?;
3147        let output = git_process.output().await?;
3148        anyhow::ensure!(
3149            output.status.success(),
3150            "{}",
3151            String::from_utf8_lossy(&output.stderr)
3152        );
3153        Ok(RemoteCommandOutput {
3154            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
3155            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3156        })
3157    } else {
3158        let ask_pass = AskPassSession::new(executor, ask_pass).await?;
3159        command
3160            .env("GIT_ASKPASS", ask_pass.script_path())
3161            .env("SSH_ASKPASS", ask_pass.script_path())
3162            .env("SSH_ASKPASS_REQUIRE", "force");
3163        let git_process = command.spawn()?;
3164
3165        run_askpass_command(ask_pass, git_process).await
3166    }
3167}
3168
3169async fn run_askpass_command(
3170    mut ask_pass: AskPassSession,
3171    git_process: util::command::Child,
3172) -> anyhow::Result<RemoteCommandOutput> {
3173    select_biased! {
3174        result = ask_pass.run().fuse() => {
3175            match result {
3176                AskPassResult::CancelledByUser => {
3177                    Err(anyhow!(REMOTE_CANCELLED_BY_USER))?
3178                }
3179                AskPassResult::Timedout => {
3180                    Err(anyhow!("Connecting to host timed out"))?
3181                }
3182            }
3183        }
3184        output = git_process.output().fuse() => {
3185            let output = output?;
3186            anyhow::ensure!(
3187                output.status.success(),
3188                "{}",
3189                String::from_utf8_lossy(&output.stderr)
3190            );
3191            Ok(RemoteCommandOutput {
3192                stdout: String::from_utf8_lossy(&output.stdout).to_string(),
3193                stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3194            })
3195        }
3196    }
3197}
3198
3199#[derive(Clone, Ord, Hash, PartialOrd, Eq, PartialEq)]
3200pub struct RepoPath(Arc<RelPath>);
3201
3202impl std::fmt::Debug for RepoPath {
3203    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3204        self.0.fmt(f)
3205    }
3206}
3207
3208impl RepoPath {
3209    pub fn new<S: AsRef<str> + ?Sized>(s: &S) -> Result<Self> {
3210        let rel_path = RelPath::unix(s.as_ref())?;
3211        Ok(Self::from_rel_path(rel_path))
3212    }
3213
3214    pub fn from_std_path(path: &Path, path_style: PathStyle) -> Result<Self> {
3215        let rel_path = RelPath::new(path, path_style)?;
3216        Ok(Self::from_rel_path(&rel_path))
3217    }
3218
3219    pub fn from_proto(proto: &str) -> Result<Self> {
3220        let rel_path = RelPath::from_proto(proto)?;
3221        Ok(Self(rel_path))
3222    }
3223
3224    pub fn from_rel_path(path: &RelPath) -> RepoPath {
3225        Self(Arc::from(path))
3226    }
3227
3228    pub fn as_std_path(&self) -> &Path {
3229        // git2 does not like empty paths and our RelPath infra turns `.` into ``
3230        // so undo that here
3231        if self.is_empty() {
3232            Path::new(".")
3233        } else {
3234            self.0.as_std_path()
3235        }
3236    }
3237}
3238
3239#[cfg(any(test, feature = "test-support"))]
3240pub fn repo_path<S: AsRef<str> + ?Sized>(s: &S) -> RepoPath {
3241    RepoPath(RelPath::unix(s.as_ref()).unwrap().into())
3242}
3243
3244impl AsRef<Arc<RelPath>> for RepoPath {
3245    fn as_ref(&self) -> &Arc<RelPath> {
3246        &self.0
3247    }
3248}
3249
3250impl std::ops::Deref for RepoPath {
3251    type Target = RelPath;
3252
3253    fn deref(&self) -> &Self::Target {
3254        &self.0
3255    }
3256}
3257
3258#[derive(Debug)]
3259pub struct RepoPathDescendants<'a>(pub &'a RepoPath);
3260
3261impl MapSeekTarget<RepoPath> for RepoPathDescendants<'_> {
3262    fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
3263        if key.starts_with(self.0) {
3264            Ordering::Greater
3265        } else {
3266            self.0.cmp(key)
3267        }
3268    }
3269}
3270
3271fn parse_branch_input(input: &str) -> Result<Vec<Branch>> {
3272    let mut branches = Vec::new();
3273    for line in input.split('\n') {
3274        if line.is_empty() {
3275            continue;
3276        }
3277        let mut fields = line.split('\x00');
3278        let Some(head) = fields.next() else {
3279            continue;
3280        };
3281        let Some(head_sha) = fields.next().map(|f| f.to_string().into()) else {
3282            continue;
3283        };
3284        let Some(parent_sha) = fields.next().map(|f| f.to_string()) else {
3285            continue;
3286        };
3287        let Some(ref_name) = fields.next().map(|f| f.to_string().into()) else {
3288            continue;
3289        };
3290        let Some(upstream_name) = fields.next().map(|f| f.to_string()) else {
3291            continue;
3292        };
3293        let Some(upstream_tracking) = fields.next().and_then(|f| parse_upstream_track(f).ok())
3294        else {
3295            continue;
3296        };
3297        let Some(commiterdate) = fields.next().and_then(|f| f.parse::<i64>().ok()) else {
3298            continue;
3299        };
3300        let Some(author_name) = fields.next().map(|f| f.to_string().into()) else {
3301            continue;
3302        };
3303        let Some(subject) = fields.next().map(|f| f.to_string().into()) else {
3304            continue;
3305        };
3306
3307        branches.push(Branch {
3308            is_head: head == "*",
3309            ref_name,
3310            most_recent_commit: Some(CommitSummary {
3311                sha: head_sha,
3312                subject,
3313                commit_timestamp: commiterdate,
3314                author_name: author_name,
3315                has_parent: !parent_sha.is_empty(),
3316            }),
3317            upstream: if upstream_name.is_empty() {
3318                None
3319            } else {
3320                Some(Upstream {
3321                    ref_name: upstream_name.into(),
3322                    tracking: upstream_tracking,
3323                })
3324            },
3325        })
3326    }
3327
3328    Ok(branches)
3329}
3330
3331fn parse_upstream_track(upstream_track: &str) -> Result<UpstreamTracking> {
3332    if upstream_track.is_empty() {
3333        return Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
3334            ahead: 0,
3335            behind: 0,
3336        }));
3337    }
3338
3339    let upstream_track = upstream_track.strip_prefix("[").context("missing [")?;
3340    let upstream_track = upstream_track.strip_suffix("]").context("missing [")?;
3341    let mut ahead: u32 = 0;
3342    let mut behind: u32 = 0;
3343    for component in upstream_track.split(", ") {
3344        if component == "gone" {
3345            return Ok(UpstreamTracking::Gone);
3346        }
3347        if let Some(ahead_num) = component.strip_prefix("ahead ") {
3348            ahead = ahead_num.parse::<u32>()?;
3349        }
3350        if let Some(behind_num) = component.strip_prefix("behind ") {
3351            behind = behind_num.parse::<u32>()?;
3352        }
3353    }
3354    Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
3355        ahead,
3356        behind,
3357    }))
3358}
3359
3360fn checkpoint_author_envs() -> HashMap<String, String> {
3361    HashMap::from_iter([
3362        ("GIT_AUTHOR_NAME".to_string(), "Zed".to_string()),
3363        ("GIT_AUTHOR_EMAIL".to_string(), "hi@zed.dev".to_string()),
3364        ("GIT_COMMITTER_NAME".to_string(), "Zed".to_string()),
3365        ("GIT_COMMITTER_EMAIL".to_string(), "hi@zed.dev".to_string()),
3366    ])
3367}
3368
3369#[cfg(test)]
3370mod tests {
3371    use super::*;
3372    use gpui::TestAppContext;
3373
3374    fn disable_git_global_config() {
3375        unsafe {
3376            std::env::set_var("GIT_CONFIG_GLOBAL", "");
3377            std::env::set_var("GIT_CONFIG_SYSTEM", "");
3378        }
3379    }
3380
3381    #[gpui::test]
3382    async fn test_build_command_untrusted_includes_both_safety_args(cx: &mut TestAppContext) {
3383        cx.executor().allow_parking();
3384        let dir = tempfile::tempdir().unwrap();
3385        let git = GitBinary::new(
3386            PathBuf::from("git"),
3387            dir.path().to_path_buf(),
3388            cx.executor(),
3389            false,
3390        );
3391        let output = git
3392            .build_command(["version"])
3393            .output()
3394            .await
3395            .expect("git version should succeed");
3396        assert!(output.status.success());
3397
3398        let git = GitBinary::new(
3399            PathBuf::from("git"),
3400            dir.path().to_path_buf(),
3401            cx.executor(),
3402            false,
3403        );
3404        let output = git
3405            .build_command(["config", "--get", "core.fsmonitor"])
3406            .output()
3407            .await
3408            .expect("git config should run");
3409        let stdout = String::from_utf8_lossy(&output.stdout);
3410        assert_eq!(
3411            stdout.trim(),
3412            "false",
3413            "fsmonitor should be disabled for untrusted repos"
3414        );
3415
3416        git2::Repository::init(dir.path()).unwrap();
3417        let git = GitBinary::new(
3418            PathBuf::from("git"),
3419            dir.path().to_path_buf(),
3420            cx.executor(),
3421            false,
3422        );
3423        let output = git
3424            .build_command(["config", "--get", "core.hooksPath"])
3425            .output()
3426            .await
3427            .expect("git config should run");
3428        let stdout = String::from_utf8_lossy(&output.stdout);
3429        assert_eq!(
3430            stdout.trim(),
3431            "/dev/null",
3432            "hooksPath should be /dev/null for untrusted repos"
3433        );
3434    }
3435
3436    #[gpui::test]
3437    async fn test_build_command_trusted_only_disables_fsmonitor(cx: &mut TestAppContext) {
3438        cx.executor().allow_parking();
3439        let dir = tempfile::tempdir().unwrap();
3440        git2::Repository::init(dir.path()).unwrap();
3441
3442        let git = GitBinary::new(
3443            PathBuf::from("git"),
3444            dir.path().to_path_buf(),
3445            cx.executor(),
3446            true,
3447        );
3448        let output = git
3449            .build_command(["config", "--get", "core.fsmonitor"])
3450            .output()
3451            .await
3452            .expect("git config should run");
3453        let stdout = String::from_utf8_lossy(&output.stdout);
3454        assert_eq!(
3455            stdout.trim(),
3456            "false",
3457            "fsmonitor should be disabled even for trusted repos"
3458        );
3459
3460        let git = GitBinary::new(
3461            PathBuf::from("git"),
3462            dir.path().to_path_buf(),
3463            cx.executor(),
3464            true,
3465        );
3466        let output = git
3467            .build_command(["config", "--get", "core.hooksPath"])
3468            .output()
3469            .await
3470            .expect("git config should run");
3471        assert!(
3472            !output.status.success(),
3473            "hooksPath should NOT be overridden for trusted repos"
3474        );
3475    }
3476
3477    #[gpui::test]
3478    async fn test_checkpoint_basic(cx: &mut TestAppContext) {
3479        disable_git_global_config();
3480
3481        cx.executor().allow_parking();
3482
3483        let repo_dir = tempfile::tempdir().unwrap();
3484
3485        git2::Repository::init(repo_dir.path()).unwrap();
3486        let file_path = repo_dir.path().join("file");
3487        smol::fs::write(&file_path, "initial").await.unwrap();
3488
3489        let repo = RealGitRepository::new(
3490            &repo_dir.path().join(".git"),
3491            None,
3492            Some("git".into()),
3493            cx.executor(),
3494        )
3495        .unwrap();
3496
3497        repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
3498            .await
3499            .unwrap();
3500        repo.commit(
3501            "Initial commit".into(),
3502            None,
3503            CommitOptions::default(),
3504            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3505            Arc::new(checkpoint_author_envs()),
3506        )
3507        .await
3508        .unwrap();
3509
3510        smol::fs::write(&file_path, "modified before checkpoint")
3511            .await
3512            .unwrap();
3513        smol::fs::write(repo_dir.path().join("new_file_before_checkpoint"), "1")
3514            .await
3515            .unwrap();
3516        let checkpoint = repo.checkpoint().await.unwrap();
3517
3518        // Ensure the user can't see any branches after creating a checkpoint.
3519        assert_eq!(repo.branches().await.unwrap().len(), 1);
3520
3521        smol::fs::write(&file_path, "modified after checkpoint")
3522            .await
3523            .unwrap();
3524        repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
3525            .await
3526            .unwrap();
3527        repo.commit(
3528            "Commit after checkpoint".into(),
3529            None,
3530            CommitOptions::default(),
3531            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3532            Arc::new(checkpoint_author_envs()),
3533        )
3534        .await
3535        .unwrap();
3536
3537        smol::fs::remove_file(repo_dir.path().join("new_file_before_checkpoint"))
3538            .await
3539            .unwrap();
3540        smol::fs::write(repo_dir.path().join("new_file_after_checkpoint"), "2")
3541            .await
3542            .unwrap();
3543
3544        // Ensure checkpoint stays alive even after a Git GC.
3545        repo.gc().await.unwrap();
3546        repo.restore_checkpoint(checkpoint.clone()).await.unwrap();
3547
3548        assert_eq!(
3549            smol::fs::read_to_string(&file_path).await.unwrap(),
3550            "modified before checkpoint"
3551        );
3552        assert_eq!(
3553            smol::fs::read_to_string(repo_dir.path().join("new_file_before_checkpoint"))
3554                .await
3555                .unwrap(),
3556            "1"
3557        );
3558        // See TODO above
3559        // assert_eq!(
3560        //     smol::fs::read_to_string(repo_dir.path().join("new_file_after_checkpoint"))
3561        //         .await
3562        //         .ok(),
3563        //     None
3564        // );
3565    }
3566
3567    #[gpui::test]
3568    async fn test_checkpoint_empty_repo(cx: &mut TestAppContext) {
3569        disable_git_global_config();
3570
3571        cx.executor().allow_parking();
3572
3573        let repo_dir = tempfile::tempdir().unwrap();
3574        git2::Repository::init(repo_dir.path()).unwrap();
3575        let repo = RealGitRepository::new(
3576            &repo_dir.path().join(".git"),
3577            None,
3578            Some("git".into()),
3579            cx.executor(),
3580        )
3581        .unwrap();
3582
3583        smol::fs::write(repo_dir.path().join("foo"), "foo")
3584            .await
3585            .unwrap();
3586        let checkpoint_sha = repo.checkpoint().await.unwrap();
3587
3588        // Ensure the user can't see any branches after creating a checkpoint.
3589        assert_eq!(repo.branches().await.unwrap().len(), 1);
3590
3591        smol::fs::write(repo_dir.path().join("foo"), "bar")
3592            .await
3593            .unwrap();
3594        smol::fs::write(repo_dir.path().join("baz"), "qux")
3595            .await
3596            .unwrap();
3597        repo.restore_checkpoint(checkpoint_sha).await.unwrap();
3598        assert_eq!(
3599            smol::fs::read_to_string(repo_dir.path().join("foo"))
3600                .await
3601                .unwrap(),
3602            "foo"
3603        );
3604        // See TODOs above
3605        // assert_eq!(
3606        //     smol::fs::read_to_string(repo_dir.path().join("baz"))
3607        //         .await
3608        //         .ok(),
3609        //     None
3610        // );
3611    }
3612
3613    #[gpui::test]
3614    async fn test_compare_checkpoints(cx: &mut TestAppContext) {
3615        disable_git_global_config();
3616
3617        cx.executor().allow_parking();
3618
3619        let repo_dir = tempfile::tempdir().unwrap();
3620        git2::Repository::init(repo_dir.path()).unwrap();
3621        let repo = RealGitRepository::new(
3622            &repo_dir.path().join(".git"),
3623            None,
3624            Some("git".into()),
3625            cx.executor(),
3626        )
3627        .unwrap();
3628
3629        smol::fs::write(repo_dir.path().join("file1"), "content1")
3630            .await
3631            .unwrap();
3632        let checkpoint1 = repo.checkpoint().await.unwrap();
3633
3634        smol::fs::write(repo_dir.path().join("file2"), "content2")
3635            .await
3636            .unwrap();
3637        let checkpoint2 = repo.checkpoint().await.unwrap();
3638
3639        assert!(
3640            !repo
3641                .compare_checkpoints(checkpoint1, checkpoint2.clone())
3642                .await
3643                .unwrap()
3644        );
3645
3646        let checkpoint3 = repo.checkpoint().await.unwrap();
3647        assert!(
3648            repo.compare_checkpoints(checkpoint2, checkpoint3)
3649                .await
3650                .unwrap()
3651        );
3652    }
3653
3654    #[gpui::test]
3655    async fn test_checkpoint_exclude_binary_files(cx: &mut TestAppContext) {
3656        disable_git_global_config();
3657
3658        cx.executor().allow_parking();
3659
3660        let repo_dir = tempfile::tempdir().unwrap();
3661        let text_path = repo_dir.path().join("main.rs");
3662        let bin_path = repo_dir.path().join("binary.o");
3663
3664        git2::Repository::init(repo_dir.path()).unwrap();
3665
3666        smol::fs::write(&text_path, "fn main() {}").await.unwrap();
3667
3668        smol::fs::write(&bin_path, "some binary file here")
3669            .await
3670            .unwrap();
3671
3672        let repo = RealGitRepository::new(
3673            &repo_dir.path().join(".git"),
3674            None,
3675            Some("git".into()),
3676            cx.executor(),
3677        )
3678        .unwrap();
3679
3680        // initial commit
3681        repo.stage_paths(vec![repo_path("main.rs")], Arc::new(HashMap::default()))
3682            .await
3683            .unwrap();
3684        repo.commit(
3685            "Initial commit".into(),
3686            None,
3687            CommitOptions::default(),
3688            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3689            Arc::new(checkpoint_author_envs()),
3690        )
3691        .await
3692        .unwrap();
3693
3694        let checkpoint = repo.checkpoint().await.unwrap();
3695
3696        smol::fs::write(&text_path, "fn main() { println!(\"Modified\"); }")
3697            .await
3698            .unwrap();
3699        smol::fs::write(&bin_path, "Modified binary file")
3700            .await
3701            .unwrap();
3702
3703        repo.restore_checkpoint(checkpoint).await.unwrap();
3704
3705        // Text files should be restored to checkpoint state,
3706        // but binaries should not (they aren't tracked)
3707        assert_eq!(
3708            smol::fs::read_to_string(&text_path).await.unwrap(),
3709            "fn main() {}"
3710        );
3711
3712        assert_eq!(
3713            smol::fs::read_to_string(&bin_path).await.unwrap(),
3714            "Modified binary file"
3715        );
3716    }
3717
3718    #[test]
3719    fn test_branches_parsing() {
3720        // suppress "help: octal escapes are not supported, `\0` is always null"
3721        #[allow(clippy::octal_escapes)]
3722        let input = "*\0060964da10574cd9bf06463a53bf6e0769c5c45e\0\0refs/heads/zed-patches\0refs/remotes/origin/zed-patches\0\01733187470\0John Doe\0generated protobuf\n";
3723        assert_eq!(
3724            parse_branch_input(input).unwrap(),
3725            vec![Branch {
3726                is_head: true,
3727                ref_name: "refs/heads/zed-patches".into(),
3728                upstream: Some(Upstream {
3729                    ref_name: "refs/remotes/origin/zed-patches".into(),
3730                    tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3731                        ahead: 0,
3732                        behind: 0
3733                    })
3734                }),
3735                most_recent_commit: Some(CommitSummary {
3736                    sha: "060964da10574cd9bf06463a53bf6e0769c5c45e".into(),
3737                    subject: "generated protobuf".into(),
3738                    commit_timestamp: 1733187470,
3739                    author_name: SharedString::new_static("John Doe"),
3740                    has_parent: false,
3741                })
3742            }]
3743        )
3744    }
3745
3746    #[test]
3747    fn test_branches_parsing_containing_refs_with_missing_fields() {
3748        #[allow(clippy::octal_escapes)]
3749        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";
3750
3751        let branches = parse_branch_input(input).unwrap();
3752        assert_eq!(branches.len(), 2);
3753        assert_eq!(
3754            branches,
3755            vec![
3756                Branch {
3757                    is_head: false,
3758                    ref_name: "refs/heads/dev".into(),
3759                    upstream: None,
3760                    most_recent_commit: Some(CommitSummary {
3761                        sha: "eb0cae33272689bd11030822939dd2701c52f81e".into(),
3762                        subject: "Add feature".into(),
3763                        commit_timestamp: 1762948725,
3764                        author_name: SharedString::new_static("Zed"),
3765                        has_parent: true,
3766                    })
3767                },
3768                Branch {
3769                    is_head: true,
3770                    ref_name: "refs/heads/main".into(),
3771                    upstream: None,
3772                    most_recent_commit: Some(CommitSummary {
3773                        sha: "895951d681e5561478c0acdd6905e8aacdfd2249".into(),
3774                        subject: "Initial commit".into(),
3775                        commit_timestamp: 1762948695,
3776                        author_name: SharedString::new_static("Zed"),
3777                        has_parent: false,
3778                    })
3779                }
3780            ]
3781        )
3782    }
3783
3784    #[test]
3785    fn test_upstream_branch_name() {
3786        let upstream = Upstream {
3787            ref_name: "refs/remotes/origin/feature/branch".into(),
3788            tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3789                ahead: 0,
3790                behind: 0,
3791            }),
3792        };
3793        assert_eq!(upstream.branch_name(), Some("feature/branch"));
3794
3795        let upstream = Upstream {
3796            ref_name: "refs/remotes/upstream/main".into(),
3797            tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3798                ahead: 0,
3799                behind: 0,
3800            }),
3801        };
3802        assert_eq!(upstream.branch_name(), Some("main"));
3803
3804        let upstream = Upstream {
3805            ref_name: "refs/heads/local".into(),
3806            tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3807                ahead: 0,
3808                behind: 0,
3809            }),
3810        };
3811        assert_eq!(upstream.branch_name(), None);
3812
3813        // Test case where upstream branch name differs from what might be the local branch name
3814        let upstream = Upstream {
3815            ref_name: "refs/remotes/origin/feature/git-pull-request".into(),
3816            tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3817                ahead: 0,
3818                behind: 0,
3819            }),
3820        };
3821        assert_eq!(upstream.branch_name(), Some("feature/git-pull-request"));
3822    }
3823
3824    #[test]
3825    fn test_parse_worktrees_from_str() {
3826        // Empty input
3827        let result = parse_worktrees_from_str("");
3828        assert!(result.is_empty());
3829
3830        // Single worktree (main)
3831        let input = "worktree /home/user/project\nHEAD abc123def\nbranch refs/heads/main\n\n";
3832        let result = parse_worktrees_from_str(input);
3833        assert_eq!(result.len(), 1);
3834        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3835        assert_eq!(result[0].sha.as_ref(), "abc123def");
3836        assert_eq!(result[0].ref_name.as_ref(), "refs/heads/main");
3837
3838        // Multiple worktrees
3839        let input = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n\n\
3840                      worktree /home/user/project-wt\nHEAD def456\nbranch refs/heads/feature\n\n";
3841        let result = parse_worktrees_from_str(input);
3842        assert_eq!(result.len(), 2);
3843        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3844        assert_eq!(result[0].ref_name.as_ref(), "refs/heads/main");
3845        assert_eq!(result[1].path, PathBuf::from("/home/user/project-wt"));
3846        assert_eq!(result[1].ref_name.as_ref(), "refs/heads/feature");
3847
3848        // Detached HEAD entry (should be skipped since ref_name won't parse)
3849        let input = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n\n\
3850                      worktree /home/user/detached\nHEAD def456\ndetached\n\n";
3851        let result = parse_worktrees_from_str(input);
3852        assert_eq!(result.len(), 1);
3853        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3854
3855        // Bare repo entry (should be skipped)
3856        let input = "worktree /home/user/bare.git\nHEAD abc123\nbare\n\n\
3857                      worktree /home/user/project\nHEAD def456\nbranch refs/heads/main\n\n";
3858        let result = parse_worktrees_from_str(input);
3859        assert_eq!(result.len(), 1);
3860        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3861
3862        // Extra porcelain lines (locked, prunable) should be ignored
3863        let input = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n\n\
3864                      worktree /home/user/locked-wt\nHEAD def456\nbranch refs/heads/locked-branch\nlocked\n\n\
3865                      worktree /home/user/prunable-wt\nHEAD 789aaa\nbranch refs/heads/prunable-branch\nprunable\n\n";
3866        let result = parse_worktrees_from_str(input);
3867        assert_eq!(result.len(), 3);
3868        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3869        assert_eq!(result[0].ref_name.as_ref(), "refs/heads/main");
3870        assert_eq!(result[1].path, PathBuf::from("/home/user/locked-wt"));
3871        assert_eq!(result[1].ref_name.as_ref(), "refs/heads/locked-branch");
3872        assert_eq!(result[2].path, PathBuf::from("/home/user/prunable-wt"));
3873        assert_eq!(result[2].ref_name.as_ref(), "refs/heads/prunable-branch");
3874
3875        // Leading/trailing whitespace on lines should be tolerated
3876        let input =
3877            "  worktree /home/user/project  \n  HEAD abc123  \n  branch refs/heads/main  \n\n";
3878        let result = parse_worktrees_from_str(input);
3879        assert_eq!(result.len(), 1);
3880        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3881        assert_eq!(result[0].sha.as_ref(), "abc123");
3882        assert_eq!(result[0].ref_name.as_ref(), "refs/heads/main");
3883
3884        // Windows-style line endings should be handled
3885        let input = "worktree /home/user/project\r\nHEAD abc123\r\nbranch refs/heads/main\r\n\r\n";
3886        let result = parse_worktrees_from_str(input);
3887        assert_eq!(result.len(), 1);
3888        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3889        assert_eq!(result[0].sha.as_ref(), "abc123");
3890        assert_eq!(result[0].ref_name.as_ref(), "refs/heads/main");
3891    }
3892
3893    const TEST_WORKTREE_DIRECTORIES: &[&str] =
3894        &["../worktrees", ".git/zed-worktrees", "my-worktrees/"];
3895
3896    #[gpui::test]
3897    async fn test_create_and_list_worktrees(cx: &mut TestAppContext) {
3898        disable_git_global_config();
3899        cx.executor().allow_parking();
3900
3901        for worktree_dir_setting in TEST_WORKTREE_DIRECTORIES {
3902            let repo_dir = tempfile::tempdir().unwrap();
3903            git2::Repository::init(repo_dir.path()).unwrap();
3904
3905            let repo = RealGitRepository::new(
3906                &repo_dir.path().join(".git"),
3907                None,
3908                Some("git".into()),
3909                cx.executor(),
3910            )
3911            .unwrap();
3912
3913            // Create an initial commit (required for worktrees)
3914            smol::fs::write(repo_dir.path().join("file.txt"), "content")
3915                .await
3916                .unwrap();
3917            repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
3918                .await
3919                .unwrap();
3920            repo.commit(
3921                "Initial commit".into(),
3922                None,
3923                CommitOptions::default(),
3924                AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3925                Arc::new(checkpoint_author_envs()),
3926            )
3927            .await
3928            .unwrap();
3929
3930            // List worktrees — should have just the main one
3931            let worktrees = repo.worktrees().await.unwrap();
3932            assert_eq!(worktrees.len(), 1);
3933            assert_eq!(
3934                worktrees[0].path.canonicalize().unwrap(),
3935                repo_dir.path().canonicalize().unwrap()
3936            );
3937
3938            // Create a new worktree
3939            repo.create_worktree(
3940                "test-branch".to_string(),
3941                resolve_worktree_directory(repo_dir.path(), worktree_dir_setting),
3942                Some("HEAD".to_string()),
3943            )
3944            .await
3945            .unwrap();
3946
3947            // List worktrees — should have two
3948            let worktrees = repo.worktrees().await.unwrap();
3949            assert_eq!(worktrees.len(), 2);
3950
3951            let expected_path =
3952                worktree_path_for_branch(repo_dir.path(), worktree_dir_setting, "test-branch");
3953            let new_worktree = worktrees
3954                .iter()
3955                .find(|w| w.branch() == "test-branch")
3956                .expect("should find worktree with test-branch");
3957            assert_eq!(
3958                new_worktree.path.canonicalize().unwrap(),
3959                expected_path.canonicalize().unwrap(),
3960                "failed for worktree_directory setting: {worktree_dir_setting:?}"
3961            );
3962
3963            // Clean up so the next iteration starts fresh
3964            repo.remove_worktree(expected_path, true).await.unwrap();
3965
3966            // Clean up the worktree base directory if it was created outside repo_dir
3967            // (e.g. for the "../worktrees" setting, it won't be inside the TempDir)
3968            let resolved_dir = resolve_worktree_directory(repo_dir.path(), worktree_dir_setting);
3969            if !resolved_dir.starts_with(repo_dir.path()) {
3970                let _ = std::fs::remove_dir_all(&resolved_dir);
3971            }
3972        }
3973    }
3974
3975    #[gpui::test]
3976    async fn test_remove_worktree(cx: &mut TestAppContext) {
3977        disable_git_global_config();
3978        cx.executor().allow_parking();
3979
3980        for worktree_dir_setting in TEST_WORKTREE_DIRECTORIES {
3981            let repo_dir = tempfile::tempdir().unwrap();
3982            git2::Repository::init(repo_dir.path()).unwrap();
3983
3984            let repo = RealGitRepository::new(
3985                &repo_dir.path().join(".git"),
3986                None,
3987                Some("git".into()),
3988                cx.executor(),
3989            )
3990            .unwrap();
3991
3992            // Create an initial commit
3993            smol::fs::write(repo_dir.path().join("file.txt"), "content")
3994                .await
3995                .unwrap();
3996            repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
3997                .await
3998                .unwrap();
3999            repo.commit(
4000                "Initial commit".into(),
4001                None,
4002                CommitOptions::default(),
4003                AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
4004                Arc::new(checkpoint_author_envs()),
4005            )
4006            .await
4007            .unwrap();
4008
4009            // Create a worktree
4010            repo.create_worktree(
4011                "to-remove".to_string(),
4012                resolve_worktree_directory(repo_dir.path(), worktree_dir_setting),
4013                Some("HEAD".to_string()),
4014            )
4015            .await
4016            .unwrap();
4017
4018            let worktree_path =
4019                worktree_path_for_branch(repo_dir.path(), worktree_dir_setting, "to-remove");
4020            assert!(worktree_path.exists());
4021
4022            // Remove the worktree
4023            repo.remove_worktree(worktree_path.clone(), false)
4024                .await
4025                .unwrap();
4026
4027            // Verify it's gone from the list
4028            let worktrees = repo.worktrees().await.unwrap();
4029            assert_eq!(worktrees.len(), 1);
4030            assert!(
4031                worktrees.iter().all(|w| w.branch() != "to-remove"),
4032                "removed worktree should not appear in list"
4033            );
4034
4035            // Verify the directory is removed
4036            assert!(!worktree_path.exists());
4037
4038            // Clean up the worktree base directory if it was created outside repo_dir
4039            // (e.g. for the "../worktrees" setting, it won't be inside the TempDir)
4040            let resolved_dir = resolve_worktree_directory(repo_dir.path(), worktree_dir_setting);
4041            if !resolved_dir.starts_with(repo_dir.path()) {
4042                let _ = std::fs::remove_dir_all(&resolved_dir);
4043            }
4044        }
4045    }
4046
4047    #[gpui::test]
4048    async fn test_remove_worktree_force(cx: &mut TestAppContext) {
4049        disable_git_global_config();
4050        cx.executor().allow_parking();
4051
4052        for worktree_dir_setting in TEST_WORKTREE_DIRECTORIES {
4053            let repo_dir = tempfile::tempdir().unwrap();
4054            git2::Repository::init(repo_dir.path()).unwrap();
4055
4056            let repo = RealGitRepository::new(
4057                &repo_dir.path().join(".git"),
4058                None,
4059                Some("git".into()),
4060                cx.executor(),
4061            )
4062            .unwrap();
4063
4064            // Create an initial commit
4065            smol::fs::write(repo_dir.path().join("file.txt"), "content")
4066                .await
4067                .unwrap();
4068            repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
4069                .await
4070                .unwrap();
4071            repo.commit(
4072                "Initial commit".into(),
4073                None,
4074                CommitOptions::default(),
4075                AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
4076                Arc::new(checkpoint_author_envs()),
4077            )
4078            .await
4079            .unwrap();
4080
4081            // Create a worktree
4082            repo.create_worktree(
4083                "dirty-wt".to_string(),
4084                resolve_worktree_directory(repo_dir.path(), worktree_dir_setting),
4085                Some("HEAD".to_string()),
4086            )
4087            .await
4088            .unwrap();
4089
4090            let worktree_path =
4091                worktree_path_for_branch(repo_dir.path(), worktree_dir_setting, "dirty-wt");
4092
4093            // Add uncommitted changes in the worktree
4094            smol::fs::write(worktree_path.join("dirty-file.txt"), "uncommitted")
4095                .await
4096                .unwrap();
4097
4098            // Non-force removal should fail with dirty worktree
4099            let result = repo.remove_worktree(worktree_path.clone(), false).await;
4100            assert!(
4101                result.is_err(),
4102                "non-force removal of dirty worktree should fail"
4103            );
4104
4105            // Force removal should succeed
4106            repo.remove_worktree(worktree_path.clone(), true)
4107                .await
4108                .unwrap();
4109
4110            let worktrees = repo.worktrees().await.unwrap();
4111            assert_eq!(worktrees.len(), 1);
4112            assert!(!worktree_path.exists());
4113
4114            // Clean up the worktree base directory if it was created outside repo_dir
4115            // (e.g. for the "../worktrees" setting, it won't be inside the TempDir)
4116            let resolved_dir = resolve_worktree_directory(repo_dir.path(), worktree_dir_setting);
4117            if !resolved_dir.starts_with(repo_dir.path()) {
4118                let _ = std::fs::remove_dir_all(&resolved_dir);
4119            }
4120        }
4121    }
4122
4123    #[gpui::test]
4124    async fn test_rename_worktree(cx: &mut TestAppContext) {
4125        disable_git_global_config();
4126        cx.executor().allow_parking();
4127
4128        for worktree_dir_setting in TEST_WORKTREE_DIRECTORIES {
4129            let repo_dir = tempfile::tempdir().unwrap();
4130            git2::Repository::init(repo_dir.path()).unwrap();
4131
4132            let repo = RealGitRepository::new(
4133                &repo_dir.path().join(".git"),
4134                None,
4135                Some("git".into()),
4136                cx.executor(),
4137            )
4138            .unwrap();
4139
4140            // Create an initial commit
4141            smol::fs::write(repo_dir.path().join("file.txt"), "content")
4142                .await
4143                .unwrap();
4144            repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
4145                .await
4146                .unwrap();
4147            repo.commit(
4148                "Initial commit".into(),
4149                None,
4150                CommitOptions::default(),
4151                AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
4152                Arc::new(checkpoint_author_envs()),
4153            )
4154            .await
4155            .unwrap();
4156
4157            // Create a worktree
4158            repo.create_worktree(
4159                "old-name".to_string(),
4160                resolve_worktree_directory(repo_dir.path(), worktree_dir_setting),
4161                Some("HEAD".to_string()),
4162            )
4163            .await
4164            .unwrap();
4165
4166            let old_path =
4167                worktree_path_for_branch(repo_dir.path(), worktree_dir_setting, "old-name");
4168            assert!(old_path.exists());
4169
4170            // Move the worktree to a new path
4171            let new_path =
4172                resolve_worktree_directory(repo_dir.path(), worktree_dir_setting).join("new-name");
4173            repo.rename_worktree(old_path.clone(), new_path.clone())
4174                .await
4175                .unwrap();
4176
4177            // Verify the old path is gone and new path exists
4178            assert!(!old_path.exists());
4179            assert!(new_path.exists());
4180
4181            // Verify it shows up in worktree list at the new path
4182            let worktrees = repo.worktrees().await.unwrap();
4183            assert_eq!(worktrees.len(), 2);
4184            let moved_worktree = worktrees
4185                .iter()
4186                .find(|w| w.branch() == "old-name")
4187                .expect("should find worktree by branch name");
4188            assert_eq!(
4189                moved_worktree.path.canonicalize().unwrap(),
4190                new_path.canonicalize().unwrap()
4191            );
4192
4193            // Clean up so the next iteration starts fresh
4194            repo.remove_worktree(new_path, true).await.unwrap();
4195
4196            // Clean up the worktree base directory if it was created outside repo_dir
4197            // (e.g. for the "../worktrees" setting, it won't be inside the TempDir)
4198            let resolved_dir = resolve_worktree_directory(repo_dir.path(), worktree_dir_setting);
4199            if !resolved_dir.starts_with(repo_dir.path()) {
4200                let _ = std::fs::remove_dir_all(&resolved_dir);
4201            }
4202        }
4203    }
4204
4205    #[test]
4206    fn test_resolve_worktree_directory() {
4207        let work_dir = Path::new("/code/my-project");
4208
4209        // Sibling directory — outside project, so repo dir name is appended
4210        assert_eq!(
4211            resolve_worktree_directory(work_dir, "../worktrees"),
4212            PathBuf::from("/code/worktrees/my-project")
4213        );
4214
4215        // Git subdir — inside project, no repo name appended
4216        assert_eq!(
4217            resolve_worktree_directory(work_dir, ".git/zed-worktrees"),
4218            PathBuf::from("/code/my-project/.git/zed-worktrees")
4219        );
4220
4221        // Simple subdir — inside project, no repo name appended
4222        assert_eq!(
4223            resolve_worktree_directory(work_dir, "my-worktrees"),
4224            PathBuf::from("/code/my-project/my-worktrees")
4225        );
4226
4227        // Trailing slash is stripped
4228        assert_eq!(
4229            resolve_worktree_directory(work_dir, "../worktrees/"),
4230            PathBuf::from("/code/worktrees/my-project")
4231        );
4232        assert_eq!(
4233            resolve_worktree_directory(work_dir, "my-worktrees/"),
4234            PathBuf::from("/code/my-project/my-worktrees")
4235        );
4236
4237        // Multiple trailing slashes
4238        assert_eq!(
4239            resolve_worktree_directory(work_dir, "foo///"),
4240            PathBuf::from("/code/my-project/foo")
4241        );
4242
4243        // Trailing backslashes (Windows-style)
4244        assert_eq!(
4245            resolve_worktree_directory(work_dir, "my-worktrees\\"),
4246            PathBuf::from("/code/my-project/my-worktrees")
4247        );
4248        assert_eq!(
4249            resolve_worktree_directory(work_dir, "foo\\/\\"),
4250            PathBuf::from("/code/my-project/foo")
4251        );
4252
4253        // Empty string resolves to the working directory itself (inside)
4254        assert_eq!(
4255            resolve_worktree_directory(work_dir, ""),
4256            PathBuf::from("/code/my-project")
4257        );
4258
4259        // Just ".." — outside project, repo dir name appended
4260        assert_eq!(
4261            resolve_worktree_directory(work_dir, ".."),
4262            PathBuf::from("/code/my-project")
4263        );
4264    }
4265
4266    #[test]
4267    fn test_original_repo_path_from_common_dir() {
4268        // Normal repo: common_dir is <work_dir>/.git
4269        assert_eq!(
4270            original_repo_path_from_common_dir(Path::new("/code/zed5/.git")),
4271            PathBuf::from("/code/zed5")
4272        );
4273
4274        // Worktree: common_dir is the main repo's .git
4275        // (same result — that's the point, it always traces back to the original)
4276        assert_eq!(
4277            original_repo_path_from_common_dir(Path::new("/code/zed5/.git")),
4278            PathBuf::from("/code/zed5")
4279        );
4280
4281        // Bare repo: no .git suffix, returns as-is
4282        assert_eq!(
4283            original_repo_path_from_common_dir(Path::new("/code/zed5.git")),
4284            PathBuf::from("/code/zed5.git")
4285        );
4286
4287        // Root-level .git directory
4288        assert_eq!(
4289            original_repo_path_from_common_dir(Path::new("/.git")),
4290            PathBuf::from("/")
4291        );
4292    }
4293
4294    #[test]
4295    fn test_validate_worktree_directory() {
4296        let work_dir = Path::new("/code/my-project");
4297
4298        // Valid: sibling
4299        assert!(validate_worktree_directory(work_dir, "../worktrees").is_ok());
4300
4301        // Valid: subdirectory
4302        assert!(validate_worktree_directory(work_dir, ".git/zed-worktrees").is_ok());
4303        assert!(validate_worktree_directory(work_dir, "my-worktrees").is_ok());
4304
4305        // Invalid: just ".." would resolve back to the working directory itself
4306        let err = validate_worktree_directory(work_dir, "..").unwrap_err();
4307        assert!(err.to_string().contains("must not be \"..\""));
4308
4309        // Invalid: ".." with trailing separators
4310        let err = validate_worktree_directory(work_dir, "..\\").unwrap_err();
4311        assert!(err.to_string().contains("must not be \"..\""));
4312        let err = validate_worktree_directory(work_dir, "../").unwrap_err();
4313        assert!(err.to_string().contains("must not be \"..\""));
4314
4315        // Invalid: empty string would resolve to the working directory itself
4316        let err = validate_worktree_directory(work_dir, "").unwrap_err();
4317        assert!(err.to_string().contains("must not be empty"));
4318
4319        // Invalid: absolute path
4320        let err = validate_worktree_directory(work_dir, "/tmp/worktrees").unwrap_err();
4321        assert!(err.to_string().contains("relative path"));
4322
4323        // Invalid: "/" is absolute on Unix
4324        let err = validate_worktree_directory(work_dir, "/").unwrap_err();
4325        assert!(err.to_string().contains("relative path"));
4326
4327        // Invalid: "///" is absolute
4328        let err = validate_worktree_directory(work_dir, "///").unwrap_err();
4329        assert!(err.to_string().contains("relative path"));
4330
4331        // Invalid: escapes too far up
4332        let err = validate_worktree_directory(work_dir, "../../other-project/wt").unwrap_err();
4333        assert!(err.to_string().contains("outside"));
4334    }
4335
4336    #[test]
4337    fn test_worktree_path_for_branch() {
4338        let work_dir = Path::new("/code/my-project");
4339
4340        // Outside project — repo dir name is part of the resolved directory
4341        assert_eq!(
4342            worktree_path_for_branch(work_dir, "../worktrees", "feature/foo"),
4343            PathBuf::from("/code/worktrees/my-project/feature/foo")
4344        );
4345
4346        // Inside project — no repo dir name inserted
4347        assert_eq!(
4348            worktree_path_for_branch(work_dir, ".git/zed-worktrees", "my-branch"),
4349            PathBuf::from("/code/my-project/.git/zed-worktrees/my-branch")
4350        );
4351
4352        // Trailing slash on setting (inside project)
4353        assert_eq!(
4354            worktree_path_for_branch(work_dir, "my-worktrees/", "branch"),
4355            PathBuf::from("/code/my-project/my-worktrees/branch")
4356        );
4357    }
4358
4359    impl RealGitRepository {
4360        /// Force a Git garbage collection on the repository.
4361        fn gc(&self) -> BoxFuture<'_, Result<()>> {
4362            let working_directory = self.working_directory();
4363            let git_binary_path = self.any_git_binary_path.clone();
4364            let executor = self.executor.clone();
4365            self.executor
4366                .spawn(async move {
4367                    let git_binary_path = git_binary_path.clone();
4368                    let working_directory = working_directory?;
4369                    let git = GitBinary::new(git_binary_path, working_directory, executor, true);
4370                    git.run(&["gc", "--prune"]).await?;
4371                    Ok(())
4372                })
4373                .boxed()
4374        }
4375    }
4376}