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