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