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::future::BoxFuture;
8use futures::io::BufWriter;
9use futures::{AsyncWriteExt, FutureExt as _, select_biased};
10use git2::BranchType;
11use gpui::{AppContext as _, AsyncApp, BackgroundExecutor, SharedString, Task};
12use parking_lot::Mutex;
13use rope::Rope;
14use schemars::JsonSchema;
15use serde::Deserialize;
16use smol::io::{AsyncBufReadExt, AsyncReadExt, BufReader};
17use std::ffi::{OsStr, OsString};
18use std::process::{ExitStatus, Stdio};
19use std::{
20 cmp::Ordering,
21 future,
22 path::{Path, PathBuf},
23 sync::Arc,
24};
25use sum_tree::MapSeekTarget;
26use thiserror::Error;
27use util::command::new_smol_command;
28use util::paths::PathStyle;
29use util::rel_path::RelPath;
30use util::{ResultExt, paths};
31use uuid::Uuid;
32
33pub use askpass::{AskPassDelegate, AskPassResult, AskPassSession};
34
35pub const REMOTE_CANCELLED_BY_USER: &str = "Operation cancelled by user";
36
37#[derive(Clone, Debug, Hash, PartialEq, Eq)]
38pub struct Branch {
39 pub is_head: bool,
40 pub ref_name: SharedString,
41 pub upstream: Option<Upstream>,
42 pub most_recent_commit: Option<CommitSummary>,
43}
44
45impl Branch {
46 pub fn name(&self) -> &str {
47 self.ref_name
48 .as_ref()
49 .strip_prefix("refs/heads/")
50 .or_else(|| self.ref_name.as_ref().strip_prefix("refs/remotes/"))
51 .unwrap_or(self.ref_name.as_ref())
52 }
53
54 pub fn is_remote(&self) -> bool {
55 self.ref_name.starts_with("refs/remotes/")
56 }
57
58 pub fn tracking_status(&self) -> Option<UpstreamTrackingStatus> {
59 self.upstream
60 .as_ref()
61 .and_then(|upstream| upstream.tracking.status())
62 }
63
64 pub fn priority_key(&self) -> (bool, Option<i64>) {
65 (
66 self.is_head,
67 self.most_recent_commit
68 .as_ref()
69 .map(|commit| commit.commit_timestamp),
70 )
71 }
72}
73
74#[derive(Clone, Debug, Hash, PartialEq, Eq)]
75pub struct Worktree {
76 pub path: PathBuf,
77 pub ref_name: SharedString,
78 pub sha: SharedString,
79}
80
81impl Worktree {
82 pub fn branch(&self) -> &str {
83 self.ref_name
84 .as_ref()
85 .strip_prefix("refs/heads/")
86 .or_else(|| self.ref_name.as_ref().strip_prefix("refs/remotes/"))
87 .unwrap_or(self.ref_name.as_ref())
88 }
89}
90
91pub fn parse_worktrees_from_str<T: AsRef<str>>(raw_worktrees: T) -> Vec<Worktree> {
92 let mut worktrees = Vec::new();
93 let entries = raw_worktrees.as_ref().split("\n\n");
94 for entry in entries {
95 let mut parts = entry.splitn(3, '\n');
96 let path = parts
97 .next()
98 .and_then(|p| p.split_once(' ').map(|(_, path)| path.to_string()));
99 let sha = parts
100 .next()
101 .and_then(|p| p.split_once(' ').map(|(_, sha)| sha.to_string()));
102 let ref_name = parts
103 .next()
104 .and_then(|p| p.split_once(' ').map(|(_, ref_name)| ref_name.to_string()));
105
106 if let (Some(path), Some(sha), Some(ref_name)) = (path, sha, ref_name) {
107 worktrees.push(Worktree {
108 path: PathBuf::from(path),
109 ref_name: ref_name.into(),
110 sha: sha.into(),
111 })
112 }
113 }
114
115 worktrees
116}
117
118#[derive(Clone, Debug, Hash, PartialEq, Eq)]
119pub struct Upstream {
120 pub ref_name: SharedString,
121 pub tracking: UpstreamTracking,
122}
123
124impl Upstream {
125 pub fn is_remote(&self) -> bool {
126 self.remote_name().is_some()
127 }
128
129 pub fn remote_name(&self) -> Option<&str> {
130 self.ref_name
131 .strip_prefix("refs/remotes/")
132 .and_then(|stripped| stripped.split("/").next())
133 }
134
135 pub fn stripped_ref_name(&self) -> Option<&str> {
136 self.ref_name.strip_prefix("refs/remotes/")
137 }
138}
139
140#[derive(Clone, Copy, Default)]
141pub struct CommitOptions {
142 pub amend: bool,
143 pub signoff: bool,
144}
145
146#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
147pub enum UpstreamTracking {
148 /// Remote ref not present in local repository.
149 Gone,
150 /// Remote ref present in local repository (fetched from remote).
151 Tracked(UpstreamTrackingStatus),
152}
153
154impl From<UpstreamTrackingStatus> for UpstreamTracking {
155 fn from(status: UpstreamTrackingStatus) -> Self {
156 UpstreamTracking::Tracked(status)
157 }
158}
159
160impl UpstreamTracking {
161 pub fn is_gone(&self) -> bool {
162 matches!(self, UpstreamTracking::Gone)
163 }
164
165 pub fn status(&self) -> Option<UpstreamTrackingStatus> {
166 match self {
167 UpstreamTracking::Gone => None,
168 UpstreamTracking::Tracked(status) => Some(*status),
169 }
170 }
171}
172
173#[derive(Debug, Clone)]
174pub struct RemoteCommandOutput {
175 pub stdout: String,
176 pub stderr: String,
177}
178
179impl RemoteCommandOutput {
180 pub fn is_empty(&self) -> bool {
181 self.stdout.is_empty() && self.stderr.is_empty()
182 }
183}
184
185#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
186pub struct UpstreamTrackingStatus {
187 pub ahead: u32,
188 pub behind: u32,
189}
190
191#[derive(Clone, Debug, Hash, PartialEq, Eq)]
192pub struct CommitSummary {
193 pub sha: SharedString,
194 pub subject: SharedString,
195 /// This is a unix timestamp
196 pub commit_timestamp: i64,
197 pub author_name: SharedString,
198 pub has_parent: bool,
199}
200
201#[derive(Clone, Debug, Default, Hash, PartialEq, Eq)]
202pub struct CommitDetails {
203 pub sha: SharedString,
204 pub message: SharedString,
205 pub commit_timestamp: i64,
206 pub author_email: SharedString,
207 pub author_name: SharedString,
208}
209
210#[derive(Clone, Debug, Hash, PartialEq, Eq)]
211pub struct FileHistoryEntry {
212 pub sha: SharedString,
213 pub subject: SharedString,
214 pub message: SharedString,
215 pub commit_timestamp: i64,
216 pub author_name: SharedString,
217 pub author_email: SharedString,
218}
219
220#[derive(Debug, Clone)]
221pub struct FileHistory {
222 pub entries: Vec<FileHistoryEntry>,
223 pub path: RepoPath,
224}
225
226#[derive(Debug)]
227pub struct CommitDiff {
228 pub files: Vec<CommitFile>,
229}
230
231#[derive(Debug)]
232pub struct CommitFile {
233 pub path: RepoPath,
234 pub old_text: Option<String>,
235 pub new_text: Option<String>,
236}
237
238impl CommitDetails {
239 pub fn short_sha(&self) -> SharedString {
240 self.sha[..SHORT_SHA_LENGTH].to_string().into()
241 }
242}
243
244#[derive(Debug, Clone, Hash, PartialEq, Eq)]
245pub struct Remote {
246 pub name: SharedString,
247}
248
249pub enum ResetMode {
250 /// Reset the branch pointer, leave index and worktree unchanged (this will make it look like things that were
251 /// committed are now staged).
252 Soft,
253 /// Reset the branch pointer and index, leave worktree unchanged (this makes it look as though things that were
254 /// committed are now unstaged).
255 Mixed,
256}
257
258#[derive(Debug, Clone, Hash, PartialEq, Eq)]
259pub enum FetchOptions {
260 All,
261 Remote(Remote),
262}
263
264impl FetchOptions {
265 pub fn to_proto(&self) -> Option<String> {
266 match self {
267 FetchOptions::All => None,
268 FetchOptions::Remote(remote) => Some(remote.clone().name.into()),
269 }
270 }
271
272 pub fn from_proto(remote_name: Option<String>) -> Self {
273 match remote_name {
274 Some(name) => FetchOptions::Remote(Remote { name: name.into() }),
275 None => FetchOptions::All,
276 }
277 }
278
279 pub fn name(&self) -> SharedString {
280 match self {
281 Self::All => "Fetch all remotes".into(),
282 Self::Remote(remote) => remote.name.clone(),
283 }
284 }
285}
286
287impl std::fmt::Display for FetchOptions {
288 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
289 match self {
290 FetchOptions::All => write!(f, "--all"),
291 FetchOptions::Remote(remote) => write!(f, "{}", remote.name),
292 }
293 }
294}
295
296/// Modifies .git/info/exclude temporarily
297pub struct GitExcludeOverride {
298 git_exclude_path: PathBuf,
299 original_excludes: Option<String>,
300 added_excludes: Option<String>,
301}
302
303impl GitExcludeOverride {
304 const START_BLOCK_MARKER: &str = "\n\n# ====== Auto-added by Zed: =======\n";
305 const END_BLOCK_MARKER: &str = "\n# ====== End of auto-added by Zed =======\n";
306
307 pub async fn new(git_exclude_path: PathBuf) -> Result<Self> {
308 let original_excludes =
309 smol::fs::read_to_string(&git_exclude_path)
310 .await
311 .ok()
312 .map(|content| {
313 // Auto-generated lines are normally cleaned up in
314 // `restore_original()` or `drop()`, but may stuck in rare cases.
315 // Make sure to remove them.
316 Self::remove_auto_generated_block(&content)
317 });
318
319 Ok(GitExcludeOverride {
320 git_exclude_path,
321 original_excludes,
322 added_excludes: None,
323 })
324 }
325
326 pub async fn add_excludes(&mut self, excludes: &str) -> Result<()> {
327 self.added_excludes = Some(if let Some(ref already_added) = self.added_excludes {
328 format!("{already_added}\n{excludes}")
329 } else {
330 excludes.to_string()
331 });
332
333 let mut content = self.original_excludes.clone().unwrap_or_default();
334
335 content.push_str(Self::START_BLOCK_MARKER);
336 content.push_str(self.added_excludes.as_ref().unwrap());
337 content.push_str(Self::END_BLOCK_MARKER);
338
339 smol::fs::write(&self.git_exclude_path, content).await?;
340 Ok(())
341 }
342
343 pub async fn restore_original(&mut self) -> Result<()> {
344 if let Some(ref original) = self.original_excludes {
345 smol::fs::write(&self.git_exclude_path, original).await?;
346 } else if self.git_exclude_path.exists() {
347 smol::fs::remove_file(&self.git_exclude_path).await?;
348 }
349
350 self.added_excludes = None;
351
352 Ok(())
353 }
354
355 fn remove_auto_generated_block(content: &str) -> String {
356 let start_marker = Self::START_BLOCK_MARKER;
357 let end_marker = Self::END_BLOCK_MARKER;
358 let mut content = content.to_string();
359
360 let start_index = content.find(start_marker);
361 let end_index = content.rfind(end_marker);
362
363 if let (Some(start), Some(end)) = (start_index, end_index) {
364 if end > start {
365 content.replace_range(start..end + end_marker.len(), "");
366 }
367 }
368
369 // Older versions of Zed didn't have end-of-block markers,
370 // so it's impossible to determine auto-generated lines.
371 // Conservatively remove the standard list of excludes
372 let standard_excludes = format!(
373 "{}{}",
374 Self::START_BLOCK_MARKER,
375 include_str!("./checkpoint.gitignore")
376 );
377 content = content.replace(&standard_excludes, "");
378
379 content
380 }
381}
382
383impl Drop for GitExcludeOverride {
384 fn drop(&mut self) {
385 if self.added_excludes.is_some() {
386 let git_exclude_path = self.git_exclude_path.clone();
387 let original_excludes = self.original_excludes.clone();
388 smol::spawn(async move {
389 if let Some(original) = original_excludes {
390 smol::fs::write(&git_exclude_path, original).await
391 } else {
392 smol::fs::remove_file(&git_exclude_path).await
393 }
394 })
395 .detach();
396 }
397 }
398}
399
400pub trait GitRepository: Send + Sync {
401 fn reload_index(&self);
402
403 /// Returns the contents of an entry in the repository's index, or None if there is no entry for the given path.
404 ///
405 /// Also returns `None` for symlinks.
406 fn load_index_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>>;
407
408 /// 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.
409 ///
410 /// Also returns `None` for symlinks.
411 fn load_committed_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>>;
412 fn load_blob_content(&self, oid: Oid) -> BoxFuture<'_, Result<String>>;
413
414 fn set_index_text(
415 &self,
416 path: RepoPath,
417 content: Option<String>,
418 env: Arc<HashMap<String, String>>,
419 is_executable: bool,
420 ) -> BoxFuture<'_, anyhow::Result<()>>;
421
422 /// Returns the URL of the remote with the given name.
423 fn remote_url(&self, name: &str) -> BoxFuture<'_, Option<String>>;
424
425 /// Resolve a list of refs to SHAs.
426 fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<'_, Result<Vec<Option<String>>>>;
427
428 fn head_sha(&self) -> BoxFuture<'_, Option<String>> {
429 async move {
430 self.revparse_batch(vec!["HEAD".into()])
431 .await
432 .unwrap_or_default()
433 .into_iter()
434 .next()
435 .flatten()
436 }
437 .boxed()
438 }
439
440 fn merge_message(&self) -> BoxFuture<'_, Option<String>>;
441
442 fn status(&self, path_prefixes: &[RepoPath]) -> Task<Result<GitStatus>>;
443 fn diff_tree(&self, request: DiffTreeType) -> BoxFuture<'_, Result<TreeDiff>>;
444
445 fn stash_entries(&self) -> BoxFuture<'_, Result<GitStash>>;
446
447 fn branches(&self) -> BoxFuture<'_, Result<Vec<Branch>>>;
448
449 fn change_branch(&self, name: String) -> BoxFuture<'_, Result<()>>;
450 fn create_branch(&self, name: String, base_branch: Option<String>)
451 -> BoxFuture<'_, Result<()>>;
452 fn rename_branch(&self, branch: String, new_name: String) -> BoxFuture<'_, Result<()>>;
453
454 fn delete_branch(&self, name: String) -> BoxFuture<'_, Result<()>>;
455
456 fn worktrees(&self) -> BoxFuture<'_, Result<Vec<Worktree>>>;
457
458 fn create_worktree(
459 &self,
460 name: String,
461 directory: PathBuf,
462 from_commit: Option<String>,
463 ) -> BoxFuture<'_, Result<()>>;
464
465 fn reset(
466 &self,
467 commit: String,
468 mode: ResetMode,
469 env: Arc<HashMap<String, String>>,
470 ) -> BoxFuture<'_, Result<()>>;
471
472 fn checkout_files(
473 &self,
474 commit: String,
475 paths: Vec<RepoPath>,
476 env: Arc<HashMap<String, String>>,
477 ) -> BoxFuture<'_, Result<()>>;
478
479 fn show(&self, commit: String) -> BoxFuture<'_, Result<CommitDetails>>;
480
481 fn load_commit(&self, commit: String, cx: AsyncApp) -> BoxFuture<'_, Result<CommitDiff>>;
482 fn blame(&self, path: RepoPath, content: Rope) -> BoxFuture<'_, Result<crate::blame::Blame>>;
483 fn file_history(&self, path: RepoPath) -> BoxFuture<'_, Result<FileHistory>>;
484 fn file_history_paginated(
485 &self,
486 path: RepoPath,
487 skip: usize,
488 limit: Option<usize>,
489 ) -> BoxFuture<'_, Result<FileHistory>>;
490
491 /// Returns the absolute path to the repository. For worktrees, this will be the path to the
492 /// worktree's gitdir within the main repository (typically `.git/worktrees/<name>`).
493 fn path(&self) -> PathBuf;
494
495 fn main_repository_path(&self) -> PathBuf;
496
497 /// Updates the index to match the worktree at the given paths.
498 ///
499 /// If any of the paths have been deleted from the worktree, they will be removed from the index if found there.
500 fn stage_paths(
501 &self,
502 paths: Vec<RepoPath>,
503 env: Arc<HashMap<String, String>>,
504 ) -> BoxFuture<'_, Result<()>>;
505 /// Updates the index to match HEAD at the given paths.
506 ///
507 /// If any of the paths were previously staged but do not exist in HEAD, they will be removed from the index.
508 fn unstage_paths(
509 &self,
510 paths: Vec<RepoPath>,
511 env: Arc<HashMap<String, String>>,
512 ) -> BoxFuture<'_, Result<()>>;
513
514 fn run_hook(
515 &self,
516 hook: RunHook,
517 env: Arc<HashMap<String, String>>,
518 ) -> BoxFuture<'_, Result<()>>;
519
520 fn commit(
521 &self,
522 message: SharedString,
523 name_and_email: Option<(SharedString, SharedString)>,
524 options: CommitOptions,
525 askpass: AskPassDelegate,
526 env: Arc<HashMap<String, String>>,
527 ) -> BoxFuture<'_, Result<()>>;
528
529 fn stash_paths(
530 &self,
531 paths: Vec<RepoPath>,
532 env: Arc<HashMap<String, String>>,
533 ) -> BoxFuture<'_, Result<()>>;
534
535 fn stash_pop(
536 &self,
537 index: Option<usize>,
538 env: Arc<HashMap<String, String>>,
539 ) -> BoxFuture<'_, Result<()>>;
540
541 fn stash_apply(
542 &self,
543 index: Option<usize>,
544 env: Arc<HashMap<String, String>>,
545 ) -> BoxFuture<'_, Result<()>>;
546
547 fn stash_drop(
548 &self,
549 index: Option<usize>,
550 env: Arc<HashMap<String, String>>,
551 ) -> BoxFuture<'_, Result<()>>;
552
553 fn push(
554 &self,
555 branch_name: String,
556 upstream_name: String,
557 options: Option<PushOptions>,
558 askpass: AskPassDelegate,
559 env: Arc<HashMap<String, String>>,
560 // This method takes an AsyncApp to ensure it's invoked on the main thread,
561 // otherwise git-credentials-manager won't work.
562 cx: AsyncApp,
563 ) -> BoxFuture<'_, Result<RemoteCommandOutput>>;
564
565 fn pull(
566 &self,
567 branch_name: Option<String>,
568 upstream_name: String,
569 rebase: bool,
570 askpass: AskPassDelegate,
571 env: Arc<HashMap<String, String>>,
572 // This method takes an AsyncApp to ensure it's invoked on the main thread,
573 // otherwise git-credentials-manager won't work.
574 cx: AsyncApp,
575 ) -> BoxFuture<'_, Result<RemoteCommandOutput>>;
576
577 fn fetch(
578 &self,
579 fetch_options: FetchOptions,
580 askpass: AskPassDelegate,
581 env: Arc<HashMap<String, String>>,
582 // This method takes an AsyncApp to ensure it's invoked on the main thread,
583 // otherwise git-credentials-manager won't work.
584 cx: AsyncApp,
585 ) -> BoxFuture<'_, Result<RemoteCommandOutput>>;
586
587 fn get_push_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>>;
588
589 fn get_branch_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>>;
590
591 fn get_all_remotes(&self) -> BoxFuture<'_, Result<Vec<Remote>>>;
592
593 /// returns a list of remote branches that contain HEAD
594 fn check_for_pushed_commit(&self) -> BoxFuture<'_, Result<Vec<SharedString>>>;
595
596 /// Run git diff
597 fn diff(&self, diff: DiffType) -> BoxFuture<'_, Result<String>>;
598
599 /// Creates a checkpoint for the repository.
600 fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>>;
601
602 /// Resets to a previously-created checkpoint.
603 fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>>;
604
605 /// Compares two checkpoints, returning true if they are equal
606 fn compare_checkpoints(
607 &self,
608 left: GitRepositoryCheckpoint,
609 right: GitRepositoryCheckpoint,
610 ) -> BoxFuture<'_, Result<bool>>;
611
612 /// Computes a diff between two checkpoints.
613 fn diff_checkpoints(
614 &self,
615 base_checkpoint: GitRepositoryCheckpoint,
616 target_checkpoint: GitRepositoryCheckpoint,
617 ) -> BoxFuture<'_, Result<String>>;
618
619 fn default_branch(&self) -> BoxFuture<'_, Result<Option<SharedString>>>;
620}
621
622pub enum DiffType {
623 HeadToIndex,
624 HeadToWorktree,
625}
626
627#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]
628pub enum PushOptions {
629 SetUpstream,
630 Force,
631}
632
633impl std::fmt::Debug for dyn GitRepository {
634 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
635 f.debug_struct("dyn GitRepository<...>").finish()
636 }
637}
638
639pub struct RealGitRepository {
640 pub repository: Arc<Mutex<git2::Repository>>,
641 pub system_git_binary_path: Option<PathBuf>,
642 pub any_git_binary_path: PathBuf,
643 executor: BackgroundExecutor,
644}
645
646impl RealGitRepository {
647 pub fn new(
648 dotgit_path: &Path,
649 bundled_git_binary_path: Option<PathBuf>,
650 system_git_binary_path: Option<PathBuf>,
651 executor: BackgroundExecutor,
652 ) -> Option<Self> {
653 let any_git_binary_path = system_git_binary_path.clone().or(bundled_git_binary_path)?;
654 let workdir_root = dotgit_path.parent()?;
655 let repository = git2::Repository::open(workdir_root).log_err()?;
656 Some(Self {
657 repository: Arc::new(Mutex::new(repository)),
658 system_git_binary_path,
659 any_git_binary_path,
660 executor,
661 })
662 }
663
664 fn working_directory(&self) -> Result<PathBuf> {
665 self.repository
666 .lock()
667 .workdir()
668 .context("failed to read git work directory")
669 .map(Path::to_path_buf)
670 }
671}
672
673#[derive(Clone, Debug)]
674pub struct GitRepositoryCheckpoint {
675 pub commit_sha: Oid,
676}
677
678#[derive(Debug)]
679pub struct GitCommitter {
680 pub name: Option<String>,
681 pub email: Option<String>,
682}
683
684pub async fn get_git_committer(cx: &AsyncApp) -> GitCommitter {
685 if cfg!(any(feature = "test-support", test)) {
686 return GitCommitter {
687 name: None,
688 email: None,
689 };
690 }
691
692 let git_binary_path =
693 if cfg!(target_os = "macos") && option_env!("ZED_BUNDLE").as_deref() == Some("true") {
694 cx.update(|cx| {
695 cx.path_for_auxiliary_executable("git")
696 .context("could not find git binary path")
697 .log_err()
698 })
699 .ok()
700 .flatten()
701 } else {
702 None
703 };
704
705 let git = GitBinary::new(
706 git_binary_path.unwrap_or(PathBuf::from("git")),
707 paths::home_dir().clone(),
708 cx.background_executor().clone(),
709 );
710
711 cx.background_spawn(async move {
712 let name = git.run(["config", "--global", "user.name"]).await.log_err();
713 let email = git
714 .run(["config", "--global", "user.email"])
715 .await
716 .log_err();
717 GitCommitter { name, email }
718 })
719 .await
720}
721
722impl GitRepository for RealGitRepository {
723 fn reload_index(&self) {
724 if let Ok(mut index) = self.repository.lock().index() {
725 _ = index.read(false);
726 }
727 }
728
729 fn path(&self) -> PathBuf {
730 let repo = self.repository.lock();
731 repo.path().into()
732 }
733
734 fn main_repository_path(&self) -> PathBuf {
735 let repo = self.repository.lock();
736 repo.commondir().into()
737 }
738
739 fn show(&self, commit: String) -> BoxFuture<'_, Result<CommitDetails>> {
740 let git_binary_path = self.any_git_binary_path.clone();
741 let working_directory = self.working_directory();
742 self.executor
743 .spawn(async move {
744 let working_directory = working_directory?;
745 let output = new_smol_command(git_binary_path)
746 .current_dir(&working_directory)
747 .args([
748 "--no-optional-locks",
749 "show",
750 "--no-patch",
751 "--format=%H%x00%B%x00%at%x00%ae%x00%an%x00",
752 &commit,
753 ])
754 .output()
755 .await?;
756 let output = std::str::from_utf8(&output.stdout)?;
757 let fields = output.split('\0').collect::<Vec<_>>();
758 if fields.len() != 6 {
759 bail!("unexpected git-show output for {commit:?}: {output:?}")
760 }
761 let sha = fields[0].to_string().into();
762 let message = fields[1].to_string().into();
763 let commit_timestamp = fields[2].parse()?;
764 let author_email = fields[3].to_string().into();
765 let author_name = fields[4].to_string().into();
766 Ok(CommitDetails {
767 sha,
768 message,
769 commit_timestamp,
770 author_email,
771 author_name,
772 })
773 })
774 .boxed()
775 }
776
777 fn load_commit(&self, commit: String, cx: AsyncApp) -> BoxFuture<'_, Result<CommitDiff>> {
778 let Some(working_directory) = self.repository.lock().workdir().map(ToOwned::to_owned)
779 else {
780 return future::ready(Err(anyhow!("no working directory"))).boxed();
781 };
782 let git_binary_path = self.any_git_binary_path.clone();
783 cx.background_spawn(async move {
784 let show_output = util::command::new_smol_command(&git_binary_path)
785 .current_dir(&working_directory)
786 .args([
787 "--no-optional-locks",
788 "show",
789 "--format=",
790 "-z",
791 "--no-renames",
792 "--name-status",
793 "--first-parent",
794 ])
795 .arg(&commit)
796 .stdin(Stdio::null())
797 .stdout(Stdio::piped())
798 .stderr(Stdio::piped())
799 .output()
800 .await
801 .context("starting git show process")?;
802
803 let show_stdout = String::from_utf8_lossy(&show_output.stdout);
804 let changes = parse_git_diff_name_status(&show_stdout);
805 let parent_sha = format!("{}^", commit);
806
807 let mut cat_file_process = util::command::new_smol_command(&git_binary_path)
808 .current_dir(&working_directory)
809 .args(["--no-optional-locks", "cat-file", "--batch=%(objectsize)"])
810 .stdin(Stdio::piped())
811 .stdout(Stdio::piped())
812 .stderr(Stdio::piped())
813 .spawn()
814 .context("starting git cat-file process")?;
815
816 let mut files = Vec::<CommitFile>::new();
817 let mut stdin = BufWriter::with_capacity(512, cat_file_process.stdin.take().unwrap());
818 let mut stdout = BufReader::new(cat_file_process.stdout.take().unwrap());
819 let mut info_line = String::new();
820 let mut newline = [b'\0'];
821 for (path, status_code) in changes {
822 // git-show outputs `/`-delimited paths even on Windows.
823 let Some(rel_path) = RelPath::unix(path).log_err() else {
824 continue;
825 };
826
827 match status_code {
828 StatusCode::Modified => {
829 stdin.write_all(commit.as_bytes()).await?;
830 stdin.write_all(b":").await?;
831 stdin.write_all(path.as_bytes()).await?;
832 stdin.write_all(b"\n").await?;
833 stdin.write_all(parent_sha.as_bytes()).await?;
834 stdin.write_all(b":").await?;
835 stdin.write_all(path.as_bytes()).await?;
836 stdin.write_all(b"\n").await?;
837 }
838 StatusCode::Added => {
839 stdin.write_all(commit.as_bytes()).await?;
840 stdin.write_all(b":").await?;
841 stdin.write_all(path.as_bytes()).await?;
842 stdin.write_all(b"\n").await?;
843 }
844 StatusCode::Deleted => {
845 stdin.write_all(parent_sha.as_bytes()).await?;
846 stdin.write_all(b":").await?;
847 stdin.write_all(path.as_bytes()).await?;
848 stdin.write_all(b"\n").await?;
849 }
850 _ => continue,
851 }
852 stdin.flush().await?;
853
854 info_line.clear();
855 stdout.read_line(&mut info_line).await?;
856
857 let len = info_line.trim_end().parse().with_context(|| {
858 format!("invalid object size output from cat-file {info_line}")
859 })?;
860 let mut text = vec![0; len];
861 stdout.read_exact(&mut text).await?;
862 stdout.read_exact(&mut newline).await?;
863 let text = String::from_utf8_lossy(&text).to_string();
864
865 let mut old_text = None;
866 let mut new_text = None;
867 match status_code {
868 StatusCode::Modified => {
869 info_line.clear();
870 stdout.read_line(&mut info_line).await?;
871 let len = info_line.trim_end().parse().with_context(|| {
872 format!("invalid object size output from cat-file {}", info_line)
873 })?;
874 let mut parent_text = vec![0; len];
875 stdout.read_exact(&mut parent_text).await?;
876 stdout.read_exact(&mut newline).await?;
877 old_text = Some(String::from_utf8_lossy(&parent_text).to_string());
878 new_text = Some(text);
879 }
880 StatusCode::Added => new_text = Some(text),
881 StatusCode::Deleted => old_text = Some(text),
882 _ => continue,
883 }
884
885 files.push(CommitFile {
886 path: RepoPath(Arc::from(rel_path)),
887 old_text,
888 new_text,
889 })
890 }
891
892 Ok(CommitDiff { files })
893 })
894 .boxed()
895 }
896
897 fn reset(
898 &self,
899 commit: String,
900 mode: ResetMode,
901 env: Arc<HashMap<String, String>>,
902 ) -> BoxFuture<'_, Result<()>> {
903 async move {
904 let working_directory = self.working_directory();
905
906 let mode_flag = match mode {
907 ResetMode::Mixed => "--mixed",
908 ResetMode::Soft => "--soft",
909 };
910
911 let output = new_smol_command(&self.any_git_binary_path)
912 .envs(env.iter())
913 .current_dir(&working_directory?)
914 .args(["reset", mode_flag, &commit])
915 .output()
916 .await?;
917 anyhow::ensure!(
918 output.status.success(),
919 "Failed to reset:\n{}",
920 String::from_utf8_lossy(&output.stderr),
921 );
922 Ok(())
923 }
924 .boxed()
925 }
926
927 fn checkout_files(
928 &self,
929 commit: String,
930 paths: Vec<RepoPath>,
931 env: Arc<HashMap<String, String>>,
932 ) -> BoxFuture<'_, Result<()>> {
933 let working_directory = self.working_directory();
934 let git_binary_path = self.any_git_binary_path.clone();
935 async move {
936 if paths.is_empty() {
937 return Ok(());
938 }
939
940 let output = new_smol_command(&git_binary_path)
941 .current_dir(&working_directory?)
942 .envs(env.iter())
943 .args(["checkout", &commit, "--"])
944 .args(paths.iter().map(|path| path.as_unix_str()))
945 .output()
946 .await?;
947 anyhow::ensure!(
948 output.status.success(),
949 "Failed to checkout files:\n{}",
950 String::from_utf8_lossy(&output.stderr),
951 );
952 Ok(())
953 }
954 .boxed()
955 }
956
957 fn load_index_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>> {
958 // https://git-scm.com/book/en/v2/Git-Internals-Git-Objects
959 const GIT_MODE_SYMLINK: u32 = 0o120000;
960
961 let repo = self.repository.clone();
962 self.executor
963 .spawn(async move {
964 fn logic(repo: &git2::Repository, path: &RepoPath) -> Result<Option<String>> {
965 // This check is required because index.get_path() unwraps internally :(
966 let mut index = repo.index()?;
967 index.read(false)?;
968
969 const STAGE_NORMAL: i32 = 0;
970 let path = path.as_std_path();
971 // `RepoPath` contains a `RelPath` which normalizes `.` into an empty path
972 // `get_path` unwraps on empty paths though, so undo that normalization here
973 let path = if path.components().next().is_none() {
974 ".".as_ref()
975 } else {
976 path
977 };
978 let oid = match index.get_path(path, STAGE_NORMAL) {
979 Some(entry) if entry.mode != GIT_MODE_SYMLINK => entry.id,
980 _ => return Ok(None),
981 };
982
983 let content = repo.find_blob(oid)?.content().to_owned();
984 Ok(String::from_utf8(content).ok())
985 }
986
987 match logic(&repo.lock(), &path) {
988 Ok(value) => return value,
989 Err(err) => log::error!("Error loading index text: {:?}", err),
990 }
991 None
992 })
993 .boxed()
994 }
995
996 fn load_committed_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>> {
997 let repo = self.repository.clone();
998 self.executor
999 .spawn(async move {
1000 let repo = repo.lock();
1001 let head = repo.head().ok()?.peel_to_tree().log_err()?;
1002 let entry = head.get_path(path.as_std_path()).ok()?;
1003 if entry.filemode() == i32::from(git2::FileMode::Link) {
1004 return None;
1005 }
1006 let content = repo.find_blob(entry.id()).log_err()?.content().to_owned();
1007 String::from_utf8(content).ok()
1008 })
1009 .boxed()
1010 }
1011
1012 fn load_blob_content(&self, oid: Oid) -> BoxFuture<'_, Result<String>> {
1013 let repo = self.repository.clone();
1014 self.executor
1015 .spawn(async move {
1016 let repo = repo.lock();
1017 let content = repo.find_blob(oid.0)?.content().to_owned();
1018 Ok(String::from_utf8(content)?)
1019 })
1020 .boxed()
1021 }
1022
1023 fn set_index_text(
1024 &self,
1025 path: RepoPath,
1026 content: Option<String>,
1027 env: Arc<HashMap<String, String>>,
1028 is_executable: bool,
1029 ) -> BoxFuture<'_, anyhow::Result<()>> {
1030 let working_directory = self.working_directory();
1031 let git_binary_path = self.any_git_binary_path.clone();
1032 self.executor
1033 .spawn(async move {
1034 let working_directory = working_directory?;
1035 let mode = if is_executable { "100755" } else { "100644" };
1036
1037 if let Some(content) = content {
1038 let mut child = new_smol_command(&git_binary_path)
1039 .current_dir(&working_directory)
1040 .envs(env.iter())
1041 .args(["hash-object", "-w", "--stdin"])
1042 .stdin(Stdio::piped())
1043 .stdout(Stdio::piped())
1044 .spawn()?;
1045 let mut stdin = child.stdin.take().unwrap();
1046 stdin.write_all(content.as_bytes()).await?;
1047 stdin.flush().await?;
1048 drop(stdin);
1049 let output = child.output().await?.stdout;
1050 let sha = str::from_utf8(&output)?.trim();
1051
1052 log::debug!("indexing SHA: {sha}, path {path:?}");
1053
1054 let output = new_smol_command(&git_binary_path)
1055 .current_dir(&working_directory)
1056 .envs(env.iter())
1057 .args(["update-index", "--add", "--cacheinfo", mode, sha])
1058 .arg(path.as_unix_str())
1059 .output()
1060 .await?;
1061
1062 anyhow::ensure!(
1063 output.status.success(),
1064 "Failed to stage:\n{}",
1065 String::from_utf8_lossy(&output.stderr)
1066 );
1067 } else {
1068 log::debug!("removing path {path:?} from the index");
1069 let output = new_smol_command(&git_binary_path)
1070 .current_dir(&working_directory)
1071 .envs(env.iter())
1072 .args(["update-index", "--force-remove"])
1073 .arg(path.as_unix_str())
1074 .output()
1075 .await?;
1076 anyhow::ensure!(
1077 output.status.success(),
1078 "Failed to unstage:\n{}",
1079 String::from_utf8_lossy(&output.stderr)
1080 );
1081 }
1082
1083 Ok(())
1084 })
1085 .boxed()
1086 }
1087
1088 fn remote_url(&self, name: &str) -> BoxFuture<'_, Option<String>> {
1089 let repo = self.repository.clone();
1090 let name = name.to_owned();
1091 self.executor
1092 .spawn(async move {
1093 let repo = repo.lock();
1094 let remote = repo.find_remote(&name).ok()?;
1095 remote.url().map(|url| url.to_string())
1096 })
1097 .boxed()
1098 }
1099
1100 fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<'_, Result<Vec<Option<String>>>> {
1101 let working_directory = self.working_directory();
1102 let git_binary_path = self.any_git_binary_path.clone();
1103 self.executor
1104 .spawn(async move {
1105 let working_directory = working_directory?;
1106 let mut process = new_smol_command(&git_binary_path)
1107 .current_dir(&working_directory)
1108 .args([
1109 "--no-optional-locks",
1110 "cat-file",
1111 "--batch-check=%(objectname)",
1112 ])
1113 .stdin(Stdio::piped())
1114 .stdout(Stdio::piped())
1115 .stderr(Stdio::piped())
1116 .spawn()?;
1117
1118 let stdin = process
1119 .stdin
1120 .take()
1121 .context("no stdin for git cat-file subprocess")?;
1122 let mut stdin = BufWriter::new(stdin);
1123 for rev in &revs {
1124 stdin.write_all(rev.as_bytes()).await?;
1125 stdin.write_all(b"\n").await?;
1126 }
1127 stdin.flush().await?;
1128 drop(stdin);
1129
1130 let output = process.output().await?;
1131 let output = std::str::from_utf8(&output.stdout)?;
1132 let shas = output
1133 .lines()
1134 .map(|line| {
1135 if line.ends_with("missing") {
1136 None
1137 } else {
1138 Some(line.to_string())
1139 }
1140 })
1141 .collect::<Vec<_>>();
1142
1143 if shas.len() != revs.len() {
1144 // In an octopus merge, git cat-file still only outputs the first sha from MERGE_HEAD.
1145 bail!("unexpected number of shas")
1146 }
1147
1148 Ok(shas)
1149 })
1150 .boxed()
1151 }
1152
1153 fn merge_message(&self) -> BoxFuture<'_, Option<String>> {
1154 let path = self.path().join("MERGE_MSG");
1155 self.executor
1156 .spawn(async move { std::fs::read_to_string(&path).ok() })
1157 .boxed()
1158 }
1159
1160 fn status(&self, path_prefixes: &[RepoPath]) -> Task<Result<GitStatus>> {
1161 let git_binary_path = self.any_git_binary_path.clone();
1162 let working_directory = match self.working_directory() {
1163 Ok(working_directory) => working_directory,
1164 Err(e) => return Task::ready(Err(e)),
1165 };
1166 let args = git_status_args(path_prefixes);
1167 log::debug!("Checking for git status in {path_prefixes:?}");
1168 self.executor.spawn(async move {
1169 let output = new_smol_command(&git_binary_path)
1170 .current_dir(working_directory)
1171 .args(args)
1172 .output()
1173 .await?;
1174 if output.status.success() {
1175 let stdout = String::from_utf8_lossy(&output.stdout);
1176 stdout.parse()
1177 } else {
1178 let stderr = String::from_utf8_lossy(&output.stderr);
1179 anyhow::bail!("git status failed: {stderr}");
1180 }
1181 })
1182 }
1183
1184 fn diff_tree(&self, request: DiffTreeType) -> BoxFuture<'_, Result<TreeDiff>> {
1185 let git_binary_path = self.any_git_binary_path.clone();
1186 let working_directory = match self.working_directory() {
1187 Ok(working_directory) => working_directory,
1188 Err(e) => return Task::ready(Err(e)).boxed(),
1189 };
1190
1191 let mut args = vec![
1192 OsString::from("--no-optional-locks"),
1193 OsString::from("diff-tree"),
1194 OsString::from("-r"),
1195 OsString::from("-z"),
1196 OsString::from("--no-renames"),
1197 ];
1198 match request {
1199 DiffTreeType::MergeBase { base, head } => {
1200 args.push("--merge-base".into());
1201 args.push(OsString::from(base.as_str()));
1202 args.push(OsString::from(head.as_str()));
1203 }
1204 DiffTreeType::Since { base, head } => {
1205 args.push(OsString::from(base.as_str()));
1206 args.push(OsString::from(head.as_str()));
1207 }
1208 }
1209
1210 self.executor
1211 .spawn(async move {
1212 let output = new_smol_command(&git_binary_path)
1213 .current_dir(working_directory)
1214 .args(args)
1215 .output()
1216 .await?;
1217 if output.status.success() {
1218 let stdout = String::from_utf8_lossy(&output.stdout);
1219 stdout.parse()
1220 } else {
1221 let stderr = String::from_utf8_lossy(&output.stderr);
1222 anyhow::bail!("git status failed: {stderr}");
1223 }
1224 })
1225 .boxed()
1226 }
1227
1228 fn stash_entries(&self) -> BoxFuture<'_, Result<GitStash>> {
1229 let git_binary_path = self.any_git_binary_path.clone();
1230 let working_directory = self.working_directory();
1231 self.executor
1232 .spawn(async move {
1233 let output = new_smol_command(&git_binary_path)
1234 .current_dir(working_directory?)
1235 .args(&["stash", "list", "--pretty=format:%gd%x00%H%x00%ct%x00%s"])
1236 .output()
1237 .await?;
1238 if output.status.success() {
1239 let stdout = String::from_utf8_lossy(&output.stdout);
1240 stdout.parse()
1241 } else {
1242 let stderr = String::from_utf8_lossy(&output.stderr);
1243 anyhow::bail!("git status failed: {stderr}");
1244 }
1245 })
1246 .boxed()
1247 }
1248
1249 fn branches(&self) -> BoxFuture<'_, Result<Vec<Branch>>> {
1250 let working_directory = self.working_directory();
1251 let git_binary_path = self.any_git_binary_path.clone();
1252 self.executor
1253 .spawn(async move {
1254 let fields = [
1255 "%(HEAD)",
1256 "%(objectname)",
1257 "%(parent)",
1258 "%(refname)",
1259 "%(upstream)",
1260 "%(upstream:track)",
1261 "%(committerdate:unix)",
1262 "%(authorname)",
1263 "%(contents:subject)",
1264 ]
1265 .join("%00");
1266 let args = vec![
1267 "for-each-ref",
1268 "refs/heads/**/*",
1269 "refs/remotes/**/*",
1270 "--format",
1271 &fields,
1272 ];
1273 let working_directory = working_directory?;
1274 let output = new_smol_command(&git_binary_path)
1275 .current_dir(&working_directory)
1276 .args(args)
1277 .output()
1278 .await?;
1279
1280 anyhow::ensure!(
1281 output.status.success(),
1282 "Failed to git git branches:\n{}",
1283 String::from_utf8_lossy(&output.stderr)
1284 );
1285
1286 let input = String::from_utf8_lossy(&output.stdout);
1287
1288 let mut branches = parse_branch_input(&input)?;
1289 if branches.is_empty() {
1290 let args = vec!["symbolic-ref", "--quiet", "HEAD"];
1291
1292 let output = new_smol_command(&git_binary_path)
1293 .current_dir(&working_directory)
1294 .args(args)
1295 .output()
1296 .await?;
1297
1298 // git symbolic-ref returns a non-0 exit code if HEAD points
1299 // to something other than a branch
1300 if output.status.success() {
1301 let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
1302
1303 branches.push(Branch {
1304 ref_name: name.into(),
1305 is_head: true,
1306 upstream: None,
1307 most_recent_commit: None,
1308 });
1309 }
1310 }
1311
1312 Ok(branches)
1313 })
1314 .boxed()
1315 }
1316
1317 fn worktrees(&self) -> BoxFuture<'_, Result<Vec<Worktree>>> {
1318 let git_binary_path = self.any_git_binary_path.clone();
1319 let working_directory = self.working_directory();
1320 self.executor
1321 .spawn(async move {
1322 let output = new_smol_command(&git_binary_path)
1323 .current_dir(working_directory?)
1324 .args(&["--no-optional-locks", "worktree", "list", "--porcelain"])
1325 .output()
1326 .await?;
1327 if output.status.success() {
1328 let stdout = String::from_utf8_lossy(&output.stdout);
1329 Ok(parse_worktrees_from_str(&stdout))
1330 } else {
1331 let stderr = String::from_utf8_lossy(&output.stderr);
1332 anyhow::bail!("git worktree list failed: {stderr}");
1333 }
1334 })
1335 .boxed()
1336 }
1337
1338 fn create_worktree(
1339 &self,
1340 name: String,
1341 directory: PathBuf,
1342 from_commit: Option<String>,
1343 ) -> BoxFuture<'_, Result<()>> {
1344 let git_binary_path = self.any_git_binary_path.clone();
1345 let working_directory = self.working_directory();
1346 let final_path = directory.join(&name);
1347 let mut args = vec![
1348 OsString::from("--no-optional-locks"),
1349 OsString::from("worktree"),
1350 OsString::from("add"),
1351 OsString::from(final_path.as_os_str()),
1352 ];
1353 if let Some(from_commit) = from_commit {
1354 args.extend([
1355 OsString::from("-b"),
1356 OsString::from(name.as_str()),
1357 OsString::from(from_commit),
1358 ]);
1359 }
1360 self.executor
1361 .spawn(async move {
1362 let output = new_smol_command(&git_binary_path)
1363 .current_dir(working_directory?)
1364 .args(args)
1365 .output()
1366 .await?;
1367 if output.status.success() {
1368 Ok(())
1369 } else {
1370 let stderr = String::from_utf8_lossy(&output.stderr);
1371 anyhow::bail!("git worktree list failed: {stderr}");
1372 }
1373 })
1374 .boxed()
1375 }
1376
1377 fn change_branch(&self, name: String) -> BoxFuture<'_, Result<()>> {
1378 let repo = self.repository.clone();
1379 let working_directory = self.working_directory();
1380 let git_binary_path = self.any_git_binary_path.clone();
1381 let executor = self.executor.clone();
1382 let branch = self.executor.spawn(async move {
1383 let repo = repo.lock();
1384 let branch = if let Ok(branch) = repo.find_branch(&name, BranchType::Local) {
1385 branch
1386 } else if let Ok(revision) = repo.find_branch(&name, BranchType::Remote) {
1387 let (_, branch_name) = name.split_once("/").context("Unexpected branch format")?;
1388 let revision = revision.get();
1389 let branch_commit = revision.peel_to_commit()?;
1390 let mut branch = repo.branch(&branch_name, &branch_commit, false)?;
1391 branch.set_upstream(Some(&name))?;
1392 branch
1393 } else {
1394 anyhow::bail!("Branch '{}' not found", name);
1395 };
1396
1397 Ok(branch
1398 .name()?
1399 .context("cannot checkout anonymous branch")?
1400 .to_string())
1401 });
1402
1403 self.executor
1404 .spawn(async move {
1405 let branch = branch.await?;
1406
1407 GitBinary::new(git_binary_path, working_directory?, executor)
1408 .run(&["checkout", &branch])
1409 .await?;
1410 anyhow::Ok(())
1411 })
1412 .boxed()
1413 }
1414
1415 fn create_branch(
1416 &self,
1417 name: String,
1418 base_branch: Option<String>,
1419 ) -> BoxFuture<'_, Result<()>> {
1420 let git_binary_path = self.any_git_binary_path.clone();
1421 let working_directory = self.working_directory();
1422 let executor = self.executor.clone();
1423
1424 self.executor
1425 .spawn(async move {
1426 let mut args = vec!["switch", "-c", &name];
1427 let base_branch_str;
1428 if let Some(ref base) = base_branch {
1429 base_branch_str = base.clone();
1430 args.push(&base_branch_str);
1431 }
1432
1433 GitBinary::new(git_binary_path, working_directory?, executor)
1434 .run(&args)
1435 .await?;
1436 anyhow::Ok(())
1437 })
1438 .boxed()
1439 }
1440
1441 fn rename_branch(&self, branch: String, new_name: String) -> BoxFuture<'_, Result<()>> {
1442 let git_binary_path = self.any_git_binary_path.clone();
1443 let working_directory = self.working_directory();
1444 let executor = self.executor.clone();
1445
1446 self.executor
1447 .spawn(async move {
1448 GitBinary::new(git_binary_path, working_directory?, executor)
1449 .run(&["branch", "-m", &branch, &new_name])
1450 .await?;
1451 anyhow::Ok(())
1452 })
1453 .boxed()
1454 }
1455
1456 fn delete_branch(&self, name: String) -> BoxFuture<'_, Result<()>> {
1457 let git_binary_path = self.any_git_binary_path.clone();
1458 let working_directory = self.working_directory();
1459 let executor = self.executor.clone();
1460
1461 self.executor
1462 .spawn(async move {
1463 GitBinary::new(git_binary_path, working_directory?, executor)
1464 .run(&["branch", "-d", &name])
1465 .await?;
1466 anyhow::Ok(())
1467 })
1468 .boxed()
1469 }
1470
1471 fn blame(&self, path: RepoPath, content: Rope) -> BoxFuture<'_, Result<crate::blame::Blame>> {
1472 let working_directory = self.working_directory();
1473 let git_binary_path = self.any_git_binary_path.clone();
1474 let executor = self.executor.clone();
1475
1476 async move {
1477 let remote_url = if let Some(remote_url) = self.remote_url("upstream").await {
1478 Some(remote_url)
1479 } else if let Some(remote_url) = self.remote_url("origin").await {
1480 Some(remote_url)
1481 } else {
1482 None
1483 };
1484 executor
1485 .spawn(async move {
1486 crate::blame::Blame::for_path(
1487 &git_binary_path,
1488 &working_directory?,
1489 &path,
1490 &content,
1491 remote_url,
1492 )
1493 .await
1494 })
1495 .await
1496 }
1497 .boxed()
1498 }
1499
1500 fn file_history(&self, path: RepoPath) -> BoxFuture<'_, Result<FileHistory>> {
1501 self.file_history_paginated(path, 0, None)
1502 }
1503
1504 fn file_history_paginated(
1505 &self,
1506 path: RepoPath,
1507 skip: usize,
1508 limit: Option<usize>,
1509 ) -> BoxFuture<'_, Result<FileHistory>> {
1510 let working_directory = self.working_directory();
1511 let git_binary_path = self.any_git_binary_path.clone();
1512 self.executor
1513 .spawn(async move {
1514 let working_directory = working_directory?;
1515 // Use a unique delimiter with a hardcoded UUID to separate commits
1516 // This essentially eliminates any chance of encountering the delimiter in actual commit data
1517 let commit_delimiter =
1518 concat!("<<COMMIT_END-", "3f8a9c2e-7d4b-4e1a-9f6c-8b5d2a1e4c3f>>",);
1519
1520 let format_string = format!(
1521 "--pretty=format:%H%x00%s%x00%B%x00%at%x00%an%x00%ae{}",
1522 commit_delimiter
1523 );
1524
1525 let mut args = vec!["--no-optional-locks", "log", "--follow", &format_string];
1526
1527 let skip_str;
1528 let limit_str;
1529 if skip > 0 {
1530 skip_str = skip.to_string();
1531 args.push("--skip");
1532 args.push(&skip_str);
1533 }
1534 if let Some(n) = limit {
1535 limit_str = n.to_string();
1536 args.push("-n");
1537 args.push(&limit_str);
1538 }
1539
1540 args.push("--");
1541
1542 let output = new_smol_command(&git_binary_path)
1543 .current_dir(&working_directory)
1544 .args(&args)
1545 .arg(path.as_unix_str())
1546 .output()
1547 .await?;
1548
1549 if !output.status.success() {
1550 let stderr = String::from_utf8_lossy(&output.stderr);
1551 bail!("git log failed: {stderr}");
1552 }
1553
1554 let stdout = std::str::from_utf8(&output.stdout)?;
1555 let mut entries = Vec::new();
1556
1557 for commit_block in stdout.split(commit_delimiter) {
1558 let commit_block = commit_block.trim();
1559 if commit_block.is_empty() {
1560 continue;
1561 }
1562
1563 let fields: Vec<&str> = commit_block.split('\0').collect();
1564 if fields.len() >= 6 {
1565 let sha = fields[0].trim().to_string().into();
1566 let subject = fields[1].trim().to_string().into();
1567 let message = fields[2].trim().to_string().into();
1568 let commit_timestamp = fields[3].trim().parse().unwrap_or(0);
1569 let author_name = fields[4].trim().to_string().into();
1570 let author_email = fields[5].trim().to_string().into();
1571
1572 entries.push(FileHistoryEntry {
1573 sha,
1574 subject,
1575 message,
1576 commit_timestamp,
1577 author_name,
1578 author_email,
1579 });
1580 }
1581 }
1582
1583 Ok(FileHistory { entries, path })
1584 })
1585 .boxed()
1586 }
1587
1588 fn diff(&self, diff: DiffType) -> BoxFuture<'_, Result<String>> {
1589 let working_directory = self.working_directory();
1590 let git_binary_path = self.any_git_binary_path.clone();
1591 self.executor
1592 .spawn(async move {
1593 let args = match diff {
1594 DiffType::HeadToIndex => Some("--staged"),
1595 DiffType::HeadToWorktree => None,
1596 };
1597
1598 let output = new_smol_command(&git_binary_path)
1599 .current_dir(&working_directory?)
1600 .args(["diff"])
1601 .args(args)
1602 .output()
1603 .await?;
1604
1605 anyhow::ensure!(
1606 output.status.success(),
1607 "Failed to run git diff:\n{}",
1608 String::from_utf8_lossy(&output.stderr)
1609 );
1610 Ok(String::from_utf8_lossy(&output.stdout).to_string())
1611 })
1612 .boxed()
1613 }
1614
1615 fn stage_paths(
1616 &self,
1617 paths: Vec<RepoPath>,
1618 env: Arc<HashMap<String, String>>,
1619 ) -> BoxFuture<'_, Result<()>> {
1620 let working_directory = self.working_directory();
1621 let git_binary_path = self.any_git_binary_path.clone();
1622 self.executor
1623 .spawn(async move {
1624 if !paths.is_empty() {
1625 let output = new_smol_command(&git_binary_path)
1626 .current_dir(&working_directory?)
1627 .envs(env.iter())
1628 .args(["update-index", "--add", "--remove", "--"])
1629 .args(paths.iter().map(|p| p.as_unix_str()))
1630 .output()
1631 .await?;
1632 anyhow::ensure!(
1633 output.status.success(),
1634 "Failed to stage paths:\n{}",
1635 String::from_utf8_lossy(&output.stderr),
1636 );
1637 }
1638 Ok(())
1639 })
1640 .boxed()
1641 }
1642
1643 fn unstage_paths(
1644 &self,
1645 paths: Vec<RepoPath>,
1646 env: Arc<HashMap<String, String>>,
1647 ) -> BoxFuture<'_, Result<()>> {
1648 let working_directory = self.working_directory();
1649 let git_binary_path = self.any_git_binary_path.clone();
1650
1651 self.executor
1652 .spawn(async move {
1653 if !paths.is_empty() {
1654 let output = new_smol_command(&git_binary_path)
1655 .current_dir(&working_directory?)
1656 .envs(env.iter())
1657 .args(["reset", "--quiet", "--"])
1658 .args(paths.iter().map(|p| p.as_std_path()))
1659 .output()
1660 .await?;
1661
1662 anyhow::ensure!(
1663 output.status.success(),
1664 "Failed to unstage:\n{}",
1665 String::from_utf8_lossy(&output.stderr),
1666 );
1667 }
1668 Ok(())
1669 })
1670 .boxed()
1671 }
1672
1673 fn stash_paths(
1674 &self,
1675 paths: Vec<RepoPath>,
1676 env: Arc<HashMap<String, String>>,
1677 ) -> BoxFuture<'_, Result<()>> {
1678 let working_directory = self.working_directory();
1679 let git_binary_path = self.any_git_binary_path.clone();
1680 self.executor
1681 .spawn(async move {
1682 let mut cmd = new_smol_command(&git_binary_path);
1683 cmd.current_dir(&working_directory?)
1684 .envs(env.iter())
1685 .args(["stash", "push", "--quiet"])
1686 .arg("--include-untracked");
1687
1688 cmd.args(paths.iter().map(|p| p.as_unix_str()));
1689
1690 let output = cmd.output().await?;
1691
1692 anyhow::ensure!(
1693 output.status.success(),
1694 "Failed to stash:\n{}",
1695 String::from_utf8_lossy(&output.stderr)
1696 );
1697 Ok(())
1698 })
1699 .boxed()
1700 }
1701
1702 fn stash_pop(
1703 &self,
1704 index: Option<usize>,
1705 env: Arc<HashMap<String, String>>,
1706 ) -> BoxFuture<'_, Result<()>> {
1707 let working_directory = self.working_directory();
1708 let git_binary_path = self.any_git_binary_path.clone();
1709 self.executor
1710 .spawn(async move {
1711 let mut cmd = new_smol_command(git_binary_path);
1712 let mut args = vec!["stash".to_string(), "pop".to_string()];
1713 if let Some(index) = index {
1714 args.push(format!("stash@{{{}}}", index));
1715 }
1716 cmd.current_dir(&working_directory?)
1717 .envs(env.iter())
1718 .args(args);
1719
1720 let output = cmd.output().await?;
1721
1722 anyhow::ensure!(
1723 output.status.success(),
1724 "Failed to stash pop:\n{}",
1725 String::from_utf8_lossy(&output.stderr)
1726 );
1727 Ok(())
1728 })
1729 .boxed()
1730 }
1731
1732 fn stash_apply(
1733 &self,
1734 index: Option<usize>,
1735 env: Arc<HashMap<String, String>>,
1736 ) -> BoxFuture<'_, Result<()>> {
1737 let working_directory = self.working_directory();
1738 let git_binary_path = self.any_git_binary_path.clone();
1739 self.executor
1740 .spawn(async move {
1741 let mut cmd = new_smol_command(git_binary_path);
1742 let mut args = vec!["stash".to_string(), "apply".to_string()];
1743 if let Some(index) = index {
1744 args.push(format!("stash@{{{}}}", index));
1745 }
1746 cmd.current_dir(&working_directory?)
1747 .envs(env.iter())
1748 .args(args);
1749
1750 let output = cmd.output().await?;
1751
1752 anyhow::ensure!(
1753 output.status.success(),
1754 "Failed to apply stash:\n{}",
1755 String::from_utf8_lossy(&output.stderr)
1756 );
1757 Ok(())
1758 })
1759 .boxed()
1760 }
1761
1762 fn stash_drop(
1763 &self,
1764 index: Option<usize>,
1765 env: Arc<HashMap<String, String>>,
1766 ) -> BoxFuture<'_, Result<()>> {
1767 let working_directory = self.working_directory();
1768 let git_binary_path = self.any_git_binary_path.clone();
1769 self.executor
1770 .spawn(async move {
1771 let mut cmd = new_smol_command(git_binary_path);
1772 let mut args = vec!["stash".to_string(), "drop".to_string()];
1773 if let Some(index) = index {
1774 args.push(format!("stash@{{{}}}", index));
1775 }
1776 cmd.current_dir(&working_directory?)
1777 .envs(env.iter())
1778 .args(args);
1779
1780 let output = cmd.output().await?;
1781
1782 anyhow::ensure!(
1783 output.status.success(),
1784 "Failed to stash drop:\n{}",
1785 String::from_utf8_lossy(&output.stderr)
1786 );
1787 Ok(())
1788 })
1789 .boxed()
1790 }
1791
1792 fn commit(
1793 &self,
1794 message: SharedString,
1795 name_and_email: Option<(SharedString, SharedString)>,
1796 options: CommitOptions,
1797 ask_pass: AskPassDelegate,
1798 env: Arc<HashMap<String, String>>,
1799 ) -> BoxFuture<'_, Result<()>> {
1800 let working_directory = self.working_directory();
1801 let git_binary_path = self.any_git_binary_path.clone();
1802 let executor = self.executor.clone();
1803 // Note: Do not spawn this command on the background thread, it might pop open the credential helper
1804 // which we want to block on.
1805 async move {
1806 let mut cmd = new_smol_command(git_binary_path);
1807 cmd.current_dir(&working_directory?)
1808 .envs(env.iter())
1809 .args(["commit", "--quiet", "-m"])
1810 .arg(&message.to_string())
1811 .arg("--cleanup=strip")
1812 .arg("--no-verify")
1813 .stdout(smol::process::Stdio::piped())
1814 .stderr(smol::process::Stdio::piped());
1815
1816 if options.amend {
1817 cmd.arg("--amend");
1818 }
1819
1820 if options.signoff {
1821 cmd.arg("--signoff");
1822 }
1823
1824 if let Some((name, email)) = name_and_email {
1825 cmd.arg("--author").arg(&format!("{name} <{email}>"));
1826 }
1827
1828 run_git_command(env, ask_pass, cmd, &executor).await?;
1829
1830 Ok(())
1831 }
1832 .boxed()
1833 }
1834
1835 fn push(
1836 &self,
1837 branch_name: String,
1838 remote_name: String,
1839 options: Option<PushOptions>,
1840 ask_pass: AskPassDelegate,
1841 env: Arc<HashMap<String, String>>,
1842 cx: AsyncApp,
1843 ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
1844 let working_directory = self.working_directory();
1845 let executor = cx.background_executor().clone();
1846 let git_binary_path = self.system_git_binary_path.clone();
1847 // Note: Do not spawn this command on the background thread, it might pop open the credential helper
1848 // which we want to block on.
1849 async move {
1850 let git_binary_path = git_binary_path.context("git not found on $PATH, can't push")?;
1851 let working_directory = working_directory?;
1852 let mut command = new_smol_command(git_binary_path);
1853 command
1854 .envs(env.iter())
1855 .current_dir(&working_directory)
1856 .args(["push"])
1857 .args(options.map(|option| match option {
1858 PushOptions::SetUpstream => "--set-upstream",
1859 PushOptions::Force => "--force-with-lease",
1860 }))
1861 .arg(remote_name)
1862 .arg(format!("{}:{}", branch_name, branch_name))
1863 .stdin(smol::process::Stdio::null())
1864 .stdout(smol::process::Stdio::piped())
1865 .stderr(smol::process::Stdio::piped());
1866
1867 run_git_command(env, ask_pass, command, &executor).await
1868 }
1869 .boxed()
1870 }
1871
1872 fn pull(
1873 &self,
1874 branch_name: Option<String>,
1875 remote_name: String,
1876 rebase: bool,
1877 ask_pass: AskPassDelegate,
1878 env: Arc<HashMap<String, String>>,
1879 cx: AsyncApp,
1880 ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
1881 let working_directory = self.working_directory();
1882 let executor = cx.background_executor().clone();
1883 let git_binary_path = self.system_git_binary_path.clone();
1884 // Note: Do not spawn this command on the background thread, it might pop open the credential helper
1885 // which we want to block on.
1886 async move {
1887 let git_binary_path = git_binary_path.context("git not found on $PATH, can't pull")?;
1888 let mut command = new_smol_command(git_binary_path);
1889 command
1890 .envs(env.iter())
1891 .current_dir(&working_directory?)
1892 .arg("pull");
1893
1894 if rebase {
1895 command.arg("--rebase");
1896 }
1897
1898 command
1899 .arg(remote_name)
1900 .args(branch_name)
1901 .stdout(smol::process::Stdio::piped())
1902 .stderr(smol::process::Stdio::piped());
1903
1904 run_git_command(env, ask_pass, command, &executor).await
1905 }
1906 .boxed()
1907 }
1908
1909 fn fetch(
1910 &self,
1911 fetch_options: FetchOptions,
1912 ask_pass: AskPassDelegate,
1913 env: Arc<HashMap<String, String>>,
1914 cx: AsyncApp,
1915 ) -> BoxFuture<'_, Result<RemoteCommandOutput>> {
1916 let working_directory = self.working_directory();
1917 let remote_name = format!("{}", fetch_options);
1918 let git_binary_path = self.system_git_binary_path.clone();
1919 let executor = cx.background_executor().clone();
1920 // Note: Do not spawn this command on the background thread, it might pop open the credential helper
1921 // which we want to block on.
1922 async move {
1923 let git_binary_path = git_binary_path.context("git not found on $PATH, can't fetch")?;
1924 let mut command = new_smol_command(git_binary_path);
1925 command
1926 .envs(env.iter())
1927 .current_dir(&working_directory?)
1928 .args(["fetch", &remote_name])
1929 .stdout(smol::process::Stdio::piped())
1930 .stderr(smol::process::Stdio::piped());
1931
1932 run_git_command(env, ask_pass, command, &executor).await
1933 }
1934 .boxed()
1935 }
1936
1937 fn get_push_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
1938 let working_directory = self.working_directory();
1939 let git_binary_path = self.any_git_binary_path.clone();
1940 self.executor
1941 .spawn(async move {
1942 let working_directory = working_directory?;
1943 let output = new_smol_command(&git_binary_path)
1944 .current_dir(&working_directory)
1945 .args(["rev-parse", "--abbrev-ref"])
1946 .arg(format!("{branch}@{{push}}"))
1947 .output()
1948 .await?;
1949 if !output.status.success() {
1950 return Ok(None);
1951 }
1952 let remote_name = String::from_utf8_lossy(&output.stdout)
1953 .split('/')
1954 .next()
1955 .map(|name| Remote {
1956 name: name.trim().to_string().into(),
1957 });
1958
1959 Ok(remote_name)
1960 })
1961 .boxed()
1962 }
1963
1964 fn get_branch_remote(&self, branch: String) -> BoxFuture<'_, Result<Option<Remote>>> {
1965 let working_directory = self.working_directory();
1966 let git_binary_path = self.any_git_binary_path.clone();
1967 self.executor
1968 .spawn(async move {
1969 let working_directory = working_directory?;
1970 let output = new_smol_command(&git_binary_path)
1971 .current_dir(&working_directory)
1972 .args(["config", "--get"])
1973 .arg(format!("branch.{branch}.remote"))
1974 .output()
1975 .await?;
1976 if !output.status.success() {
1977 return Ok(None);
1978 }
1979
1980 let remote_name = String::from_utf8_lossy(&output.stdout);
1981 return Ok(Some(Remote {
1982 name: remote_name.trim().to_string().into(),
1983 }));
1984 })
1985 .boxed()
1986 }
1987
1988 fn get_all_remotes(&self) -> BoxFuture<'_, Result<Vec<Remote>>> {
1989 let working_directory = self.working_directory();
1990 let git_binary_path = self.any_git_binary_path.clone();
1991 self.executor
1992 .spawn(async move {
1993 let working_directory = working_directory?;
1994 let output = new_smol_command(&git_binary_path)
1995 .current_dir(&working_directory)
1996 .args(["remote"])
1997 .output()
1998 .await?;
1999
2000 anyhow::ensure!(
2001 output.status.success(),
2002 "Failed to get all remotes:\n{}",
2003 String::from_utf8_lossy(&output.stderr)
2004 );
2005 let remote_names = String::from_utf8_lossy(&output.stdout)
2006 .split('\n')
2007 .filter(|name| !name.is_empty())
2008 .map(|name| Remote {
2009 name: name.trim().to_string().into(),
2010 })
2011 .collect();
2012 Ok(remote_names)
2013 })
2014 .boxed()
2015 }
2016
2017 fn check_for_pushed_commit(&self) -> BoxFuture<'_, Result<Vec<SharedString>>> {
2018 let working_directory = self.working_directory();
2019 let git_binary_path = self.any_git_binary_path.clone();
2020 self.executor
2021 .spawn(async move {
2022 let working_directory = working_directory?;
2023 let git_cmd = async |args: &[&str]| -> Result<String> {
2024 let output = new_smol_command(&git_binary_path)
2025 .current_dir(&working_directory)
2026 .args(args)
2027 .output()
2028 .await?;
2029 anyhow::ensure!(
2030 output.status.success(),
2031 String::from_utf8_lossy(&output.stderr).to_string()
2032 );
2033 Ok(String::from_utf8(output.stdout)?)
2034 };
2035
2036 let head = git_cmd(&["rev-parse", "HEAD"])
2037 .await
2038 .context("Failed to get HEAD")?
2039 .trim()
2040 .to_owned();
2041
2042 let mut remote_branches = vec![];
2043 let mut add_if_matching = async |remote_head: &str| {
2044 if let Ok(merge_base) = git_cmd(&["merge-base", &head, remote_head]).await
2045 && merge_base.trim() == head
2046 && let Some(s) = remote_head.strip_prefix("refs/remotes/")
2047 {
2048 remote_branches.push(s.to_owned().into());
2049 }
2050 };
2051
2052 // check the main branch of each remote
2053 let remotes = git_cmd(&["remote"])
2054 .await
2055 .context("Failed to get remotes")?;
2056 for remote in remotes.lines() {
2057 if let Ok(remote_head) =
2058 git_cmd(&["symbolic-ref", &format!("refs/remotes/{remote}/HEAD")]).await
2059 {
2060 add_if_matching(remote_head.trim()).await;
2061 }
2062 }
2063
2064 // ... and the remote branch that the checked-out one is tracking
2065 if let Ok(remote_head) =
2066 git_cmd(&["rev-parse", "--symbolic-full-name", "@{u}"]).await
2067 {
2068 add_if_matching(remote_head.trim()).await;
2069 }
2070
2071 Ok(remote_branches)
2072 })
2073 .boxed()
2074 }
2075
2076 fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>> {
2077 let working_directory = self.working_directory();
2078 let git_binary_path = self.any_git_binary_path.clone();
2079 let executor = self.executor.clone();
2080 self.executor
2081 .spawn(async move {
2082 let working_directory = working_directory?;
2083 let mut git = GitBinary::new(git_binary_path, working_directory.clone(), executor)
2084 .envs(checkpoint_author_envs());
2085 git.with_temp_index(async |git| {
2086 let head_sha = git.run(&["rev-parse", "HEAD"]).await.ok();
2087 let mut excludes = exclude_files(git).await?;
2088
2089 git.run(&["add", "--all"]).await?;
2090 let tree = git.run(&["write-tree"]).await?;
2091 let checkpoint_sha = if let Some(head_sha) = head_sha.as_deref() {
2092 git.run(&["commit-tree", &tree, "-p", head_sha, "-m", "Checkpoint"])
2093 .await?
2094 } else {
2095 git.run(&["commit-tree", &tree, "-m", "Checkpoint"]).await?
2096 };
2097
2098 excludes.restore_original().await?;
2099
2100 Ok(GitRepositoryCheckpoint {
2101 commit_sha: checkpoint_sha.parse()?,
2102 })
2103 })
2104 .await
2105 })
2106 .boxed()
2107 }
2108
2109 fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<'_, Result<()>> {
2110 let working_directory = self.working_directory();
2111 let git_binary_path = self.any_git_binary_path.clone();
2112
2113 let executor = self.executor.clone();
2114 self.executor
2115 .spawn(async move {
2116 let working_directory = working_directory?;
2117
2118 let git = GitBinary::new(git_binary_path, working_directory, executor);
2119 git.run(&[
2120 "restore",
2121 "--source",
2122 &checkpoint.commit_sha.to_string(),
2123 "--worktree",
2124 ".",
2125 ])
2126 .await?;
2127
2128 // TODO: We don't track binary and large files anymore,
2129 // so the following call would delete them.
2130 // Implement an alternative way to track files added by agent.
2131 //
2132 // git.with_temp_index(async move |git| {
2133 // git.run(&["read-tree", &checkpoint.commit_sha.to_string()])
2134 // .await?;
2135 // git.run(&["clean", "-d", "--force"]).await
2136 // })
2137 // .await?;
2138
2139 Ok(())
2140 })
2141 .boxed()
2142 }
2143
2144 fn compare_checkpoints(
2145 &self,
2146 left: GitRepositoryCheckpoint,
2147 right: GitRepositoryCheckpoint,
2148 ) -> BoxFuture<'_, Result<bool>> {
2149 let working_directory = self.working_directory();
2150 let git_binary_path = self.any_git_binary_path.clone();
2151
2152 let executor = self.executor.clone();
2153 self.executor
2154 .spawn(async move {
2155 let working_directory = working_directory?;
2156 let git = GitBinary::new(git_binary_path, working_directory, executor);
2157 let result = git
2158 .run(&[
2159 "diff-tree",
2160 "--quiet",
2161 &left.commit_sha.to_string(),
2162 &right.commit_sha.to_string(),
2163 ])
2164 .await;
2165 match result {
2166 Ok(_) => Ok(true),
2167 Err(error) => {
2168 if let Some(GitBinaryCommandError { status, .. }) =
2169 error.downcast_ref::<GitBinaryCommandError>()
2170 && status.code() == Some(1)
2171 {
2172 return Ok(false);
2173 }
2174
2175 Err(error)
2176 }
2177 }
2178 })
2179 .boxed()
2180 }
2181
2182 fn diff_checkpoints(
2183 &self,
2184 base_checkpoint: GitRepositoryCheckpoint,
2185 target_checkpoint: GitRepositoryCheckpoint,
2186 ) -> BoxFuture<'_, Result<String>> {
2187 let working_directory = self.working_directory();
2188 let git_binary_path = self.any_git_binary_path.clone();
2189
2190 let executor = self.executor.clone();
2191 self.executor
2192 .spawn(async move {
2193 let working_directory = working_directory?;
2194 let git = GitBinary::new(git_binary_path, working_directory, executor);
2195 git.run(&[
2196 "diff",
2197 "--find-renames",
2198 "--patch",
2199 &base_checkpoint.commit_sha.to_string(),
2200 &target_checkpoint.commit_sha.to_string(),
2201 ])
2202 .await
2203 })
2204 .boxed()
2205 }
2206
2207 fn default_branch(&self) -> BoxFuture<'_, Result<Option<SharedString>>> {
2208 let working_directory = self.working_directory();
2209 let git_binary_path = self.any_git_binary_path.clone();
2210
2211 let executor = self.executor.clone();
2212 self.executor
2213 .spawn(async move {
2214 let working_directory = working_directory?;
2215 let git = GitBinary::new(git_binary_path, working_directory, executor);
2216
2217 if let Ok(output) = git
2218 .run(&["symbolic-ref", "refs/remotes/upstream/HEAD"])
2219 .await
2220 {
2221 let output = output
2222 .strip_prefix("refs/remotes/upstream/")
2223 .map(|s| SharedString::from(s.to_owned()));
2224 return Ok(output);
2225 }
2226
2227 if let Ok(output) = git.run(&["symbolic-ref", "refs/remotes/origin/HEAD"]).await {
2228 return Ok(output
2229 .strip_prefix("refs/remotes/origin/")
2230 .map(|s| SharedString::from(s.to_owned())));
2231 }
2232
2233 if let Ok(default_branch) = git.run(&["config", "init.defaultBranch"]).await {
2234 if git.run(&["rev-parse", &default_branch]).await.is_ok() {
2235 return Ok(Some(default_branch.into()));
2236 }
2237 }
2238
2239 if git.run(&["rev-parse", "master"]).await.is_ok() {
2240 return Ok(Some("master".into()));
2241 }
2242
2243 Ok(None)
2244 })
2245 .boxed()
2246 }
2247
2248 fn run_hook(
2249 &self,
2250 hook: RunHook,
2251 env: Arc<HashMap<String, String>>,
2252 ) -> BoxFuture<'_, Result<()>> {
2253 let working_directory = self.working_directory();
2254 let git_binary_path = self.any_git_binary_path.clone();
2255 let executor = self.executor.clone();
2256 self.executor
2257 .spawn(async move {
2258 let working_directory = working_directory?;
2259 let git = GitBinary::new(git_binary_path, working_directory, executor)
2260 .envs(HashMap::clone(&env));
2261 git.run(&["hook", "run", "--ignore-missing", hook.as_str()])
2262 .await?;
2263 Ok(())
2264 })
2265 .boxed()
2266 }
2267}
2268
2269fn git_status_args(path_prefixes: &[RepoPath]) -> Vec<OsString> {
2270 let mut args = vec![
2271 OsString::from("--no-optional-locks"),
2272 OsString::from("status"),
2273 OsString::from("--porcelain=v1"),
2274 OsString::from("--untracked-files=all"),
2275 OsString::from("--no-renames"),
2276 OsString::from("-z"),
2277 ];
2278 args.extend(
2279 path_prefixes
2280 .iter()
2281 .map(|path_prefix| path_prefix.as_std_path().into()),
2282 );
2283 args.extend(path_prefixes.iter().map(|path_prefix| {
2284 if path_prefix.is_empty() {
2285 Path::new(".").into()
2286 } else {
2287 path_prefix.as_std_path().into()
2288 }
2289 }));
2290 args
2291}
2292
2293/// Temporarily git-ignore commonly ignored files and files over 2MB
2294async fn exclude_files(git: &GitBinary) -> Result<GitExcludeOverride> {
2295 const MAX_SIZE: u64 = 2 * 1024 * 1024; // 2 MB
2296 let mut excludes = git.with_exclude_overrides().await?;
2297 excludes
2298 .add_excludes(include_str!("./checkpoint.gitignore"))
2299 .await?;
2300
2301 let working_directory = git.working_directory.clone();
2302 let untracked_files = git.list_untracked_files().await?;
2303 let excluded_paths = untracked_files.into_iter().map(|path| {
2304 let working_directory = working_directory.clone();
2305 smol::spawn(async move {
2306 let full_path = working_directory.join(path.clone());
2307 match smol::fs::metadata(&full_path).await {
2308 Ok(metadata) if metadata.is_file() && metadata.len() >= MAX_SIZE => {
2309 Some(PathBuf::from("/").join(path.clone()))
2310 }
2311 _ => None,
2312 }
2313 })
2314 });
2315
2316 let excluded_paths = futures::future::join_all(excluded_paths).await;
2317 let excluded_paths = excluded_paths.into_iter().flatten().collect::<Vec<_>>();
2318
2319 if !excluded_paths.is_empty() {
2320 let exclude_patterns = excluded_paths
2321 .into_iter()
2322 .map(|path| path.to_string_lossy().into_owned())
2323 .collect::<Vec<_>>()
2324 .join("\n");
2325 excludes.add_excludes(&exclude_patterns).await?;
2326 }
2327
2328 Ok(excludes)
2329}
2330
2331struct GitBinary {
2332 git_binary_path: PathBuf,
2333 working_directory: PathBuf,
2334 executor: BackgroundExecutor,
2335 index_file_path: Option<PathBuf>,
2336 envs: HashMap<String, String>,
2337}
2338
2339impl GitBinary {
2340 fn new(
2341 git_binary_path: PathBuf,
2342 working_directory: PathBuf,
2343 executor: BackgroundExecutor,
2344 ) -> Self {
2345 Self {
2346 git_binary_path,
2347 working_directory,
2348 executor,
2349 index_file_path: None,
2350 envs: HashMap::default(),
2351 }
2352 }
2353
2354 async fn list_untracked_files(&self) -> Result<Vec<PathBuf>> {
2355 let status_output = self
2356 .run(&["status", "--porcelain=v1", "--untracked-files=all", "-z"])
2357 .await?;
2358
2359 let paths = status_output
2360 .split('\0')
2361 .filter(|entry| entry.len() >= 3 && entry.starts_with("?? "))
2362 .map(|entry| PathBuf::from(&entry[3..]))
2363 .collect::<Vec<_>>();
2364 Ok(paths)
2365 }
2366
2367 fn envs(mut self, envs: HashMap<String, String>) -> Self {
2368 self.envs = envs;
2369 self
2370 }
2371
2372 pub async fn with_temp_index<R>(
2373 &mut self,
2374 f: impl AsyncFnOnce(&Self) -> Result<R>,
2375 ) -> Result<R> {
2376 let index_file_path = self.path_for_index_id(Uuid::new_v4());
2377
2378 let delete_temp_index = util::defer({
2379 let index_file_path = index_file_path.clone();
2380 let executor = self.executor.clone();
2381 move || {
2382 executor
2383 .spawn(async move {
2384 smol::fs::remove_file(index_file_path).await.log_err();
2385 })
2386 .detach();
2387 }
2388 });
2389
2390 // Copy the default index file so that Git doesn't have to rebuild the
2391 // whole index from scratch. This might fail if this is an empty repository.
2392 smol::fs::copy(
2393 self.working_directory.join(".git").join("index"),
2394 &index_file_path,
2395 )
2396 .await
2397 .ok();
2398
2399 self.index_file_path = Some(index_file_path.clone());
2400 let result = f(self).await;
2401 self.index_file_path = None;
2402 let result = result?;
2403
2404 smol::fs::remove_file(index_file_path).await.ok();
2405 delete_temp_index.abort();
2406
2407 Ok(result)
2408 }
2409
2410 pub async fn with_exclude_overrides(&self) -> Result<GitExcludeOverride> {
2411 let path = self
2412 .working_directory
2413 .join(".git")
2414 .join("info")
2415 .join("exclude");
2416
2417 GitExcludeOverride::new(path).await
2418 }
2419
2420 fn path_for_index_id(&self, id: Uuid) -> PathBuf {
2421 self.working_directory
2422 .join(".git")
2423 .join(format!("index-{}.tmp", id))
2424 }
2425
2426 pub async fn run<S>(&self, args: impl IntoIterator<Item = S>) -> Result<String>
2427 where
2428 S: AsRef<OsStr>,
2429 {
2430 let mut stdout = self.run_raw(args).await?;
2431 if stdout.chars().last() == Some('\n') {
2432 stdout.pop();
2433 }
2434 Ok(stdout)
2435 }
2436
2437 /// Returns the result of the command without trimming the trailing newline.
2438 pub async fn run_raw<S>(&self, args: impl IntoIterator<Item = S>) -> Result<String>
2439 where
2440 S: AsRef<OsStr>,
2441 {
2442 let mut command = self.build_command(args);
2443 let output = command.output().await?;
2444 anyhow::ensure!(
2445 output.status.success(),
2446 GitBinaryCommandError {
2447 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
2448 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
2449 status: output.status,
2450 }
2451 );
2452 Ok(String::from_utf8(output.stdout)?)
2453 }
2454
2455 fn build_command<S>(&self, args: impl IntoIterator<Item = S>) -> smol::process::Command
2456 where
2457 S: AsRef<OsStr>,
2458 {
2459 let mut command = new_smol_command(&self.git_binary_path);
2460 command.current_dir(&self.working_directory);
2461 command.args(args);
2462 if let Some(index_file_path) = self.index_file_path.as_ref() {
2463 command.env("GIT_INDEX_FILE", index_file_path);
2464 }
2465 command.envs(&self.envs);
2466 command
2467 }
2468}
2469
2470#[derive(Error, Debug)]
2471#[error("Git command failed:\n{stdout}{stderr}\n")]
2472struct GitBinaryCommandError {
2473 stdout: String,
2474 stderr: String,
2475 status: ExitStatus,
2476}
2477
2478async fn run_git_command(
2479 env: Arc<HashMap<String, String>>,
2480 ask_pass: AskPassDelegate,
2481 mut command: smol::process::Command,
2482 executor: &BackgroundExecutor,
2483) -> Result<RemoteCommandOutput> {
2484 if env.contains_key("GIT_ASKPASS") {
2485 let git_process = command.spawn()?;
2486 let output = git_process.output().await?;
2487 anyhow::ensure!(
2488 output.status.success(),
2489 "{}",
2490 String::from_utf8_lossy(&output.stderr)
2491 );
2492 Ok(RemoteCommandOutput {
2493 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
2494 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
2495 })
2496 } else {
2497 let ask_pass = AskPassSession::new(executor, ask_pass).await?;
2498 command
2499 .env("GIT_ASKPASS", ask_pass.script_path())
2500 .env("SSH_ASKPASS", ask_pass.script_path())
2501 .env("SSH_ASKPASS_REQUIRE", "force");
2502 let git_process = command.spawn()?;
2503
2504 run_askpass_command(ask_pass, git_process).await
2505 }
2506}
2507
2508async fn run_askpass_command(
2509 mut ask_pass: AskPassSession,
2510 git_process: smol::process::Child,
2511) -> anyhow::Result<RemoteCommandOutput> {
2512 select_biased! {
2513 result = ask_pass.run().fuse() => {
2514 match result {
2515 AskPassResult::CancelledByUser => {
2516 Err(anyhow!(REMOTE_CANCELLED_BY_USER))?
2517 }
2518 AskPassResult::Timedout => {
2519 Err(anyhow!("Connecting to host timed out"))?
2520 }
2521 }
2522 }
2523 output = git_process.output().fuse() => {
2524 let output = output?;
2525 anyhow::ensure!(
2526 output.status.success(),
2527 "{}",
2528 String::from_utf8_lossy(&output.stderr)
2529 );
2530 Ok(RemoteCommandOutput {
2531 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
2532 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
2533 })
2534 }
2535 }
2536}
2537
2538#[derive(Clone, Ord, Hash, PartialOrd, Eq, PartialEq)]
2539pub struct RepoPath(Arc<RelPath>);
2540
2541impl std::fmt::Debug for RepoPath {
2542 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2543 self.0.fmt(f)
2544 }
2545}
2546
2547impl RepoPath {
2548 pub fn new<S: AsRef<str> + ?Sized>(s: &S) -> Result<Self> {
2549 let rel_path = RelPath::unix(s.as_ref())?;
2550 Ok(Self::from_rel_path(rel_path))
2551 }
2552
2553 pub fn from_std_path(path: &Path, path_style: PathStyle) -> Result<Self> {
2554 let rel_path = RelPath::new(path, path_style)?;
2555 Ok(Self::from_rel_path(&rel_path))
2556 }
2557
2558 pub fn from_proto(proto: &str) -> Result<Self> {
2559 let rel_path = RelPath::from_proto(proto)?;
2560 Ok(Self(rel_path))
2561 }
2562
2563 pub fn from_rel_path(path: &RelPath) -> RepoPath {
2564 Self(Arc::from(path))
2565 }
2566
2567 pub fn as_std_path(&self) -> &Path {
2568 // git2 does not like empty paths and our RelPath infra turns `.` into ``
2569 // so undo that here
2570 if self.is_empty() {
2571 Path::new(".")
2572 } else {
2573 self.0.as_std_path()
2574 }
2575 }
2576}
2577
2578#[cfg(any(test, feature = "test-support"))]
2579pub fn repo_path<S: AsRef<str> + ?Sized>(s: &S) -> RepoPath {
2580 RepoPath(RelPath::unix(s.as_ref()).unwrap().into())
2581}
2582
2583impl AsRef<Arc<RelPath>> for RepoPath {
2584 fn as_ref(&self) -> &Arc<RelPath> {
2585 &self.0
2586 }
2587}
2588
2589impl std::ops::Deref for RepoPath {
2590 type Target = RelPath;
2591
2592 fn deref(&self) -> &Self::Target {
2593 &self.0
2594 }
2595}
2596
2597#[derive(Debug)]
2598pub struct RepoPathDescendants<'a>(pub &'a RepoPath);
2599
2600impl MapSeekTarget<RepoPath> for RepoPathDescendants<'_> {
2601 fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
2602 if key.starts_with(self.0) {
2603 Ordering::Greater
2604 } else {
2605 self.0.cmp(key)
2606 }
2607 }
2608}
2609
2610fn parse_branch_input(input: &str) -> Result<Vec<Branch>> {
2611 let mut branches = Vec::new();
2612 for line in input.split('\n') {
2613 if line.is_empty() {
2614 continue;
2615 }
2616 let mut fields = line.split('\x00');
2617 let Some(head) = fields.next() else {
2618 continue;
2619 };
2620 let Some(head_sha) = fields.next().map(|f| f.to_string().into()) else {
2621 continue;
2622 };
2623 let Some(parent_sha) = fields.next().map(|f| f.to_string()) else {
2624 continue;
2625 };
2626 let Some(ref_name) = fields.next().map(|f| f.to_string().into()) else {
2627 continue;
2628 };
2629 let Some(upstream_name) = fields.next().map(|f| f.to_string()) else {
2630 continue;
2631 };
2632 let Some(upstream_tracking) = fields.next().and_then(|f| parse_upstream_track(f).ok())
2633 else {
2634 continue;
2635 };
2636 let Some(commiterdate) = fields.next().and_then(|f| f.parse::<i64>().ok()) else {
2637 continue;
2638 };
2639 let Some(author_name) = fields.next().map(|f| f.to_string().into()) else {
2640 continue;
2641 };
2642 let Some(subject) = fields.next().map(|f| f.to_string().into()) else {
2643 continue;
2644 };
2645
2646 branches.push(Branch {
2647 is_head: head == "*",
2648 ref_name,
2649 most_recent_commit: Some(CommitSummary {
2650 sha: head_sha,
2651 subject,
2652 commit_timestamp: commiterdate,
2653 author_name: author_name,
2654 has_parent: !parent_sha.is_empty(),
2655 }),
2656 upstream: if upstream_name.is_empty() {
2657 None
2658 } else {
2659 Some(Upstream {
2660 ref_name: upstream_name.into(),
2661 tracking: upstream_tracking,
2662 })
2663 },
2664 })
2665 }
2666
2667 Ok(branches)
2668}
2669
2670fn parse_upstream_track(upstream_track: &str) -> Result<UpstreamTracking> {
2671 if upstream_track.is_empty() {
2672 return Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
2673 ahead: 0,
2674 behind: 0,
2675 }));
2676 }
2677
2678 let upstream_track = upstream_track.strip_prefix("[").context("missing [")?;
2679 let upstream_track = upstream_track.strip_suffix("]").context("missing [")?;
2680 let mut ahead: u32 = 0;
2681 let mut behind: u32 = 0;
2682 for component in upstream_track.split(", ") {
2683 if component == "gone" {
2684 return Ok(UpstreamTracking::Gone);
2685 }
2686 if let Some(ahead_num) = component.strip_prefix("ahead ") {
2687 ahead = ahead_num.parse::<u32>()?;
2688 }
2689 if let Some(behind_num) = component.strip_prefix("behind ") {
2690 behind = behind_num.parse::<u32>()?;
2691 }
2692 }
2693 Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
2694 ahead,
2695 behind,
2696 }))
2697}
2698
2699fn checkpoint_author_envs() -> HashMap<String, String> {
2700 HashMap::from_iter([
2701 ("GIT_AUTHOR_NAME".to_string(), "Zed".to_string()),
2702 ("GIT_AUTHOR_EMAIL".to_string(), "hi@zed.dev".to_string()),
2703 ("GIT_COMMITTER_NAME".to_string(), "Zed".to_string()),
2704 ("GIT_COMMITTER_EMAIL".to_string(), "hi@zed.dev".to_string()),
2705 ])
2706}
2707
2708#[cfg(test)]
2709mod tests {
2710 use super::*;
2711 use gpui::TestAppContext;
2712
2713 fn disable_git_global_config() {
2714 unsafe {
2715 std::env::set_var("GIT_CONFIG_GLOBAL", "");
2716 std::env::set_var("GIT_CONFIG_SYSTEM", "");
2717 }
2718 }
2719
2720 #[gpui::test]
2721 async fn test_checkpoint_basic(cx: &mut TestAppContext) {
2722 disable_git_global_config();
2723
2724 cx.executor().allow_parking();
2725
2726 let repo_dir = tempfile::tempdir().unwrap();
2727
2728 git2::Repository::init(repo_dir.path()).unwrap();
2729 let file_path = repo_dir.path().join("file");
2730 smol::fs::write(&file_path, "initial").await.unwrap();
2731
2732 let repo = RealGitRepository::new(
2733 &repo_dir.path().join(".git"),
2734 None,
2735 Some("git".into()),
2736 cx.executor(),
2737 )
2738 .unwrap();
2739
2740 repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
2741 .await
2742 .unwrap();
2743 repo.commit(
2744 "Initial commit".into(),
2745 None,
2746 CommitOptions::default(),
2747 AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
2748 Arc::new(checkpoint_author_envs()),
2749 )
2750 .await
2751 .unwrap();
2752
2753 smol::fs::write(&file_path, "modified before checkpoint")
2754 .await
2755 .unwrap();
2756 smol::fs::write(repo_dir.path().join("new_file_before_checkpoint"), "1")
2757 .await
2758 .unwrap();
2759 let checkpoint = repo.checkpoint().await.unwrap();
2760
2761 // Ensure the user can't see any branches after creating a checkpoint.
2762 assert_eq!(repo.branches().await.unwrap().len(), 1);
2763
2764 smol::fs::write(&file_path, "modified after checkpoint")
2765 .await
2766 .unwrap();
2767 repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
2768 .await
2769 .unwrap();
2770 repo.commit(
2771 "Commit after checkpoint".into(),
2772 None,
2773 CommitOptions::default(),
2774 AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
2775 Arc::new(checkpoint_author_envs()),
2776 )
2777 .await
2778 .unwrap();
2779
2780 smol::fs::remove_file(repo_dir.path().join("new_file_before_checkpoint"))
2781 .await
2782 .unwrap();
2783 smol::fs::write(repo_dir.path().join("new_file_after_checkpoint"), "2")
2784 .await
2785 .unwrap();
2786
2787 // Ensure checkpoint stays alive even after a Git GC.
2788 repo.gc().await.unwrap();
2789 repo.restore_checkpoint(checkpoint.clone()).await.unwrap();
2790
2791 assert_eq!(
2792 smol::fs::read_to_string(&file_path).await.unwrap(),
2793 "modified before checkpoint"
2794 );
2795 assert_eq!(
2796 smol::fs::read_to_string(repo_dir.path().join("new_file_before_checkpoint"))
2797 .await
2798 .unwrap(),
2799 "1"
2800 );
2801 // See TODO above
2802 // assert_eq!(
2803 // smol::fs::read_to_string(repo_dir.path().join("new_file_after_checkpoint"))
2804 // .await
2805 // .ok(),
2806 // None
2807 // );
2808 }
2809
2810 #[gpui::test]
2811 async fn test_checkpoint_empty_repo(cx: &mut TestAppContext) {
2812 disable_git_global_config();
2813
2814 cx.executor().allow_parking();
2815
2816 let repo_dir = tempfile::tempdir().unwrap();
2817 git2::Repository::init(repo_dir.path()).unwrap();
2818 let repo = RealGitRepository::new(
2819 &repo_dir.path().join(".git"),
2820 None,
2821 Some("git".into()),
2822 cx.executor(),
2823 )
2824 .unwrap();
2825
2826 smol::fs::write(repo_dir.path().join("foo"), "foo")
2827 .await
2828 .unwrap();
2829 let checkpoint_sha = repo.checkpoint().await.unwrap();
2830
2831 // Ensure the user can't see any branches after creating a checkpoint.
2832 assert_eq!(repo.branches().await.unwrap().len(), 1);
2833
2834 smol::fs::write(repo_dir.path().join("foo"), "bar")
2835 .await
2836 .unwrap();
2837 smol::fs::write(repo_dir.path().join("baz"), "qux")
2838 .await
2839 .unwrap();
2840 repo.restore_checkpoint(checkpoint_sha).await.unwrap();
2841 assert_eq!(
2842 smol::fs::read_to_string(repo_dir.path().join("foo"))
2843 .await
2844 .unwrap(),
2845 "foo"
2846 );
2847 // See TODOs above
2848 // assert_eq!(
2849 // smol::fs::read_to_string(repo_dir.path().join("baz"))
2850 // .await
2851 // .ok(),
2852 // None
2853 // );
2854 }
2855
2856 #[gpui::test]
2857 async fn test_compare_checkpoints(cx: &mut TestAppContext) {
2858 disable_git_global_config();
2859
2860 cx.executor().allow_parking();
2861
2862 let repo_dir = tempfile::tempdir().unwrap();
2863 git2::Repository::init(repo_dir.path()).unwrap();
2864 let repo = RealGitRepository::new(
2865 &repo_dir.path().join(".git"),
2866 None,
2867 Some("git".into()),
2868 cx.executor(),
2869 )
2870 .unwrap();
2871
2872 smol::fs::write(repo_dir.path().join("file1"), "content1")
2873 .await
2874 .unwrap();
2875 let checkpoint1 = repo.checkpoint().await.unwrap();
2876
2877 smol::fs::write(repo_dir.path().join("file2"), "content2")
2878 .await
2879 .unwrap();
2880 let checkpoint2 = repo.checkpoint().await.unwrap();
2881
2882 assert!(
2883 !repo
2884 .compare_checkpoints(checkpoint1, checkpoint2.clone())
2885 .await
2886 .unwrap()
2887 );
2888
2889 let checkpoint3 = repo.checkpoint().await.unwrap();
2890 assert!(
2891 repo.compare_checkpoints(checkpoint2, checkpoint3)
2892 .await
2893 .unwrap()
2894 );
2895 }
2896
2897 #[gpui::test]
2898 async fn test_checkpoint_exclude_binary_files(cx: &mut TestAppContext) {
2899 disable_git_global_config();
2900
2901 cx.executor().allow_parking();
2902
2903 let repo_dir = tempfile::tempdir().unwrap();
2904 let text_path = repo_dir.path().join("main.rs");
2905 let bin_path = repo_dir.path().join("binary.o");
2906
2907 git2::Repository::init(repo_dir.path()).unwrap();
2908
2909 smol::fs::write(&text_path, "fn main() {}").await.unwrap();
2910
2911 smol::fs::write(&bin_path, "some binary file here")
2912 .await
2913 .unwrap();
2914
2915 let repo = RealGitRepository::new(
2916 &repo_dir.path().join(".git"),
2917 None,
2918 Some("git".into()),
2919 cx.executor(),
2920 )
2921 .unwrap();
2922
2923 // initial commit
2924 repo.stage_paths(vec![repo_path("main.rs")], Arc::new(HashMap::default()))
2925 .await
2926 .unwrap();
2927 repo.commit(
2928 "Initial commit".into(),
2929 None,
2930 CommitOptions::default(),
2931 AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
2932 Arc::new(checkpoint_author_envs()),
2933 )
2934 .await
2935 .unwrap();
2936
2937 let checkpoint = repo.checkpoint().await.unwrap();
2938
2939 smol::fs::write(&text_path, "fn main() { println!(\"Modified\"); }")
2940 .await
2941 .unwrap();
2942 smol::fs::write(&bin_path, "Modified binary file")
2943 .await
2944 .unwrap();
2945
2946 repo.restore_checkpoint(checkpoint).await.unwrap();
2947
2948 // Text files should be restored to checkpoint state,
2949 // but binaries should not (they aren't tracked)
2950 assert_eq!(
2951 smol::fs::read_to_string(&text_path).await.unwrap(),
2952 "fn main() {}"
2953 );
2954
2955 assert_eq!(
2956 smol::fs::read_to_string(&bin_path).await.unwrap(),
2957 "Modified binary file"
2958 );
2959 }
2960
2961 #[test]
2962 fn test_branches_parsing() {
2963 // suppress "help: octal escapes are not supported, `\0` is always null"
2964 #[allow(clippy::octal_escapes)]
2965 let input = "*\0060964da10574cd9bf06463a53bf6e0769c5c45e\0\0refs/heads/zed-patches\0refs/remotes/origin/zed-patches\0\01733187470\0John Doe\0generated protobuf\n";
2966 assert_eq!(
2967 parse_branch_input(input).unwrap(),
2968 vec![Branch {
2969 is_head: true,
2970 ref_name: "refs/heads/zed-patches".into(),
2971 upstream: Some(Upstream {
2972 ref_name: "refs/remotes/origin/zed-patches".into(),
2973 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
2974 ahead: 0,
2975 behind: 0
2976 })
2977 }),
2978 most_recent_commit: Some(CommitSummary {
2979 sha: "060964da10574cd9bf06463a53bf6e0769c5c45e".into(),
2980 subject: "generated protobuf".into(),
2981 commit_timestamp: 1733187470,
2982 author_name: SharedString::new("John Doe"),
2983 has_parent: false,
2984 })
2985 }]
2986 )
2987 }
2988
2989 #[test]
2990 fn test_branches_parsing_containing_refs_with_missing_fields() {
2991 #[allow(clippy::octal_escapes)]
2992 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";
2993
2994 let branches = parse_branch_input(input).unwrap();
2995 assert_eq!(branches.len(), 2);
2996 assert_eq!(
2997 branches,
2998 vec![
2999 Branch {
3000 is_head: false,
3001 ref_name: "refs/heads/dev".into(),
3002 upstream: None,
3003 most_recent_commit: Some(CommitSummary {
3004 sha: "eb0cae33272689bd11030822939dd2701c52f81e".into(),
3005 subject: "Add feature".into(),
3006 commit_timestamp: 1762948725,
3007 author_name: SharedString::new("Zed"),
3008 has_parent: true,
3009 })
3010 },
3011 Branch {
3012 is_head: true,
3013 ref_name: "refs/heads/main".into(),
3014 upstream: None,
3015 most_recent_commit: Some(CommitSummary {
3016 sha: "895951d681e5561478c0acdd6905e8aacdfd2249".into(),
3017 subject: "Initial commit".into(),
3018 commit_timestamp: 1762948695,
3019 author_name: SharedString::new("Zed"),
3020 has_parent: false,
3021 })
3022 }
3023 ]
3024 )
3025 }
3026
3027 impl RealGitRepository {
3028 /// Force a Git garbage collection on the repository.
3029 fn gc(&self) -> BoxFuture<'_, Result<()>> {
3030 let working_directory = self.working_directory();
3031 let git_binary_path = self.any_git_binary_path.clone();
3032 let executor = self.executor.clone();
3033 self.executor
3034 .spawn(async move {
3035 let git_binary_path = git_binary_path.clone();
3036 let working_directory = working_directory?;
3037 let git = GitBinary::new(git_binary_path, working_directory, executor);
3038 git.run(&["gc", "--prune"]).await?;
3039 Ok(())
3040 })
3041 .boxed()
3042 }
3043 }
3044}