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