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