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