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