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