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