repository.rs

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