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