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        diff: DiffType,
 928    ) -> BoxFuture<'_, Result<HashMap<RepoPath, crate::status::DiffStat>>>;
 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        diff: DiffType,
2001    ) -> BoxFuture<'_, Result<HashMap<RepoPath, crate::status::DiffStat>>> {
2002        let git_binary = self.git_binary();
2003        self.executor
2004            .spawn(async move {
2005                let git = git_binary?;
2006                let output = match diff {
2007                    DiffType::HeadToIndex => {
2008                        git.build_command(["diff", "--numstat", "--staged"])
2009                            .output()
2010                            .await?
2011                    }
2012                    DiffType::HeadToWorktree => {
2013                        git.build_command(["diff", "--numstat"]).output().await?
2014                    }
2015                    DiffType::MergeBase { base_ref } => {
2016                        git.build_command([
2017                            "diff",
2018                            "--numstat",
2019                            "--merge-base",
2020                            base_ref.as_ref(),
2021                            "HEAD",
2022                        ])
2023                        .output()
2024                        .await?
2025                    }
2026                };
2027
2028                anyhow::ensure!(
2029                    output.status.success(),
2030                    "Failed to run git diff --numstat:\n{}",
2031                    String::from_utf8_lossy(&output.stderr)
2032                );
2033                Ok(crate::status::parse_numstat(&String::from_utf8_lossy(
2034                    &output.stdout,
2035                )))
2036            })
2037            .boxed()
2038    }
2039
2040    fn stage_paths(
2041        &self,
2042        paths: Vec<RepoPath>,
2043        env: Arc<HashMap<String, String>>,
2044    ) -> BoxFuture<'_, Result<()>> {
2045        let git_binary = self.git_binary();
2046        self.executor
2047            .spawn(async move {
2048                if !paths.is_empty() {
2049                    let git = git_binary?;
2050                    let output = git
2051                        .build_command(["update-index", "--add", "--remove", "--"])
2052                        .envs(env.iter())
2053                        .args(paths.iter().map(|p| p.as_unix_str()))
2054                        .output()
2055                        .await?;
2056                    anyhow::ensure!(
2057                        output.status.success(),
2058                        "Failed to stage paths:\n{}",
2059                        String::from_utf8_lossy(&output.stderr),
2060                    );
2061                }
2062                Ok(())
2063            })
2064            .boxed()
2065    }
2066
2067    fn unstage_paths(
2068        &self,
2069        paths: Vec<RepoPath>,
2070        env: Arc<HashMap<String, String>>,
2071    ) -> BoxFuture<'_, Result<()>> {
2072        let git_binary = self.git_binary();
2073
2074        self.executor
2075            .spawn(async move {
2076                if !paths.is_empty() {
2077                    let git = git_binary?;
2078                    let output = git
2079                        .build_command(["reset", "--quiet", "--"])
2080                        .envs(env.iter())
2081                        .args(paths.iter().map(|p| p.as_std_path()))
2082                        .output()
2083                        .await?;
2084
2085                    anyhow::ensure!(
2086                        output.status.success(),
2087                        "Failed to unstage:\n{}",
2088                        String::from_utf8_lossy(&output.stderr),
2089                    );
2090                }
2091                Ok(())
2092            })
2093            .boxed()
2094    }
2095
2096    fn stash_paths(
2097        &self,
2098        paths: Vec<RepoPath>,
2099        env: Arc<HashMap<String, String>>,
2100    ) -> BoxFuture<'_, Result<()>> {
2101        let git_binary = self.git_binary();
2102        self.executor
2103            .spawn(async move {
2104                let git = git_binary?;
2105                let output = git
2106                    .build_command(["stash", "push", "--quiet", "--include-untracked"])
2107                    .envs(env.iter())
2108                    .args(paths.iter().map(|p| p.as_unix_str()))
2109                    .output()
2110                    .await?;
2111
2112                anyhow::ensure!(
2113                    output.status.success(),
2114                    "Failed to stash:\n{}",
2115                    String::from_utf8_lossy(&output.stderr)
2116                );
2117                Ok(())
2118            })
2119            .boxed()
2120    }
2121
2122    fn stash_pop(
2123        &self,
2124        index: Option<usize>,
2125        env: Arc<HashMap<String, String>>,
2126    ) -> BoxFuture<'_, Result<()>> {
2127        let git_binary = self.git_binary();
2128        self.executor
2129            .spawn(async move {
2130                let git = git_binary?;
2131                let mut args = vec!["stash".to_string(), "pop".to_string()];
2132                if let Some(index) = index {
2133                    args.push(format!("stash@{{{}}}", index));
2134                }
2135                let output = git.build_command(&args).envs(env.iter()).output().await?;
2136
2137                anyhow::ensure!(
2138                    output.status.success(),
2139                    "Failed to stash pop:\n{}",
2140                    String::from_utf8_lossy(&output.stderr)
2141                );
2142                Ok(())
2143            })
2144            .boxed()
2145    }
2146
2147    fn stash_apply(
2148        &self,
2149        index: Option<usize>,
2150        env: Arc<HashMap<String, String>>,
2151    ) -> BoxFuture<'_, Result<()>> {
2152        let git_binary = self.git_binary();
2153        self.executor
2154            .spawn(async move {
2155                let git = git_binary?;
2156                let mut args = vec!["stash".to_string(), "apply".to_string()];
2157                if let Some(index) = index {
2158                    args.push(format!("stash@{{{}}}", index));
2159                }
2160                let output = git.build_command(&args).envs(env.iter()).output().await?;
2161
2162                anyhow::ensure!(
2163                    output.status.success(),
2164                    "Failed to apply stash:\n{}",
2165                    String::from_utf8_lossy(&output.stderr)
2166                );
2167                Ok(())
2168            })
2169            .boxed()
2170    }
2171
2172    fn stash_drop(
2173        &self,
2174        index: Option<usize>,
2175        env: Arc<HashMap<String, String>>,
2176    ) -> BoxFuture<'_, Result<()>> {
2177        let git_binary = self.git_binary();
2178        self.executor
2179            .spawn(async move {
2180                let git = git_binary?;
2181                let mut args = vec!["stash".to_string(), "drop".to_string()];
2182                if let Some(index) = index {
2183                    args.push(format!("stash@{{{}}}", index));
2184                }
2185                let output = git.build_command(&args).envs(env.iter()).output().await?;
2186
2187                anyhow::ensure!(
2188                    output.status.success(),
2189                    "Failed to stash drop:\n{}",
2190                    String::from_utf8_lossy(&output.stderr)
2191                );
2192                Ok(())
2193            })
2194            .boxed()
2195    }
2196
2197    fn commit(
2198        &self,
2199        message: SharedString,
2200        name_and_email: Option<(SharedString, SharedString)>,
2201        options: CommitOptions,
2202        ask_pass: AskPassDelegate,
2203        env: Arc<HashMap<String, String>>,
2204    ) -> BoxFuture<'_, Result<()>> {
2205        let git_binary = self.git_binary();
2206        let executor = self.executor.clone();
2207        // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2208        // which we want to block on.
2209        async move {
2210            let git = git_binary?;
2211            let mut cmd = git.build_command(["commit", "--quiet", "-m"]);
2212            cmd.envs(env.iter())
2213                .arg(&message.to_string())
2214                .arg("--cleanup=strip")
2215                .arg("--no-verify")
2216                .stdout(Stdio::piped())
2217                .stderr(Stdio::piped());
2218
2219            if options.amend {
2220                cmd.arg("--amend");
2221            }
2222
2223            if options.signoff {
2224                cmd.arg("--signoff");
2225            }
2226
2227            if let Some((name, email)) = name_and_email {
2228                cmd.arg("--author").arg(&format!("{name} <{email}>"));
2229            }
2230
2231            run_git_command(env, ask_pass, cmd, executor).await?;
2232
2233            Ok(())
2234        }
2235        .boxed()
2236    }
2237
2238    fn push(
2239        &self,
2240        branch_name: String,
2241        remote_branch_name: String,
2242        remote_name: String,
2243        options: Option<PushOptions>,
2244        ask_pass: AskPassDelegate,
2245        env: Arc<HashMap<String, String>>,
2246        cx: AsyncApp,
2247    ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
2248        let working_directory = self.working_directory();
2249        let executor = cx.background_executor().clone();
2250        let git_binary_path = self.system_git_binary_path.clone();
2251        let is_trusted = self.is_trusted();
2252        // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2253        // which we want to block on.
2254        async move {
2255            let git_binary_path = git_binary_path.context("git not found on $PATH, can't push")?;
2256            let working_directory = working_directory?;
2257            let git = GitBinary::new(
2258                git_binary_path,
2259                working_directory,
2260                executor.clone(),
2261                is_trusted,
2262            );
2263            let mut command = git.build_command(["push"]);
2264            command
2265                .envs(env.iter())
2266                .args(options.map(|option| match option {
2267                    PushOptions::SetUpstream => "--set-upstream",
2268                    PushOptions::Force => "--force-with-lease",
2269                }))
2270                .arg(remote_name)
2271                .arg(format!("{}:{}", branch_name, remote_branch_name))
2272                .stdin(Stdio::null())
2273                .stdout(Stdio::piped())
2274                .stderr(Stdio::piped());
2275
2276            run_git_command(env, ask_pass, command, executor).await
2277        }
2278        .boxed()
2279    }
2280
2281    fn pull(
2282        &self,
2283        branch_name: Option<String>,
2284        remote_name: String,
2285        rebase: bool,
2286        ask_pass: AskPassDelegate,
2287        env: Arc<HashMap<String, String>>,
2288        cx: AsyncApp,
2289    ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
2290        let working_directory = self.working_directory();
2291        let executor = cx.background_executor().clone();
2292        let git_binary_path = self.system_git_binary_path.clone();
2293        let is_trusted = self.is_trusted();
2294        // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2295        // which we want to block on.
2296        async move {
2297            let git_binary_path = git_binary_path.context("git not found on $PATH, can't pull")?;
2298            let working_directory = working_directory?;
2299            let git = GitBinary::new(
2300                git_binary_path,
2301                working_directory,
2302                executor.clone(),
2303                is_trusted,
2304            );
2305            let mut command = git.build_command(["pull"]);
2306            command.envs(env.iter());
2307
2308            if rebase {
2309                command.arg("--rebase");
2310            }
2311
2312            command
2313                .arg(remote_name)
2314                .args(branch_name)
2315                .stdout(Stdio::piped())
2316                .stderr(Stdio::piped());
2317
2318            run_git_command(env, ask_pass, command, executor).await
2319        }
2320        .boxed()
2321    }
2322
2323    fn fetch(
2324        &self,
2325        fetch_options: FetchOptions,
2326        ask_pass: AskPassDelegate,
2327        env: Arc<HashMap<String, String>>,
2328        cx: AsyncApp,
2329    ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
2330        let working_directory = self.working_directory();
2331        let remote_name = format!("{}", fetch_options);
2332        let git_binary_path = self.system_git_binary_path.clone();
2333        let executor = cx.background_executor().clone();
2334        let is_trusted = self.is_trusted();
2335        // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2336        // which we want to block on.
2337        async move {
2338            let git_binary_path = git_binary_path.context("git not found on $PATH, can't fetch")?;
2339            let working_directory = working_directory?;
2340            let git = GitBinary::new(
2341                git_binary_path,
2342                working_directory,
2343                executor.clone(),
2344                is_trusted,
2345            );
2346            let mut command = git.build_command(["fetch", &remote_name]);
2347            command
2348                .envs(env.iter())
2349                .stdout(Stdio::piped())
2350                .stderr(Stdio::piped());
2351
2352            run_git_command(env, ask_pass, command, executor).await
2353        }
2354        .boxed()
2355    }
2356
2357    fn get_push_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
2358        let git_binary = self.git_binary();
2359        self.executor
2360            .spawn(async move {
2361                let git = git_binary?;
2362                let output = git
2363                    .build_command(["rev-parse", "--abbrev-ref"])
2364                    .arg(format!("{branch}@{{push}}"))
2365                    .output()
2366                    .await?;
2367                if !output.status.success() {
2368                    return Ok(None);
2369                }
2370                let remote_name = String::from_utf8_lossy(&output.stdout)
2371                    .split('/')
2372                    .next()
2373                    .map(|name| Remote {
2374                        name: name.trim().to_string().into(),
2375                    });
2376
2377                Ok(remote_name)
2378            })
2379            .boxed()
2380    }
2381
2382    fn get_branch_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
2383        let git_binary = self.git_binary();
2384        self.executor
2385            .spawn(async move {
2386                let git = git_binary?;
2387                let output = git
2388                    .build_command(["config", "--get"])
2389                    .arg(format!("branch.{branch}.remote"))
2390                    .output()
2391                    .await?;
2392                if !output.status.success() {
2393                    return Ok(None);
2394                }
2395
2396                let remote_name = String::from_utf8_lossy(&output.stdout);
2397                return Ok(Some(Remote {
2398                    name: remote_name.trim().to_string().into(),
2399                }));
2400            })
2401            .boxed()
2402    }
2403
2404    fn get_all_remotes(&self) -> BoxFuture<'_, Result<Vec<Remote>>> {
2405        let git_binary = self.git_binary();
2406        self.executor
2407            .spawn(async move {
2408                let git = git_binary?;
2409                let output = git.build_command(["remote", "-v"]).output().await?;
2410
2411                anyhow::ensure!(
2412                    output.status.success(),
2413                    "Failed to get all remotes:\n{}",
2414                    String::from_utf8_lossy(&output.stderr)
2415                );
2416                let remote_names: HashSet<Remote> = String::from_utf8_lossy(&output.stdout)
2417                    .lines()
2418                    .filter(|line| !line.is_empty())
2419                    .filter_map(|line| {
2420                        let mut split_line = line.split_whitespace();
2421                        let remote_name = split_line.next()?;
2422
2423                        Some(Remote {
2424                            name: remote_name.trim().to_string().into(),
2425                        })
2426                    })
2427                    .collect();
2428
2429                Ok(remote_names.into_iter().collect())
2430            })
2431            .boxed()
2432    }
2433
2434    fn remove_remote(&self, name: String) -> BoxFuture<'_, Result<()>> {
2435        let repo = self.repository.clone();
2436        self.executor
2437            .spawn(async move {
2438                let repo = repo.lock();
2439                repo.remote_delete(&name)?;
2440
2441                Ok(())
2442            })
2443            .boxed()
2444    }
2445
2446    fn create_remote(&self, name: String, url: String) -> BoxFuture<'_, Result<()>> {
2447        let repo = self.repository.clone();
2448        self.executor
2449            .spawn(async move {
2450                let repo = repo.lock();
2451                repo.remote(&name, url.as_ref())?;
2452                Ok(())
2453            })
2454            .boxed()
2455    }
2456
2457    fn check_for_pushed_commit(&self) -> BoxFuture<'_, Result<Vec<SharedString>>> {
2458        let git_binary = self.git_binary();
2459        self.executor
2460            .spawn(async move {
2461                let git = git_binary?;
2462                let git_cmd = async |args: &[&str]| -> Result<String> {
2463                    let output = git.build_command(args).output().await?;
2464                    anyhow::ensure!(
2465                        output.status.success(),
2466                        String::from_utf8_lossy(&output.stderr).to_string()
2467                    );
2468                    Ok(String::from_utf8(output.stdout)?)
2469                };
2470
2471                let head = git_cmd(&["rev-parse", "HEAD"])
2472                    .await
2473                    .context("Failed to get HEAD")?
2474                    .trim()
2475                    .to_owned();
2476
2477                let mut remote_branches = vec![];
2478                let mut add_if_matching = async |remote_head: &str| {
2479                    if let Ok(merge_base) = git_cmd(&["merge-base", &head, remote_head]).await
2480                        && merge_base.trim() == head
2481                        && let Some(s) = remote_head.strip_prefix("refs/remotes/")
2482                    {
2483                        remote_branches.push(s.to_owned().into());
2484                    }
2485                };
2486
2487                // check the main branch of each remote
2488                let remotes = git_cmd(&["remote"])
2489                    .await
2490                    .context("Failed to get remotes")?;
2491                for remote in remotes.lines() {
2492                    if let Ok(remote_head) =
2493                        git_cmd(&["symbolic-ref", &format!("refs/remotes/{remote}/HEAD")]).await
2494                    {
2495                        add_if_matching(remote_head.trim()).await;
2496                    }
2497                }
2498
2499                // ... and the remote branch that the checked-out one is tracking
2500                if let Ok(remote_head) =
2501                    git_cmd(&["rev-parse", "--symbolic-full-name", "@{u}"]).await
2502                {
2503                    add_if_matching(remote_head.trim()).await;
2504                }
2505
2506                Ok(remote_branches)
2507            })
2508            .boxed()
2509    }
2510
2511    fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>> {
2512        let git_binary = self.git_binary();
2513        self.executor
2514            .spawn(async move {
2515                let mut git = git_binary?.envs(checkpoint_author_envs());
2516                git.with_temp_index(async |git| {
2517                    let head_sha = git.run(&["rev-parse", "HEAD"]).await.ok();
2518                    let mut excludes = exclude_files(git).await?;
2519
2520                    git.run(&["add", "--all"]).await?;
2521                    let tree = git.run(&["write-tree"]).await?;
2522                    let checkpoint_sha = if let Some(head_sha) = head_sha.as_deref() {
2523                        git.run(&["commit-tree", &tree, "-p", head_sha, "-m", "Checkpoint"])
2524                            .await?
2525                    } else {
2526                        git.run(&["commit-tree", &tree, "-m", "Checkpoint"]).await?
2527                    };
2528
2529                    excludes.restore_original().await?;
2530
2531                    Ok(GitRepositoryCheckpoint {
2532                        commit_sha: checkpoint_sha.parse()?,
2533                    })
2534                })
2535                .await
2536            })
2537            .boxed()
2538    }
2539
2540    fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>> {
2541        let git_binary = self.git_binary();
2542        self.executor
2543            .spawn(async move {
2544                let git = git_binary?;
2545                git.run(&[
2546                    "restore",
2547                    "--source",
2548                    &checkpoint.commit_sha.to_string(),
2549                    "--worktree",
2550                    ".",
2551                ])
2552                .await?;
2553
2554                // TODO: We don't track binary and large files anymore,
2555                //       so the following call would delete them.
2556                //       Implement an alternative way to track files added by agent.
2557                //
2558                // git.with_temp_index(async move |git| {
2559                //     git.run(&["read-tree", &checkpoint.commit_sha.to_string()])
2560                //         .await?;
2561                //     git.run(&["clean", "-d", "--force"]).await
2562                // })
2563                // .await?;
2564
2565                Ok(())
2566            })
2567            .boxed()
2568    }
2569
2570    fn compare_checkpoints(
2571        &self,
2572        left: GitRepositoryCheckpoint,
2573        right: GitRepositoryCheckpoint,
2574    ) -> BoxFuture<'_, Result<bool>> {
2575        let git_binary = self.git_binary();
2576        self.executor
2577            .spawn(async move {
2578                let git = git_binary?;
2579                let result = git
2580                    .run(&[
2581                        "diff-tree",
2582                        "--quiet",
2583                        &left.commit_sha.to_string(),
2584                        &right.commit_sha.to_string(),
2585                    ])
2586                    .await;
2587                match result {
2588                    Ok(_) => Ok(true),
2589                    Err(error) => {
2590                        if let Some(GitBinaryCommandError { status, .. }) =
2591                            error.downcast_ref::<GitBinaryCommandError>()
2592                            && status.code() == Some(1)
2593                        {
2594                            return Ok(false);
2595                        }
2596
2597                        Err(error)
2598                    }
2599                }
2600            })
2601            .boxed()
2602    }
2603
2604    fn diff_checkpoints(
2605        &self,
2606        base_checkpoint: GitRepositoryCheckpoint,
2607        target_checkpoint: GitRepositoryCheckpoint,
2608    ) -> BoxFuture<'_, Result<String>> {
2609        let git_binary = self.git_binary();
2610        self.executor
2611            .spawn(async move {
2612                let git = git_binary?;
2613                git.run(&[
2614                    "diff",
2615                    "--find-renames",
2616                    "--patch",
2617                    &base_checkpoint.commit_sha.to_string(),
2618                    &target_checkpoint.commit_sha.to_string(),
2619                ])
2620                .await
2621            })
2622            .boxed()
2623    }
2624
2625    fn default_branch(
2626        &self,
2627        include_remote_name: bool,
2628    ) -> BoxFuture<'_, Result<Option<SharedString>>> {
2629        let git_binary = self.git_binary();
2630        self.executor
2631            .spawn(async move {
2632                let git = git_binary?;
2633
2634                let strip_prefix = if include_remote_name {
2635                    "refs/remotes/"
2636                } else {
2637                    "refs/remotes/upstream/"
2638                };
2639
2640                if let Ok(output) = git
2641                    .run(&["symbolic-ref", "refs/remotes/upstream/HEAD"])
2642                    .await
2643                {
2644                    let output = output
2645                        .strip_prefix(strip_prefix)
2646                        .map(|s| SharedString::from(s.to_owned()));
2647                    return Ok(output);
2648                }
2649
2650                let strip_prefix = if include_remote_name {
2651                    "refs/remotes/"
2652                } else {
2653                    "refs/remotes/origin/"
2654                };
2655
2656                if let Ok(output) = git.run(&["symbolic-ref", "refs/remotes/origin/HEAD"]).await {
2657                    return Ok(output
2658                        .strip_prefix(strip_prefix)
2659                        .map(|s| SharedString::from(s.to_owned())));
2660                }
2661
2662                if let Ok(default_branch) = git.run(&["config", "init.defaultBranch"]).await {
2663                    if git.run(&["rev-parse", &default_branch]).await.is_ok() {
2664                        return Ok(Some(default_branch.into()));
2665                    }
2666                }
2667
2668                if git.run(&["rev-parse", "master"]).await.is_ok() {
2669                    return Ok(Some("master".into()));
2670                }
2671
2672                Ok(None)
2673            })
2674            .boxed()
2675    }
2676
2677    fn run_hook(
2678        &self,
2679        hook: RunHook,
2680        env: Arc<HashMap<String, String>>,
2681    ) -> BoxFuture<'_, Result<()>> {
2682        let git_binary = self.git_binary();
2683        let repository = self.repository.clone();
2684        let help_output = self.any_git_binary_help_output();
2685
2686        // Note: Do not spawn these commands on the background thread, as this causes some git hooks to hang.
2687        async move {
2688            let git = git_binary?;
2689
2690            if !git.is_trusted {
2691                bail!("Can't run git commit hooks in restrictive workspace");
2692            }
2693
2694            let working_directory = git.working_directory.clone();
2695            if !help_output
2696                .await
2697                .lines()
2698                .any(|line| line.trim().starts_with("hook "))
2699            {
2700                let hook_abs_path = repository.lock().path().join("hooks").join(hook.as_str());
2701                if hook_abs_path.is_file() {
2702                    #[allow(clippy::disallowed_methods)]
2703                    let output = new_command(&hook_abs_path)
2704                        .envs(env.iter())
2705                        .current_dir(&working_directory)
2706                        .output()
2707                        .await?;
2708
2709                    if !output.status.success() {
2710                        return Err(GitBinaryCommandError {
2711                            stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
2712                            stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
2713                            status: output.status,
2714                        }
2715                        .into());
2716                    }
2717                }
2718
2719                return Ok(());
2720            }
2721
2722            let git = git.envs(HashMap::clone(&env));
2723            git.run(&["hook", "run", "--ignore-missing", hook.as_str()])
2724                .await?;
2725            Ok(())
2726        }
2727        .boxed()
2728    }
2729
2730    fn initial_graph_data(
2731        &self,
2732        log_source: LogSource,
2733        log_order: LogOrder,
2734        request_tx: Sender<Vec<Arc<InitialGraphCommitData>>>,
2735    ) -> BoxFuture<'_, Result<()>> {
2736        let git_binary = self.git_binary();
2737
2738        async move {
2739            let git = git_binary?;
2740
2741            let mut command = git.build_command([
2742                "log",
2743                GRAPH_COMMIT_FORMAT,
2744                log_order.as_arg(),
2745                log_source.get_arg()?,
2746            ]);
2747            command.stdout(Stdio::piped());
2748            command.stderr(Stdio::null());
2749
2750            let mut child = command.spawn()?;
2751            let stdout = child.stdout.take().context("failed to get stdout")?;
2752            let mut reader = BufReader::new(stdout);
2753
2754            let mut line_buffer = String::new();
2755            let mut lines: Vec<String> = Vec::with_capacity(GRAPH_CHUNK_SIZE);
2756
2757            loop {
2758                line_buffer.clear();
2759                let bytes_read = reader.read_line(&mut line_buffer).await?;
2760
2761                if bytes_read == 0 {
2762                    if !lines.is_empty() {
2763                        let commits = parse_initial_graph_output(lines.iter().map(|s| s.as_str()));
2764                        if request_tx.send(commits).await.is_err() {
2765                            log::warn!(
2766                                "initial_graph_data: receiver dropped while sending commits"
2767                            );
2768                        }
2769                    }
2770                    break;
2771                }
2772
2773                let line = line_buffer.trim_end_matches('\n').to_string();
2774                lines.push(line);
2775
2776                if lines.len() >= GRAPH_CHUNK_SIZE {
2777                    let commits = parse_initial_graph_output(lines.iter().map(|s| s.as_str()));
2778                    if request_tx.send(commits).await.is_err() {
2779                        log::warn!("initial_graph_data: receiver dropped while streaming commits");
2780                        break;
2781                    }
2782                    lines.clear();
2783                }
2784            }
2785
2786            child.status().await?;
2787            Ok(())
2788        }
2789        .boxed()
2790    }
2791
2792    fn commit_data_reader(&self) -> Result<CommitDataReader> {
2793        let git_binary = self.git_binary()?;
2794
2795        let (request_tx, request_rx) = smol::channel::bounded::<CommitDataRequest>(64);
2796
2797        let task = self.executor.spawn(async move {
2798            if let Err(error) = run_commit_data_reader(git_binary, request_rx).await {
2799                log::error!("commit data reader failed: {error:?}");
2800            }
2801        });
2802
2803        Ok(CommitDataReader {
2804            request_tx,
2805            _task: task,
2806        })
2807    }
2808
2809    fn set_trusted(&self, trusted: bool) {
2810        self.is_trusted
2811            .store(trusted, std::sync::atomic::Ordering::Release);
2812    }
2813
2814    fn is_trusted(&self) -> bool {
2815        self.is_trusted.load(std::sync::atomic::Ordering::Acquire)
2816    }
2817}
2818
2819async fn run_commit_data_reader(
2820    git: GitBinary,
2821    request_rx: smol::channel::Receiver<CommitDataRequest>,
2822) -> Result<()> {
2823    let mut process = git
2824        .build_command(["--no-optional-locks", "cat-file", "--batch"])
2825        .stdin(Stdio::piped())
2826        .stdout(Stdio::piped())
2827        .stderr(Stdio::piped())
2828        .spawn()
2829        .context("starting git cat-file --batch process")?;
2830
2831    let mut stdin = BufWriter::new(process.stdin.take().context("no stdin")?);
2832    let mut stdout = BufReader::new(process.stdout.take().context("no stdout")?);
2833
2834    const MAX_BATCH_SIZE: usize = 64;
2835
2836    while let Ok(first_request) = request_rx.recv().await {
2837        let mut pending_requests = vec![first_request];
2838
2839        while pending_requests.len() < MAX_BATCH_SIZE {
2840            match request_rx.try_recv() {
2841                Ok(request) => pending_requests.push(request),
2842                Err(_) => break,
2843            }
2844        }
2845
2846        for request in &pending_requests {
2847            stdin.write_all(request.sha.to_string().as_bytes()).await?;
2848            stdin.write_all(b"\n").await?;
2849        }
2850        stdin.flush().await?;
2851
2852        for request in pending_requests {
2853            let result = read_single_commit_response(&mut stdout, &request.sha).await;
2854            request.response_tx.send(result).ok();
2855        }
2856    }
2857
2858    drop(stdin);
2859    process.kill().ok();
2860
2861    Ok(())
2862}
2863
2864async fn read_single_commit_response<R: smol::io::AsyncBufRead + Unpin>(
2865    stdout: &mut R,
2866    sha: &Oid,
2867) -> Result<GraphCommitData> {
2868    let mut header_bytes = Vec::new();
2869    stdout.read_until(b'\n', &mut header_bytes).await?;
2870    let header_line = String::from_utf8_lossy(&header_bytes);
2871
2872    let parts: Vec<&str> = header_line.trim().split(' ').collect();
2873    if parts.len() < 3 {
2874        bail!("invalid cat-file header: {header_line}");
2875    }
2876
2877    let object_type = parts[1];
2878    if object_type == "missing" {
2879        bail!("object not found: {}", sha);
2880    }
2881
2882    if object_type != "commit" {
2883        bail!("expected commit object, got {object_type}");
2884    }
2885
2886    let size: usize = parts[2]
2887        .parse()
2888        .with_context(|| format!("invalid object size: {}", parts[2]))?;
2889
2890    let mut content = vec![0u8; size];
2891    stdout.read_exact(&mut content).await?;
2892
2893    let mut newline = [0u8; 1];
2894    stdout.read_exact(&mut newline).await?;
2895
2896    let content_str = String::from_utf8_lossy(&content);
2897    parse_cat_file_commit(*sha, &content_str)
2898        .ok_or_else(|| anyhow!("failed to parse commit {}", sha))
2899}
2900
2901fn parse_initial_graph_output<'a>(
2902    lines: impl Iterator<Item = &'a str>,
2903) -> Vec<Arc<InitialGraphCommitData>> {
2904    lines
2905        .filter(|line| !line.is_empty())
2906        .filter_map(|line| {
2907            // Format: "SHA\x00PARENT1 PARENT2...\x00REF1, REF2, ..."
2908            let mut parts = line.split('\x00');
2909
2910            let sha = Oid::from_str(parts.next()?).ok()?;
2911            let parents_str = parts.next()?;
2912            let parents = parents_str
2913                .split_whitespace()
2914                .filter_map(|p| Oid::from_str(p).ok())
2915                .collect();
2916
2917            let ref_names_str = parts.next().unwrap_or("");
2918            let ref_names = if ref_names_str.is_empty() {
2919                Vec::new()
2920            } else {
2921                ref_names_str
2922                    .split(", ")
2923                    .map(|s| SharedString::from(s.to_string()))
2924                    .collect()
2925            };
2926
2927            Some(Arc::new(InitialGraphCommitData {
2928                sha,
2929                parents,
2930                ref_names,
2931            }))
2932        })
2933        .collect()
2934}
2935
2936fn git_status_args(path_prefixes: &[RepoPath]) -> Vec<OsString> {
2937    let mut args = vec![
2938        OsString::from("--no-optional-locks"),
2939        OsString::from("status"),
2940        OsString::from("--porcelain=v1"),
2941        OsString::from("--untracked-files=all"),
2942        OsString::from("--no-renames"),
2943        OsString::from("-z"),
2944    ];
2945    args.extend(
2946        path_prefixes
2947            .iter()
2948            .map(|path_prefix| path_prefix.as_std_path().into()),
2949    );
2950    args.extend(path_prefixes.iter().map(|path_prefix| {
2951        if path_prefix.is_empty() {
2952            Path::new(".").into()
2953        } else {
2954            path_prefix.as_std_path().into()
2955        }
2956    }));
2957    args
2958}
2959
2960/// Temporarily git-ignore commonly ignored files and files over 2MB
2961async fn exclude_files(git: &GitBinary) -> Result<GitExcludeOverride> {
2962    const MAX_SIZE: u64 = 2 * 1024 * 1024; // 2 MB
2963    let mut excludes = git.with_exclude_overrides().await?;
2964    excludes
2965        .add_excludes(include_str!("./checkpoint.gitignore"))
2966        .await?;
2967
2968    let working_directory = git.working_directory.clone();
2969    let untracked_files = git.list_untracked_files().await?;
2970    let excluded_paths = untracked_files.into_iter().map(|path| {
2971        let working_directory = working_directory.clone();
2972        smol::spawn(async move {
2973            let full_path = working_directory.join(path.clone());
2974            match smol::fs::metadata(&full_path).await {
2975                Ok(metadata) if metadata.is_file() && metadata.len() >= MAX_SIZE => {
2976                    Some(PathBuf::from("/").join(path.clone()))
2977                }
2978                _ => None,
2979            }
2980        })
2981    });
2982
2983    let excluded_paths = futures::future::join_all(excluded_paths).await;
2984    let excluded_paths = excluded_paths.into_iter().flatten().collect::<Vec<_>>();
2985
2986    if !excluded_paths.is_empty() {
2987        let exclude_patterns = excluded_paths
2988            .into_iter()
2989            .map(|path| path.to_string_lossy().into_owned())
2990            .collect::<Vec<_>>()
2991            .join("\n");
2992        excludes.add_excludes(&exclude_patterns).await?;
2993    }
2994
2995    Ok(excludes)
2996}
2997
2998pub(crate) struct GitBinary {
2999    git_binary_path: PathBuf,
3000    working_directory: PathBuf,
3001    executor: BackgroundExecutor,
3002    index_file_path: Option<PathBuf>,
3003    envs: HashMap<String, String>,
3004    is_trusted: bool,
3005}
3006
3007impl GitBinary {
3008    pub(crate) fn new(
3009        git_binary_path: PathBuf,
3010        working_directory: PathBuf,
3011        executor: BackgroundExecutor,
3012        is_trusted: bool,
3013    ) -> Self {
3014        Self {
3015            git_binary_path,
3016            working_directory,
3017            executor,
3018            index_file_path: None,
3019            envs: HashMap::default(),
3020            is_trusted,
3021        }
3022    }
3023
3024    async fn list_untracked_files(&self) -> Result<Vec<PathBuf>> {
3025        let status_output = self
3026            .run(&["status", "--porcelain=v1", "--untracked-files=all", "-z"])
3027            .await?;
3028
3029        let paths = status_output
3030            .split('\0')
3031            .filter(|entry| entry.len() >= 3 && entry.starts_with("?? "))
3032            .map(|entry| PathBuf::from(&entry[3..]))
3033            .collect::<Vec<_>>();
3034        Ok(paths)
3035    }
3036
3037    fn envs(mut self, envs: HashMap<String, String>) -> Self {
3038        self.envs = envs;
3039        self
3040    }
3041
3042    pub async fn with_temp_index<R>(
3043        &mut self,
3044        f: impl AsyncFnOnce(&Self) -> Result<R>,
3045    ) -> Result<R> {
3046        let index_file_path = self.path_for_index_id(Uuid::new_v4());
3047
3048        let delete_temp_index = util::defer({
3049            let index_file_path = index_file_path.clone();
3050            let executor = self.executor.clone();
3051            move || {
3052                executor
3053                    .spawn(async move {
3054                        smol::fs::remove_file(index_file_path).await.log_err();
3055                    })
3056                    .detach();
3057            }
3058        });
3059
3060        // Copy the default index file so that Git doesn't have to rebuild the
3061        // whole index from scratch. This might fail if this is an empty repository.
3062        smol::fs::copy(
3063            self.working_directory.join(".git").join("index"),
3064            &index_file_path,
3065        )
3066        .await
3067        .ok();
3068
3069        self.index_file_path = Some(index_file_path.clone());
3070        let result = f(self).await;
3071        self.index_file_path = None;
3072        let result = result?;
3073
3074        smol::fs::remove_file(index_file_path).await.ok();
3075        delete_temp_index.abort();
3076
3077        Ok(result)
3078    }
3079
3080    pub async fn with_exclude_overrides(&self) -> Result<GitExcludeOverride> {
3081        let path = self
3082            .working_directory
3083            .join(".git")
3084            .join("info")
3085            .join("exclude");
3086
3087        GitExcludeOverride::new(path).await
3088    }
3089
3090    fn path_for_index_id(&self, id: Uuid) -> PathBuf {
3091        self.working_directory
3092            .join(".git")
3093            .join(format!("index-{}.tmp", id))
3094    }
3095
3096    pub async fn run<S>(&self, args: impl IntoIterator<Item = S>) -> Result<String>
3097    where
3098        S: AsRef<OsStr>,
3099    {
3100        let mut stdout = self.run_raw(args).await?;
3101        if stdout.chars().last() == Some('\n') {
3102            stdout.pop();
3103        }
3104        Ok(stdout)
3105    }
3106
3107    /// Returns the result of the command without trimming the trailing newline.
3108    pub async fn run_raw<S>(&self, args: impl IntoIterator<Item = S>) -> Result<String>
3109    where
3110        S: AsRef<OsStr>,
3111    {
3112        let mut command = self.build_command(args);
3113        let output = command.output().await?;
3114        anyhow::ensure!(
3115            output.status.success(),
3116            GitBinaryCommandError {
3117                stdout: String::from_utf8_lossy(&output.stdout).to_string(),
3118                stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3119                status: output.status,
3120            }
3121        );
3122        Ok(String::from_utf8(output.stdout)?)
3123    }
3124
3125    #[allow(clippy::disallowed_methods)]
3126    pub(crate) fn build_command<S>(
3127        &self,
3128        args: impl IntoIterator<Item = S>,
3129    ) -> util::command::Command
3130    where
3131        S: AsRef<OsStr>,
3132    {
3133        let mut command = new_command(&self.git_binary_path);
3134        command.current_dir(&self.working_directory);
3135        command.args(["-c", "core.fsmonitor=false"]);
3136        if !self.is_trusted {
3137            command.args(["-c", "core.hooksPath=/dev/null"]);
3138        }
3139        command.args(args);
3140        if let Some(index_file_path) = self.index_file_path.as_ref() {
3141            command.env("GIT_INDEX_FILE", index_file_path);
3142        }
3143        command.envs(&self.envs);
3144        command
3145    }
3146}
3147
3148#[derive(Error, Debug)]
3149#[error("Git command failed:\n{stdout}{stderr}\n")]
3150struct GitBinaryCommandError {
3151    stdout: String,
3152    stderr: String,
3153    status: ExitStatus,
3154}
3155
3156async fn run_git_command(
3157    env: Arc<HashMap<String, String>>,
3158    ask_pass: AskPassDelegate,
3159    mut command: util::command::Command,
3160    executor: BackgroundExecutor,
3161) -> Result<RemoteCommandOutput> {
3162    if env.contains_key("GIT_ASKPASS") {
3163        let git_process = command.spawn()?;
3164        let output = git_process.output().await?;
3165        anyhow::ensure!(
3166            output.status.success(),
3167            "{}",
3168            String::from_utf8_lossy(&output.stderr)
3169        );
3170        Ok(RemoteCommandOutput {
3171            stdout: String::from_utf8_lossy(&output.stdout).to_string(),
3172            stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3173        })
3174    } else {
3175        let ask_pass = AskPassSession::new(executor, ask_pass).await?;
3176        command
3177            .env("GIT_ASKPASS", ask_pass.script_path())
3178            .env("SSH_ASKPASS", ask_pass.script_path())
3179            .env("SSH_ASKPASS_REQUIRE", "force");
3180        let git_process = command.spawn()?;
3181
3182        run_askpass_command(ask_pass, git_process).await
3183    }
3184}
3185
3186async fn run_askpass_command(
3187    mut ask_pass: AskPassSession,
3188    git_process: util::command::Child,
3189) -> anyhow::Result<RemoteCommandOutput> {
3190    select_biased! {
3191        result = ask_pass.run().fuse() => {
3192            match result {
3193                AskPassResult::CancelledByUser => {
3194                    Err(anyhow!(REMOTE_CANCELLED_BY_USER))?
3195                }
3196                AskPassResult::Timedout => {
3197                    Err(anyhow!("Connecting to host timed out"))?
3198                }
3199            }
3200        }
3201        output = git_process.output().fuse() => {
3202            let output = output?;
3203            anyhow::ensure!(
3204                output.status.success(),
3205                "{}",
3206                String::from_utf8_lossy(&output.stderr)
3207            );
3208            Ok(RemoteCommandOutput {
3209                stdout: String::from_utf8_lossy(&output.stdout).to_string(),
3210                stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3211            })
3212        }
3213    }
3214}
3215
3216#[derive(Clone, Ord, Hash, PartialOrd, Eq, PartialEq)]
3217pub struct RepoPath(Arc<RelPath>);
3218
3219impl std::fmt::Debug for RepoPath {
3220    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3221        self.0.fmt(f)
3222    }
3223}
3224
3225impl RepoPath {
3226    pub fn new<S: AsRef<str> + ?Sized>(s: &S) -> Result<Self> {
3227        let rel_path = RelPath::unix(s.as_ref())?;
3228        Ok(Self::from_rel_path(rel_path))
3229    }
3230
3231    pub fn from_std_path(path: &Path, path_style: PathStyle) -> Result<Self> {
3232        let rel_path = RelPath::new(path, path_style)?;
3233        Ok(Self::from_rel_path(&rel_path))
3234    }
3235
3236    pub fn from_proto(proto: &str) -> Result<Self> {
3237        let rel_path = RelPath::from_proto(proto)?;
3238        Ok(Self(rel_path))
3239    }
3240
3241    pub fn from_rel_path(path: &RelPath) -> RepoPath {
3242        Self(Arc::from(path))
3243    }
3244
3245    pub fn as_std_path(&self) -> &Path {
3246        // git2 does not like empty paths and our RelPath infra turns `.` into ``
3247        // so undo that here
3248        if self.is_empty() {
3249            Path::new(".")
3250        } else {
3251            self.0.as_std_path()
3252        }
3253    }
3254}
3255
3256#[cfg(any(test, feature = "test-support"))]
3257pub fn repo_path<S: AsRef<str> + ?Sized>(s: &S) -> RepoPath {
3258    RepoPath(RelPath::unix(s.as_ref()).unwrap().into())
3259}
3260
3261impl AsRef<Arc<RelPath>> for RepoPath {
3262    fn as_ref(&self) -> &Arc<RelPath> {
3263        &self.0
3264    }
3265}
3266
3267impl std::ops::Deref for RepoPath {
3268    type Target = RelPath;
3269
3270    fn deref(&self) -> &Self::Target {
3271        &self.0
3272    }
3273}
3274
3275#[derive(Debug)]
3276pub struct RepoPathDescendants<'a>(pub &'a RepoPath);
3277
3278impl MapSeekTarget<RepoPath> for RepoPathDescendants<'_> {
3279    fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
3280        if key.starts_with(self.0) {
3281            Ordering::Greater
3282        } else {
3283            self.0.cmp(key)
3284        }
3285    }
3286}
3287
3288fn parse_branch_input(input: &str) -> Result<Vec<Branch>> {
3289    let mut branches = Vec::new();
3290    for line in input.split('\n') {
3291        if line.is_empty() {
3292            continue;
3293        }
3294        let mut fields = line.split('\x00');
3295        let Some(head) = fields.next() else {
3296            continue;
3297        };
3298        let Some(head_sha) = fields.next().map(|f| f.to_string().into()) else {
3299            continue;
3300        };
3301        let Some(parent_sha) = fields.next().map(|f| f.to_string()) else {
3302            continue;
3303        };
3304        let Some(ref_name) = fields.next().map(|f| f.to_string().into()) else {
3305            continue;
3306        };
3307        let Some(upstream_name) = fields.next().map(|f| f.to_string()) else {
3308            continue;
3309        };
3310        let Some(upstream_tracking) = fields.next().and_then(|f| parse_upstream_track(f).ok())
3311        else {
3312            continue;
3313        };
3314        let Some(commiterdate) = fields.next().and_then(|f| f.parse::<i64>().ok()) else {
3315            continue;
3316        };
3317        let Some(author_name) = fields.next().map(|f| f.to_string().into()) else {
3318            continue;
3319        };
3320        let Some(subject) = fields.next().map(|f| f.to_string().into()) else {
3321            continue;
3322        };
3323
3324        branches.push(Branch {
3325            is_head: head == "*",
3326            ref_name,
3327            most_recent_commit: Some(CommitSummary {
3328                sha: head_sha,
3329                subject,
3330                commit_timestamp: commiterdate,
3331                author_name: author_name,
3332                has_parent: !parent_sha.is_empty(),
3333            }),
3334            upstream: if upstream_name.is_empty() {
3335                None
3336            } else {
3337                Some(Upstream {
3338                    ref_name: upstream_name.into(),
3339                    tracking: upstream_tracking,
3340                })
3341            },
3342        })
3343    }
3344
3345    Ok(branches)
3346}
3347
3348fn parse_upstream_track(upstream_track: &str) -> Result<UpstreamTracking> {
3349    if upstream_track.is_empty() {
3350        return Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
3351            ahead: 0,
3352            behind: 0,
3353        }));
3354    }
3355
3356    let upstream_track = upstream_track.strip_prefix("[").context("missing [")?;
3357    let upstream_track = upstream_track.strip_suffix("]").context("missing [")?;
3358    let mut ahead: u32 = 0;
3359    let mut behind: u32 = 0;
3360    for component in upstream_track.split(", ") {
3361        if component == "gone" {
3362            return Ok(UpstreamTracking::Gone);
3363        }
3364        if let Some(ahead_num) = component.strip_prefix("ahead ") {
3365            ahead = ahead_num.parse::<u32>()?;
3366        }
3367        if let Some(behind_num) = component.strip_prefix("behind ") {
3368            behind = behind_num.parse::<u32>()?;
3369        }
3370    }
3371    Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
3372        ahead,
3373        behind,
3374    }))
3375}
3376
3377fn checkpoint_author_envs() -> HashMap<String, String> {
3378    HashMap::from_iter([
3379        ("GIT_AUTHOR_NAME".to_string(), "Zed".to_string()),
3380        ("GIT_AUTHOR_EMAIL".to_string(), "hi@zed.dev".to_string()),
3381        ("GIT_COMMITTER_NAME".to_string(), "Zed".to_string()),
3382        ("GIT_COMMITTER_EMAIL".to_string(), "hi@zed.dev".to_string()),
3383    ])
3384}
3385
3386#[cfg(test)]
3387mod tests {
3388    use super::*;
3389    use gpui::TestAppContext;
3390
3391    fn disable_git_global_config() {
3392        unsafe {
3393            std::env::set_var("GIT_CONFIG_GLOBAL", "");
3394            std::env::set_var("GIT_CONFIG_SYSTEM", "");
3395        }
3396    }
3397
3398    #[gpui::test]
3399    async fn test_build_command_untrusted_includes_both_safety_args(cx: &mut TestAppContext) {
3400        cx.executor().allow_parking();
3401        let dir = tempfile::tempdir().unwrap();
3402        let git = GitBinary::new(
3403            PathBuf::from("git"),
3404            dir.path().to_path_buf(),
3405            cx.executor(),
3406            false,
3407        );
3408        let output = git
3409            .build_command(["version"])
3410            .output()
3411            .await
3412            .expect("git version should succeed");
3413        assert!(output.status.success());
3414
3415        let git = GitBinary::new(
3416            PathBuf::from("git"),
3417            dir.path().to_path_buf(),
3418            cx.executor(),
3419            false,
3420        );
3421        let output = git
3422            .build_command(["config", "--get", "core.fsmonitor"])
3423            .output()
3424            .await
3425            .expect("git config should run");
3426        let stdout = String::from_utf8_lossy(&output.stdout);
3427        assert_eq!(
3428            stdout.trim(),
3429            "false",
3430            "fsmonitor should be disabled for untrusted repos"
3431        );
3432
3433        git2::Repository::init(dir.path()).unwrap();
3434        let git = GitBinary::new(
3435            PathBuf::from("git"),
3436            dir.path().to_path_buf(),
3437            cx.executor(),
3438            false,
3439        );
3440        let output = git
3441            .build_command(["config", "--get", "core.hooksPath"])
3442            .output()
3443            .await
3444            .expect("git config should run");
3445        let stdout = String::from_utf8_lossy(&output.stdout);
3446        assert_eq!(
3447            stdout.trim(),
3448            "/dev/null",
3449            "hooksPath should be /dev/null for untrusted repos"
3450        );
3451    }
3452
3453    #[gpui::test]
3454    async fn test_build_command_trusted_only_disables_fsmonitor(cx: &mut TestAppContext) {
3455        cx.executor().allow_parking();
3456        let dir = tempfile::tempdir().unwrap();
3457        git2::Repository::init(dir.path()).unwrap();
3458
3459        let git = GitBinary::new(
3460            PathBuf::from("git"),
3461            dir.path().to_path_buf(),
3462            cx.executor(),
3463            true,
3464        );
3465        let output = git
3466            .build_command(["config", "--get", "core.fsmonitor"])
3467            .output()
3468            .await
3469            .expect("git config should run");
3470        let stdout = String::from_utf8_lossy(&output.stdout);
3471        assert_eq!(
3472            stdout.trim(),
3473            "false",
3474            "fsmonitor should be disabled even for trusted repos"
3475        );
3476
3477        let git = GitBinary::new(
3478            PathBuf::from("git"),
3479            dir.path().to_path_buf(),
3480            cx.executor(),
3481            true,
3482        );
3483        let output = git
3484            .build_command(["config", "--get", "core.hooksPath"])
3485            .output()
3486            .await
3487            .expect("git config should run");
3488        assert!(
3489            !output.status.success(),
3490            "hooksPath should NOT be overridden for trusted repos"
3491        );
3492    }
3493
3494    #[gpui::test]
3495    async fn test_checkpoint_basic(cx: &mut TestAppContext) {
3496        disable_git_global_config();
3497
3498        cx.executor().allow_parking();
3499
3500        let repo_dir = tempfile::tempdir().unwrap();
3501
3502        git2::Repository::init(repo_dir.path()).unwrap();
3503        let file_path = repo_dir.path().join("file");
3504        smol::fs::write(&file_path, "initial").await.unwrap();
3505
3506        let repo = RealGitRepository::new(
3507            &repo_dir.path().join(".git"),
3508            None,
3509            Some("git".into()),
3510            cx.executor(),
3511        )
3512        .unwrap();
3513
3514        repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
3515            .await
3516            .unwrap();
3517        repo.commit(
3518            "Initial commit".into(),
3519            None,
3520            CommitOptions::default(),
3521            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3522            Arc::new(checkpoint_author_envs()),
3523        )
3524        .await
3525        .unwrap();
3526
3527        smol::fs::write(&file_path, "modified before checkpoint")
3528            .await
3529            .unwrap();
3530        smol::fs::write(repo_dir.path().join("new_file_before_checkpoint"), "1")
3531            .await
3532            .unwrap();
3533        let checkpoint = repo.checkpoint().await.unwrap();
3534
3535        // Ensure the user can't see any branches after creating a checkpoint.
3536        assert_eq!(repo.branches().await.unwrap().len(), 1);
3537
3538        smol::fs::write(&file_path, "modified after checkpoint")
3539            .await
3540            .unwrap();
3541        repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
3542            .await
3543            .unwrap();
3544        repo.commit(
3545            "Commit after checkpoint".into(),
3546            None,
3547            CommitOptions::default(),
3548            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3549            Arc::new(checkpoint_author_envs()),
3550        )
3551        .await
3552        .unwrap();
3553
3554        smol::fs::remove_file(repo_dir.path().join("new_file_before_checkpoint"))
3555            .await
3556            .unwrap();
3557        smol::fs::write(repo_dir.path().join("new_file_after_checkpoint"), "2")
3558            .await
3559            .unwrap();
3560
3561        // Ensure checkpoint stays alive even after a Git GC.
3562        repo.gc().await.unwrap();
3563        repo.restore_checkpoint(checkpoint.clone()).await.unwrap();
3564
3565        assert_eq!(
3566            smol::fs::read_to_string(&file_path).await.unwrap(),
3567            "modified before checkpoint"
3568        );
3569        assert_eq!(
3570            smol::fs::read_to_string(repo_dir.path().join("new_file_before_checkpoint"))
3571                .await
3572                .unwrap(),
3573            "1"
3574        );
3575        // See TODO above
3576        // assert_eq!(
3577        //     smol::fs::read_to_string(repo_dir.path().join("new_file_after_checkpoint"))
3578        //         .await
3579        //         .ok(),
3580        //     None
3581        // );
3582    }
3583
3584    #[gpui::test]
3585    async fn test_checkpoint_empty_repo(cx: &mut TestAppContext) {
3586        disable_git_global_config();
3587
3588        cx.executor().allow_parking();
3589
3590        let repo_dir = tempfile::tempdir().unwrap();
3591        git2::Repository::init(repo_dir.path()).unwrap();
3592        let repo = RealGitRepository::new(
3593            &repo_dir.path().join(".git"),
3594            None,
3595            Some("git".into()),
3596            cx.executor(),
3597        )
3598        .unwrap();
3599
3600        smol::fs::write(repo_dir.path().join("foo"), "foo")
3601            .await
3602            .unwrap();
3603        let checkpoint_sha = repo.checkpoint().await.unwrap();
3604
3605        // Ensure the user can't see any branches after creating a checkpoint.
3606        assert_eq!(repo.branches().await.unwrap().len(), 1);
3607
3608        smol::fs::write(repo_dir.path().join("foo"), "bar")
3609            .await
3610            .unwrap();
3611        smol::fs::write(repo_dir.path().join("baz"), "qux")
3612            .await
3613            .unwrap();
3614        repo.restore_checkpoint(checkpoint_sha).await.unwrap();
3615        assert_eq!(
3616            smol::fs::read_to_string(repo_dir.path().join("foo"))
3617                .await
3618                .unwrap(),
3619            "foo"
3620        );
3621        // See TODOs above
3622        // assert_eq!(
3623        //     smol::fs::read_to_string(repo_dir.path().join("baz"))
3624        //         .await
3625        //         .ok(),
3626        //     None
3627        // );
3628    }
3629
3630    #[gpui::test]
3631    async fn test_compare_checkpoints(cx: &mut TestAppContext) {
3632        disable_git_global_config();
3633
3634        cx.executor().allow_parking();
3635
3636        let repo_dir = tempfile::tempdir().unwrap();
3637        git2::Repository::init(repo_dir.path()).unwrap();
3638        let repo = RealGitRepository::new(
3639            &repo_dir.path().join(".git"),
3640            None,
3641            Some("git".into()),
3642            cx.executor(),
3643        )
3644        .unwrap();
3645
3646        smol::fs::write(repo_dir.path().join("file1"), "content1")
3647            .await
3648            .unwrap();
3649        let checkpoint1 = repo.checkpoint().await.unwrap();
3650
3651        smol::fs::write(repo_dir.path().join("file2"), "content2")
3652            .await
3653            .unwrap();
3654        let checkpoint2 = repo.checkpoint().await.unwrap();
3655
3656        assert!(
3657            !repo
3658                .compare_checkpoints(checkpoint1, checkpoint2.clone())
3659                .await
3660                .unwrap()
3661        );
3662
3663        let checkpoint3 = repo.checkpoint().await.unwrap();
3664        assert!(
3665            repo.compare_checkpoints(checkpoint2, checkpoint3)
3666                .await
3667                .unwrap()
3668        );
3669    }
3670
3671    #[gpui::test]
3672    async fn test_checkpoint_exclude_binary_files(cx: &mut TestAppContext) {
3673        disable_git_global_config();
3674
3675        cx.executor().allow_parking();
3676
3677        let repo_dir = tempfile::tempdir().unwrap();
3678        let text_path = repo_dir.path().join("main.rs");
3679        let bin_path = repo_dir.path().join("binary.o");
3680
3681        git2::Repository::init(repo_dir.path()).unwrap();
3682
3683        smol::fs::write(&text_path, "fn main() {}").await.unwrap();
3684
3685        smol::fs::write(&bin_path, "some binary file here")
3686            .await
3687            .unwrap();
3688
3689        let repo = RealGitRepository::new(
3690            &repo_dir.path().join(".git"),
3691            None,
3692            Some("git".into()),
3693            cx.executor(),
3694        )
3695        .unwrap();
3696
3697        // initial commit
3698        repo.stage_paths(vec![repo_path("main.rs")], Arc::new(HashMap::default()))
3699            .await
3700            .unwrap();
3701        repo.commit(
3702            "Initial commit".into(),
3703            None,
3704            CommitOptions::default(),
3705            AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3706            Arc::new(checkpoint_author_envs()),
3707        )
3708        .await
3709        .unwrap();
3710
3711        let checkpoint = repo.checkpoint().await.unwrap();
3712
3713        smol::fs::write(&text_path, "fn main() { println!(\"Modified\"); }")
3714            .await
3715            .unwrap();
3716        smol::fs::write(&bin_path, "Modified binary file")
3717            .await
3718            .unwrap();
3719
3720        repo.restore_checkpoint(checkpoint).await.unwrap();
3721
3722        // Text files should be restored to checkpoint state,
3723        // but binaries should not (they aren't tracked)
3724        assert_eq!(
3725            smol::fs::read_to_string(&text_path).await.unwrap(),
3726            "fn main() {}"
3727        );
3728
3729        assert_eq!(
3730            smol::fs::read_to_string(&bin_path).await.unwrap(),
3731            "Modified binary file"
3732        );
3733    }
3734
3735    #[test]
3736    fn test_branches_parsing() {
3737        // suppress "help: octal escapes are not supported, `\0` is always null"
3738        #[allow(clippy::octal_escapes)]
3739        let input = "*\0060964da10574cd9bf06463a53bf6e0769c5c45e\0\0refs/heads/zed-patches\0refs/remotes/origin/zed-patches\0\01733187470\0John Doe\0generated protobuf\n";
3740        assert_eq!(
3741            parse_branch_input(input).unwrap(),
3742            vec![Branch {
3743                is_head: true,
3744                ref_name: "refs/heads/zed-patches".into(),
3745                upstream: Some(Upstream {
3746                    ref_name: "refs/remotes/origin/zed-patches".into(),
3747                    tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3748                        ahead: 0,
3749                        behind: 0
3750                    })
3751                }),
3752                most_recent_commit: Some(CommitSummary {
3753                    sha: "060964da10574cd9bf06463a53bf6e0769c5c45e".into(),
3754                    subject: "generated protobuf".into(),
3755                    commit_timestamp: 1733187470,
3756                    author_name: SharedString::new_static("John Doe"),
3757                    has_parent: false,
3758                })
3759            }]
3760        )
3761    }
3762
3763    #[test]
3764    fn test_branches_parsing_containing_refs_with_missing_fields() {
3765        #[allow(clippy::octal_escapes)]
3766        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";
3767
3768        let branches = parse_branch_input(input).unwrap();
3769        assert_eq!(branches.len(), 2);
3770        assert_eq!(
3771            branches,
3772            vec![
3773                Branch {
3774                    is_head: false,
3775                    ref_name: "refs/heads/dev".into(),
3776                    upstream: None,
3777                    most_recent_commit: Some(CommitSummary {
3778                        sha: "eb0cae33272689bd11030822939dd2701c52f81e".into(),
3779                        subject: "Add feature".into(),
3780                        commit_timestamp: 1762948725,
3781                        author_name: SharedString::new_static("Zed"),
3782                        has_parent: true,
3783                    })
3784                },
3785                Branch {
3786                    is_head: true,
3787                    ref_name: "refs/heads/main".into(),
3788                    upstream: None,
3789                    most_recent_commit: Some(CommitSummary {
3790                        sha: "895951d681e5561478c0acdd6905e8aacdfd2249".into(),
3791                        subject: "Initial commit".into(),
3792                        commit_timestamp: 1762948695,
3793                        author_name: SharedString::new_static("Zed"),
3794                        has_parent: false,
3795                    })
3796                }
3797            ]
3798        )
3799    }
3800
3801    #[test]
3802    fn test_upstream_branch_name() {
3803        let upstream = Upstream {
3804            ref_name: "refs/remotes/origin/feature/branch".into(),
3805            tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3806                ahead: 0,
3807                behind: 0,
3808            }),
3809        };
3810        assert_eq!(upstream.branch_name(), Some("feature/branch"));
3811
3812        let upstream = Upstream {
3813            ref_name: "refs/remotes/upstream/main".into(),
3814            tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3815                ahead: 0,
3816                behind: 0,
3817            }),
3818        };
3819        assert_eq!(upstream.branch_name(), Some("main"));
3820
3821        let upstream = Upstream {
3822            ref_name: "refs/heads/local".into(),
3823            tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3824                ahead: 0,
3825                behind: 0,
3826            }),
3827        };
3828        assert_eq!(upstream.branch_name(), None);
3829
3830        // Test case where upstream branch name differs from what might be the local branch name
3831        let upstream = Upstream {
3832            ref_name: "refs/remotes/origin/feature/git-pull-request".into(),
3833            tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3834                ahead: 0,
3835                behind: 0,
3836            }),
3837        };
3838        assert_eq!(upstream.branch_name(), Some("feature/git-pull-request"));
3839    }
3840
3841    #[test]
3842    fn test_parse_worktrees_from_str() {
3843        // Empty input
3844        let result = parse_worktrees_from_str("");
3845        assert!(result.is_empty());
3846
3847        // Single worktree (main)
3848        let input = "worktree /home/user/project\nHEAD abc123def\nbranch refs/heads/main\n\n";
3849        let result = parse_worktrees_from_str(input);
3850        assert_eq!(result.len(), 1);
3851        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3852        assert_eq!(result[0].sha.as_ref(), "abc123def");
3853        assert_eq!(result[0].ref_name.as_ref(), "refs/heads/main");
3854
3855        // Multiple worktrees
3856        let input = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n\n\
3857                      worktree /home/user/project-wt\nHEAD def456\nbranch refs/heads/feature\n\n";
3858        let result = parse_worktrees_from_str(input);
3859        assert_eq!(result.len(), 2);
3860        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3861        assert_eq!(result[0].ref_name.as_ref(), "refs/heads/main");
3862        assert_eq!(result[1].path, PathBuf::from("/home/user/project-wt"));
3863        assert_eq!(result[1].ref_name.as_ref(), "refs/heads/feature");
3864
3865        // Detached HEAD entry (should be skipped since ref_name won't parse)
3866        let input = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n\n\
3867                      worktree /home/user/detached\nHEAD def456\ndetached\n\n";
3868        let result = parse_worktrees_from_str(input);
3869        assert_eq!(result.len(), 1);
3870        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3871
3872        // Bare repo entry (should be skipped)
3873        let input = "worktree /home/user/bare.git\nHEAD abc123\nbare\n\n\
3874                      worktree /home/user/project\nHEAD def456\nbranch refs/heads/main\n\n";
3875        let result = parse_worktrees_from_str(input);
3876        assert_eq!(result.len(), 1);
3877        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3878
3879        // Extra porcelain lines (locked, prunable) should be ignored
3880        let input = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n\n\
3881                      worktree /home/user/locked-wt\nHEAD def456\nbranch refs/heads/locked-branch\nlocked\n\n\
3882                      worktree /home/user/prunable-wt\nHEAD 789aaa\nbranch refs/heads/prunable-branch\nprunable\n\n";
3883        let result = parse_worktrees_from_str(input);
3884        assert_eq!(result.len(), 3);
3885        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3886        assert_eq!(result[0].ref_name.as_ref(), "refs/heads/main");
3887        assert_eq!(result[1].path, PathBuf::from("/home/user/locked-wt"));
3888        assert_eq!(result[1].ref_name.as_ref(), "refs/heads/locked-branch");
3889        assert_eq!(result[2].path, PathBuf::from("/home/user/prunable-wt"));
3890        assert_eq!(result[2].ref_name.as_ref(), "refs/heads/prunable-branch");
3891
3892        // Leading/trailing whitespace on lines should be tolerated
3893        let input =
3894            "  worktree /home/user/project  \n  HEAD abc123  \n  branch refs/heads/main  \n\n";
3895        let result = parse_worktrees_from_str(input);
3896        assert_eq!(result.len(), 1);
3897        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3898        assert_eq!(result[0].sha.as_ref(), "abc123");
3899        assert_eq!(result[0].ref_name.as_ref(), "refs/heads/main");
3900
3901        // Windows-style line endings should be handled
3902        let input = "worktree /home/user/project\r\nHEAD abc123\r\nbranch refs/heads/main\r\n\r\n";
3903        let result = parse_worktrees_from_str(input);
3904        assert_eq!(result.len(), 1);
3905        assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3906        assert_eq!(result[0].sha.as_ref(), "abc123");
3907        assert_eq!(result[0].ref_name.as_ref(), "refs/heads/main");
3908    }
3909
3910    const TEST_WORKTREE_DIRECTORIES: &[&str] =
3911        &["../worktrees", ".git/zed-worktrees", "my-worktrees/"];
3912
3913    #[gpui::test]
3914    async fn test_create_and_list_worktrees(cx: &mut TestAppContext) {
3915        disable_git_global_config();
3916        cx.executor().allow_parking();
3917
3918        for worktree_dir_setting in TEST_WORKTREE_DIRECTORIES {
3919            let repo_dir = tempfile::tempdir().unwrap();
3920            git2::Repository::init(repo_dir.path()).unwrap();
3921
3922            let repo = RealGitRepository::new(
3923                &repo_dir.path().join(".git"),
3924                None,
3925                Some("git".into()),
3926                cx.executor(),
3927            )
3928            .unwrap();
3929
3930            // Create an initial commit (required for worktrees)
3931            smol::fs::write(repo_dir.path().join("file.txt"), "content")
3932                .await
3933                .unwrap();
3934            repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
3935                .await
3936                .unwrap();
3937            repo.commit(
3938                "Initial commit".into(),
3939                None,
3940                CommitOptions::default(),
3941                AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3942                Arc::new(checkpoint_author_envs()),
3943            )
3944            .await
3945            .unwrap();
3946
3947            // List worktrees — should have just the main one
3948            let worktrees = repo.worktrees().await.unwrap();
3949            assert_eq!(worktrees.len(), 1);
3950            assert_eq!(
3951                worktrees[0].path.canonicalize().unwrap(),
3952                repo_dir.path().canonicalize().unwrap()
3953            );
3954
3955            // Create a new worktree
3956            repo.create_worktree(
3957                "test-branch".to_string(),
3958                resolve_worktree_directory(repo_dir.path(), worktree_dir_setting),
3959                Some("HEAD".to_string()),
3960            )
3961            .await
3962            .unwrap();
3963
3964            // List worktrees — should have two
3965            let worktrees = repo.worktrees().await.unwrap();
3966            assert_eq!(worktrees.len(), 2);
3967
3968            let expected_path =
3969                worktree_path_for_branch(repo_dir.path(), worktree_dir_setting, "test-branch");
3970            let new_worktree = worktrees
3971                .iter()
3972                .find(|w| w.branch() == "test-branch")
3973                .expect("should find worktree with test-branch");
3974            assert_eq!(
3975                new_worktree.path.canonicalize().unwrap(),
3976                expected_path.canonicalize().unwrap(),
3977                "failed for worktree_directory setting: {worktree_dir_setting:?}"
3978            );
3979
3980            // Clean up so the next iteration starts fresh
3981            repo.remove_worktree(expected_path, true).await.unwrap();
3982
3983            // Clean up the worktree base directory if it was created outside repo_dir
3984            // (e.g. for the "../worktrees" setting, it won't be inside the TempDir)
3985            let resolved_dir = resolve_worktree_directory(repo_dir.path(), worktree_dir_setting);
3986            if !resolved_dir.starts_with(repo_dir.path()) {
3987                let _ = std::fs::remove_dir_all(&resolved_dir);
3988            }
3989        }
3990    }
3991
3992    #[gpui::test]
3993    async fn test_remove_worktree(cx: &mut TestAppContext) {
3994        disable_git_global_config();
3995        cx.executor().allow_parking();
3996
3997        for worktree_dir_setting in TEST_WORKTREE_DIRECTORIES {
3998            let repo_dir = tempfile::tempdir().unwrap();
3999            git2::Repository::init(repo_dir.path()).unwrap();
4000
4001            let repo = RealGitRepository::new(
4002                &repo_dir.path().join(".git"),
4003                None,
4004                Some("git".into()),
4005                cx.executor(),
4006            )
4007            .unwrap();
4008
4009            // Create an initial commit
4010            smol::fs::write(repo_dir.path().join("file.txt"), "content")
4011                .await
4012                .unwrap();
4013            repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
4014                .await
4015                .unwrap();
4016            repo.commit(
4017                "Initial commit".into(),
4018                None,
4019                CommitOptions::default(),
4020                AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
4021                Arc::new(checkpoint_author_envs()),
4022            )
4023            .await
4024            .unwrap();
4025
4026            // Create a worktree
4027            repo.create_worktree(
4028                "to-remove".to_string(),
4029                resolve_worktree_directory(repo_dir.path(), worktree_dir_setting),
4030                Some("HEAD".to_string()),
4031            )
4032            .await
4033            .unwrap();
4034
4035            let worktree_path =
4036                worktree_path_for_branch(repo_dir.path(), worktree_dir_setting, "to-remove");
4037            assert!(worktree_path.exists());
4038
4039            // Remove the worktree
4040            repo.remove_worktree(worktree_path.clone(), false)
4041                .await
4042                .unwrap();
4043
4044            // Verify it's gone from the list
4045            let worktrees = repo.worktrees().await.unwrap();
4046            assert_eq!(worktrees.len(), 1);
4047            assert!(
4048                worktrees.iter().all(|w| w.branch() != "to-remove"),
4049                "removed worktree should not appear in list"
4050            );
4051
4052            // Verify the directory is removed
4053            assert!(!worktree_path.exists());
4054
4055            // Clean up the worktree base directory if it was created outside repo_dir
4056            // (e.g. for the "../worktrees" setting, it won't be inside the TempDir)
4057            let resolved_dir = resolve_worktree_directory(repo_dir.path(), worktree_dir_setting);
4058            if !resolved_dir.starts_with(repo_dir.path()) {
4059                let _ = std::fs::remove_dir_all(&resolved_dir);
4060            }
4061        }
4062    }
4063
4064    #[gpui::test]
4065    async fn test_remove_worktree_force(cx: &mut TestAppContext) {
4066        disable_git_global_config();
4067        cx.executor().allow_parking();
4068
4069        for worktree_dir_setting in TEST_WORKTREE_DIRECTORIES {
4070            let repo_dir = tempfile::tempdir().unwrap();
4071            git2::Repository::init(repo_dir.path()).unwrap();
4072
4073            let repo = RealGitRepository::new(
4074                &repo_dir.path().join(".git"),
4075                None,
4076                Some("git".into()),
4077                cx.executor(),
4078            )
4079            .unwrap();
4080
4081            // Create an initial commit
4082            smol::fs::write(repo_dir.path().join("file.txt"), "content")
4083                .await
4084                .unwrap();
4085            repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
4086                .await
4087                .unwrap();
4088            repo.commit(
4089                "Initial commit".into(),
4090                None,
4091                CommitOptions::default(),
4092                AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
4093                Arc::new(checkpoint_author_envs()),
4094            )
4095            .await
4096            .unwrap();
4097
4098            // Create a worktree
4099            repo.create_worktree(
4100                "dirty-wt".to_string(),
4101                resolve_worktree_directory(repo_dir.path(), worktree_dir_setting),
4102                Some("HEAD".to_string()),
4103            )
4104            .await
4105            .unwrap();
4106
4107            let worktree_path =
4108                worktree_path_for_branch(repo_dir.path(), worktree_dir_setting, "dirty-wt");
4109
4110            // Add uncommitted changes in the worktree
4111            smol::fs::write(worktree_path.join("dirty-file.txt"), "uncommitted")
4112                .await
4113                .unwrap();
4114
4115            // Non-force removal should fail with dirty worktree
4116            let result = repo.remove_worktree(worktree_path.clone(), false).await;
4117            assert!(
4118                result.is_err(),
4119                "non-force removal of dirty worktree should fail"
4120            );
4121
4122            // Force removal should succeed
4123            repo.remove_worktree(worktree_path.clone(), true)
4124                .await
4125                .unwrap();
4126
4127            let worktrees = repo.worktrees().await.unwrap();
4128            assert_eq!(worktrees.len(), 1);
4129            assert!(!worktree_path.exists());
4130
4131            // Clean up the worktree base directory if it was created outside repo_dir
4132            // (e.g. for the "../worktrees" setting, it won't be inside the TempDir)
4133            let resolved_dir = resolve_worktree_directory(repo_dir.path(), worktree_dir_setting);
4134            if !resolved_dir.starts_with(repo_dir.path()) {
4135                let _ = std::fs::remove_dir_all(&resolved_dir);
4136            }
4137        }
4138    }
4139
4140    #[gpui::test]
4141    async fn test_rename_worktree(cx: &mut TestAppContext) {
4142        disable_git_global_config();
4143        cx.executor().allow_parking();
4144
4145        for worktree_dir_setting in TEST_WORKTREE_DIRECTORIES {
4146            let repo_dir = tempfile::tempdir().unwrap();
4147            git2::Repository::init(repo_dir.path()).unwrap();
4148
4149            let repo = RealGitRepository::new(
4150                &repo_dir.path().join(".git"),
4151                None,
4152                Some("git".into()),
4153                cx.executor(),
4154            )
4155            .unwrap();
4156
4157            // Create an initial commit
4158            smol::fs::write(repo_dir.path().join("file.txt"), "content")
4159                .await
4160                .unwrap();
4161            repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
4162                .await
4163                .unwrap();
4164            repo.commit(
4165                "Initial commit".into(),
4166                None,
4167                CommitOptions::default(),
4168                AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
4169                Arc::new(checkpoint_author_envs()),
4170            )
4171            .await
4172            .unwrap();
4173
4174            // Create a worktree
4175            repo.create_worktree(
4176                "old-name".to_string(),
4177                resolve_worktree_directory(repo_dir.path(), worktree_dir_setting),
4178                Some("HEAD".to_string()),
4179            )
4180            .await
4181            .unwrap();
4182
4183            let old_path =
4184                worktree_path_for_branch(repo_dir.path(), worktree_dir_setting, "old-name");
4185            assert!(old_path.exists());
4186
4187            // Move the worktree to a new path
4188            let new_path =
4189                resolve_worktree_directory(repo_dir.path(), worktree_dir_setting).join("new-name");
4190            repo.rename_worktree(old_path.clone(), new_path.clone())
4191                .await
4192                .unwrap();
4193
4194            // Verify the old path is gone and new path exists
4195            assert!(!old_path.exists());
4196            assert!(new_path.exists());
4197
4198            // Verify it shows up in worktree list at the new path
4199            let worktrees = repo.worktrees().await.unwrap();
4200            assert_eq!(worktrees.len(), 2);
4201            let moved_worktree = worktrees
4202                .iter()
4203                .find(|w| w.branch() == "old-name")
4204                .expect("should find worktree by branch name");
4205            assert_eq!(
4206                moved_worktree.path.canonicalize().unwrap(),
4207                new_path.canonicalize().unwrap()
4208            );
4209
4210            // Clean up so the next iteration starts fresh
4211            repo.remove_worktree(new_path, true).await.unwrap();
4212
4213            // Clean up the worktree base directory if it was created outside repo_dir
4214            // (e.g. for the "../worktrees" setting, it won't be inside the TempDir)
4215            let resolved_dir = resolve_worktree_directory(repo_dir.path(), worktree_dir_setting);
4216            if !resolved_dir.starts_with(repo_dir.path()) {
4217                let _ = std::fs::remove_dir_all(&resolved_dir);
4218            }
4219        }
4220    }
4221
4222    #[test]
4223    fn test_resolve_worktree_directory() {
4224        let work_dir = Path::new("/code/my-project");
4225
4226        // Sibling directory — outside project, so repo dir name is appended
4227        assert_eq!(
4228            resolve_worktree_directory(work_dir, "../worktrees"),
4229            PathBuf::from("/code/worktrees/my-project")
4230        );
4231
4232        // Git subdir — inside project, no repo name appended
4233        assert_eq!(
4234            resolve_worktree_directory(work_dir, ".git/zed-worktrees"),
4235            PathBuf::from("/code/my-project/.git/zed-worktrees")
4236        );
4237
4238        // Simple subdir — inside project, no repo name appended
4239        assert_eq!(
4240            resolve_worktree_directory(work_dir, "my-worktrees"),
4241            PathBuf::from("/code/my-project/my-worktrees")
4242        );
4243
4244        // Trailing slash is stripped
4245        assert_eq!(
4246            resolve_worktree_directory(work_dir, "../worktrees/"),
4247            PathBuf::from("/code/worktrees/my-project")
4248        );
4249        assert_eq!(
4250            resolve_worktree_directory(work_dir, "my-worktrees/"),
4251            PathBuf::from("/code/my-project/my-worktrees")
4252        );
4253
4254        // Multiple trailing slashes
4255        assert_eq!(
4256            resolve_worktree_directory(work_dir, "foo///"),
4257            PathBuf::from("/code/my-project/foo")
4258        );
4259
4260        // Trailing backslashes (Windows-style)
4261        assert_eq!(
4262            resolve_worktree_directory(work_dir, "my-worktrees\\"),
4263            PathBuf::from("/code/my-project/my-worktrees")
4264        );
4265        assert_eq!(
4266            resolve_worktree_directory(work_dir, "foo\\/\\"),
4267            PathBuf::from("/code/my-project/foo")
4268        );
4269
4270        // Empty string resolves to the working directory itself (inside)
4271        assert_eq!(
4272            resolve_worktree_directory(work_dir, ""),
4273            PathBuf::from("/code/my-project")
4274        );
4275
4276        // Just ".." — outside project, repo dir name appended
4277        assert_eq!(
4278            resolve_worktree_directory(work_dir, ".."),
4279            PathBuf::from("/code/my-project")
4280        );
4281    }
4282
4283    #[test]
4284    fn test_original_repo_path_from_common_dir() {
4285        // Normal repo: common_dir is <work_dir>/.git
4286        assert_eq!(
4287            original_repo_path_from_common_dir(Path::new("/code/zed5/.git")),
4288            PathBuf::from("/code/zed5")
4289        );
4290
4291        // Worktree: common_dir is the main repo's .git
4292        // (same result — that's the point, it always traces back to the original)
4293        assert_eq!(
4294            original_repo_path_from_common_dir(Path::new("/code/zed5/.git")),
4295            PathBuf::from("/code/zed5")
4296        );
4297
4298        // Bare repo: no .git suffix, returns as-is
4299        assert_eq!(
4300            original_repo_path_from_common_dir(Path::new("/code/zed5.git")),
4301            PathBuf::from("/code/zed5.git")
4302        );
4303
4304        // Root-level .git directory
4305        assert_eq!(
4306            original_repo_path_from_common_dir(Path::new("/.git")),
4307            PathBuf::from("/")
4308        );
4309    }
4310
4311    #[test]
4312    fn test_validate_worktree_directory() {
4313        let work_dir = Path::new("/code/my-project");
4314
4315        // Valid: sibling
4316        assert!(validate_worktree_directory(work_dir, "../worktrees").is_ok());
4317
4318        // Valid: subdirectory
4319        assert!(validate_worktree_directory(work_dir, ".git/zed-worktrees").is_ok());
4320        assert!(validate_worktree_directory(work_dir, "my-worktrees").is_ok());
4321
4322        // Invalid: just ".." would resolve back to the working directory itself
4323        let err = validate_worktree_directory(work_dir, "..").unwrap_err();
4324        assert!(err.to_string().contains("must not be \"..\""));
4325
4326        // Invalid: ".." with trailing separators
4327        let err = validate_worktree_directory(work_dir, "..\\").unwrap_err();
4328        assert!(err.to_string().contains("must not be \"..\""));
4329        let err = validate_worktree_directory(work_dir, "../").unwrap_err();
4330        assert!(err.to_string().contains("must not be \"..\""));
4331
4332        // Invalid: empty string would resolve to the working directory itself
4333        let err = validate_worktree_directory(work_dir, "").unwrap_err();
4334        assert!(err.to_string().contains("must not be empty"));
4335
4336        // Invalid: absolute path
4337        let err = validate_worktree_directory(work_dir, "/tmp/worktrees").unwrap_err();
4338        assert!(err.to_string().contains("relative path"));
4339
4340        // Invalid: "/" is absolute on Unix
4341        let err = validate_worktree_directory(work_dir, "/").unwrap_err();
4342        assert!(err.to_string().contains("relative path"));
4343
4344        // Invalid: "///" is absolute
4345        let err = validate_worktree_directory(work_dir, "///").unwrap_err();
4346        assert!(err.to_string().contains("relative path"));
4347
4348        // Invalid: escapes too far up
4349        let err = validate_worktree_directory(work_dir, "../../other-project/wt").unwrap_err();
4350        assert!(err.to_string().contains("outside"));
4351    }
4352
4353    #[test]
4354    fn test_worktree_path_for_branch() {
4355        let work_dir = Path::new("/code/my-project");
4356
4357        // Outside project — repo dir name is part of the resolved directory
4358        assert_eq!(
4359            worktree_path_for_branch(work_dir, "../worktrees", "feature/foo"),
4360            PathBuf::from("/code/worktrees/my-project/feature/foo")
4361        );
4362
4363        // Inside project — no repo dir name inserted
4364        assert_eq!(
4365            worktree_path_for_branch(work_dir, ".git/zed-worktrees", "my-branch"),
4366            PathBuf::from("/code/my-project/.git/zed-worktrees/my-branch")
4367        );
4368
4369        // Trailing slash on setting (inside project)
4370        assert_eq!(
4371            worktree_path_for_branch(work_dir, "my-worktrees/", "branch"),
4372            PathBuf::from("/code/my-project/my-worktrees/branch")
4373        );
4374    }
4375
4376    impl RealGitRepository {
4377        /// Force a Git garbage collection on the repository.
4378        fn gc(&self) -> BoxFuture<'_, Result<()>> {
4379            let working_directory = self.working_directory();
4380            let git_binary_path = self.any_git_binary_path.clone();
4381            let executor = self.executor.clone();
4382            self.executor
4383                .spawn(async move {
4384                    let git_binary_path = git_binary_path.clone();
4385                    let working_directory = working_directory?;
4386                    let git = GitBinary::new(git_binary_path, working_directory, executor, true);
4387                    git.run(&["gc", "--prune"]).await?;
4388                    Ok(())
4389                })
4390                .boxed()
4391        }
4392    }
4393}