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