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::piped());
2695
2696 let mut child = command.spawn()?;
2697 let stdout = child.stdout.take().context("failed to get stdout")?;
2698 let stderr = child.stderr.take().context("failed to get stderr")?;
2699 let mut reader = BufReader::new(stdout);
2700
2701 let mut line_buffer = String::new();
2702 let mut lines: Vec<String> = Vec::with_capacity(GRAPH_CHUNK_SIZE);
2703
2704 loop {
2705 line_buffer.clear();
2706 let bytes_read = reader.read_line(&mut line_buffer).await?;
2707
2708 if bytes_read == 0 {
2709 if !lines.is_empty() {
2710 let commits = parse_initial_graph_output(lines.iter().map(|s| s.as_str()));
2711 if request_tx.send(commits).await.is_err() {
2712 log::warn!(
2713 "initial_graph_data: receiver dropped while sending commits"
2714 );
2715 }
2716 }
2717 break;
2718 }
2719
2720 let line = line_buffer.trim_end_matches('\n').to_string();
2721 lines.push(line);
2722
2723 if lines.len() >= GRAPH_CHUNK_SIZE {
2724 let commits = parse_initial_graph_output(lines.iter().map(|s| s.as_str()));
2725 if request_tx.send(commits).await.is_err() {
2726 log::warn!("initial_graph_data: receiver dropped while streaming commits");
2727 break;
2728 }
2729 lines.clear();
2730 }
2731 }
2732
2733 let status = child.status().await?;
2734 if !status.success() {
2735 let mut stderr_output = String::new();
2736 BufReader::new(stderr)
2737 .read_to_string(&mut stderr_output)
2738 .await
2739 .log_err();
2740
2741 if stderr_output.is_empty() {
2742 anyhow::bail!("git log command failed with {}", status);
2743 } else {
2744 anyhow::bail!("git log command failed with {}: {}", status, stderr_output);
2745 }
2746 }
2747 Ok(())
2748 }
2749 .boxed()
2750 }
2751
2752 fn search_commits(
2753 &self,
2754 log_source: LogSource,
2755 search_args: SearchCommitArgs,
2756 request_tx: Sender<Oid>,
2757 ) -> BoxFuture<'_, Result<()>> {
2758 let git_binary = self.git_binary();
2759
2760 async move {
2761 let git = git_binary?;
2762
2763 let mut args = vec!["log", SEARCH_COMMIT_FORMAT, log_source.get_arg()?];
2764
2765 args.push("--fixed-strings");
2766
2767 if !search_args.case_sensitive {
2768 args.push("--regexp-ignore-case");
2769 }
2770
2771 args.push("--grep");
2772 args.push(search_args.query.as_str());
2773
2774 let mut command = git.build_command(&args);
2775 command.stdout(Stdio::piped());
2776 command.stderr(Stdio::null());
2777
2778 let mut child = command.spawn()?;
2779 let stdout = child.stdout.take().context("failed to get stdout")?;
2780 let mut reader = BufReader::new(stdout);
2781
2782 let mut line_buffer = String::new();
2783
2784 loop {
2785 line_buffer.clear();
2786 let bytes_read = reader.read_line(&mut line_buffer).await?;
2787
2788 if bytes_read == 0 {
2789 break;
2790 }
2791
2792 let sha = line_buffer.trim_end_matches('\n');
2793
2794 if let Ok(oid) = Oid::from_str(sha)
2795 && request_tx.send(oid).await.is_err()
2796 {
2797 break;
2798 }
2799 }
2800
2801 child.status().await?;
2802 Ok(())
2803 }
2804 .boxed()
2805 }
2806
2807 fn commit_data_reader(&self) -> Result<CommitDataReader> {
2808 let git_binary = self.git_binary()?;
2809
2810 let (request_tx, request_rx) = smol::channel::bounded::<CommitDataRequest>(64);
2811
2812 let task = self.executor.spawn(async move {
2813 if let Err(error) = run_commit_data_reader(git_binary, request_rx).await {
2814 log::error!("commit data reader failed: {error:?}");
2815 }
2816 });
2817
2818 Ok(CommitDataReader {
2819 request_tx,
2820 _task: task,
2821 })
2822 }
2823
2824 fn set_trusted(&self, trusted: bool) {
2825 self.is_trusted
2826 .store(trusted, std::sync::atomic::Ordering::Release);
2827 }
2828
2829 fn is_trusted(&self) -> bool {
2830 self.is_trusted.load(std::sync::atomic::Ordering::Acquire)
2831 }
2832}
2833
2834async fn run_commit_data_reader(
2835 git: GitBinary,
2836 request_rx: smol::channel::Receiver<CommitDataRequest>,
2837) -> Result<()> {
2838 let mut process = git
2839 .build_command(&["cat-file", "--batch"])
2840 .stdin(Stdio::piped())
2841 .stdout(Stdio::piped())
2842 .stderr(Stdio::piped())
2843 .spawn()
2844 .context("starting git cat-file --batch process")?;
2845
2846 let mut stdin = BufWriter::new(process.stdin.take().context("no stdin")?);
2847 let mut stdout = BufReader::new(process.stdout.take().context("no stdout")?);
2848
2849 const MAX_BATCH_SIZE: usize = 64;
2850
2851 while let Ok(first_request) = request_rx.recv().await {
2852 let mut pending_requests = vec![first_request];
2853
2854 while pending_requests.len() < MAX_BATCH_SIZE {
2855 match request_rx.try_recv() {
2856 Ok(request) => pending_requests.push(request),
2857 Err(_) => break,
2858 }
2859 }
2860
2861 for request in &pending_requests {
2862 stdin.write_all(request.sha.to_string().as_bytes()).await?;
2863 stdin.write_all(b"\n").await?;
2864 }
2865 stdin.flush().await?;
2866
2867 for request in pending_requests {
2868 let result = read_single_commit_response(&mut stdout, &request.sha).await;
2869 request.response_tx.send(result).ok();
2870 }
2871 }
2872
2873 drop(stdin);
2874 process.kill().ok();
2875
2876 Ok(())
2877}
2878
2879async fn read_single_commit_response<R: smol::io::AsyncBufRead + Unpin>(
2880 stdout: &mut R,
2881 sha: &Oid,
2882) -> Result<GraphCommitData> {
2883 let mut header_bytes = Vec::new();
2884 stdout.read_until(b'\n', &mut header_bytes).await?;
2885 let header_line = String::from_utf8_lossy(&header_bytes);
2886
2887 let parts: Vec<&str> = header_line.trim().split(' ').collect();
2888 if parts.len() < 3 {
2889 bail!("invalid cat-file header: {header_line}");
2890 }
2891
2892 let object_type = parts[1];
2893 if object_type == "missing" {
2894 bail!("object not found: {}", sha);
2895 }
2896
2897 if object_type != "commit" {
2898 bail!("expected commit object, got {object_type}");
2899 }
2900
2901 let size: usize = parts[2]
2902 .parse()
2903 .with_context(|| format!("invalid object size: {}", parts[2]))?;
2904
2905 let mut content = vec![0u8; size];
2906 stdout.read_exact(&mut content).await?;
2907
2908 let mut newline = [0u8; 1];
2909 stdout.read_exact(&mut newline).await?;
2910
2911 let content_str = String::from_utf8_lossy(&content);
2912 parse_cat_file_commit(*sha, &content_str)
2913 .ok_or_else(|| anyhow!("failed to parse commit {}", sha))
2914}
2915
2916fn parse_initial_graph_output<'a>(
2917 lines: impl Iterator<Item = &'a str>,
2918) -> Vec<Arc<InitialGraphCommitData>> {
2919 lines
2920 .filter(|line| !line.is_empty())
2921 .filter_map(|line| {
2922 // Format: "SHA\x00PARENT1 PARENT2...\x00REF1, REF2, ..."
2923 let mut parts = line.split('\x00');
2924
2925 let sha = Oid::from_str(parts.next()?).ok()?;
2926 let parents_str = parts.next()?;
2927 let parents = parents_str
2928 .split_whitespace()
2929 .filter_map(|p| Oid::from_str(p).ok())
2930 .collect();
2931
2932 let ref_names_str = parts.next().unwrap_or("");
2933 let ref_names = if ref_names_str.is_empty() {
2934 Vec::new()
2935 } else {
2936 ref_names_str
2937 .split(", ")
2938 .map(|s| SharedString::from(s.to_string()))
2939 .collect()
2940 };
2941
2942 Some(Arc::new(InitialGraphCommitData {
2943 sha,
2944 parents,
2945 ref_names,
2946 }))
2947 })
2948 .collect()
2949}
2950
2951fn git_status_args(path_prefixes: &[RepoPath]) -> Vec<OsString> {
2952 let mut args = vec![
2953 OsString::from("status"),
2954 OsString::from("--porcelain=v1"),
2955 OsString::from("--untracked-files=all"),
2956 OsString::from("--no-renames"),
2957 OsString::from("-z"),
2958 ];
2959 args.extend(path_prefixes.iter().map(|path_prefix| {
2960 if path_prefix.is_empty() {
2961 Path::new(".").into()
2962 } else {
2963 path_prefix.as_std_path().into()
2964 }
2965 }));
2966 args
2967}
2968
2969/// Temporarily git-ignore commonly ignored files and files over 2MB
2970async fn exclude_files(git: &GitBinary) -> Result<GitExcludeOverride> {
2971 const MAX_SIZE: u64 = 2 * 1024 * 1024; // 2 MB
2972 let mut excludes = git.with_exclude_overrides().await?;
2973 excludes
2974 .add_excludes(include_str!("./checkpoint.gitignore"))
2975 .await?;
2976
2977 let working_directory = git.working_directory.clone();
2978 let untracked_files = git.list_untracked_files().await?;
2979 let excluded_paths = untracked_files.into_iter().map(|path| {
2980 let working_directory = working_directory.clone();
2981 smol::spawn(async move {
2982 let full_path = working_directory.join(path.clone());
2983 match smol::fs::metadata(&full_path).await {
2984 Ok(metadata) if metadata.is_file() && metadata.len() >= MAX_SIZE => {
2985 Some(PathBuf::from("/").join(path.clone()))
2986 }
2987 _ => None,
2988 }
2989 })
2990 });
2991
2992 let excluded_paths = futures::future::join_all(excluded_paths).await;
2993 let excluded_paths = excluded_paths.into_iter().flatten().collect::<Vec<_>>();
2994
2995 if !excluded_paths.is_empty() {
2996 let exclude_patterns = excluded_paths
2997 .into_iter()
2998 .map(|path| path.to_string_lossy().into_owned())
2999 .collect::<Vec<_>>()
3000 .join("\n");
3001 excludes.add_excludes(&exclude_patterns).await?;
3002 }
3003
3004 Ok(excludes)
3005}
3006
3007pub(crate) struct GitBinary {
3008 git_binary_path: PathBuf,
3009 working_directory: PathBuf,
3010 git_directory: PathBuf,
3011 executor: BackgroundExecutor,
3012 index_file_path: Option<PathBuf>,
3013 envs: HashMap<String, String>,
3014 is_trusted: bool,
3015}
3016
3017impl GitBinary {
3018 pub(crate) fn new(
3019 git_binary_path: PathBuf,
3020 working_directory: PathBuf,
3021 git_directory: PathBuf,
3022 executor: BackgroundExecutor,
3023 is_trusted: bool,
3024 ) -> Self {
3025 Self {
3026 git_binary_path,
3027 working_directory,
3028 git_directory,
3029 executor,
3030 index_file_path: None,
3031 envs: HashMap::default(),
3032 is_trusted,
3033 }
3034 }
3035
3036 async fn list_untracked_files(&self) -> Result<Vec<PathBuf>> {
3037 let status_output = self
3038 .run(&["status", "--porcelain=v1", "--untracked-files=all", "-z"])
3039 .await?;
3040
3041 let paths = status_output
3042 .split('\0')
3043 .filter(|entry| entry.len() >= 3 && entry.starts_with("?? "))
3044 .map(|entry| PathBuf::from(&entry[3..]))
3045 .collect::<Vec<_>>();
3046 Ok(paths)
3047 }
3048
3049 fn envs(mut self, envs: HashMap<String, String>) -> Self {
3050 self.envs = envs;
3051 self
3052 }
3053
3054 pub async fn with_temp_index<R>(
3055 &mut self,
3056 f: impl AsyncFnOnce(&Self) -> Result<R>,
3057 ) -> Result<R> {
3058 let index_file_path = self.path_for_index_id(Uuid::new_v4());
3059
3060 let delete_temp_index = util::defer({
3061 let index_file_path = index_file_path.clone();
3062 let executor = self.executor.clone();
3063 move || {
3064 executor
3065 .spawn(async move {
3066 smol::fs::remove_file(index_file_path).await.log_err();
3067 })
3068 .detach();
3069 }
3070 });
3071
3072 // Copy the default index file so that Git doesn't have to rebuild the
3073 // whole index from scratch. This might fail if this is an empty repository.
3074 smol::fs::copy(self.git_directory.join("index"), &index_file_path)
3075 .await
3076 .ok();
3077
3078 self.index_file_path = Some(index_file_path.clone());
3079 let result = f(self).await;
3080 self.index_file_path = None;
3081 let result = result?;
3082
3083 smol::fs::remove_file(index_file_path).await.ok();
3084 delete_temp_index.abort();
3085
3086 Ok(result)
3087 }
3088
3089 pub async fn with_exclude_overrides(&self) -> Result<GitExcludeOverride> {
3090 let path = self.git_directory.join("info").join("exclude");
3091
3092 GitExcludeOverride::new(path).await
3093 }
3094
3095 fn path_for_index_id(&self, id: Uuid) -> PathBuf {
3096 self.git_directory.join(format!("index-{}.tmp", id))
3097 }
3098
3099 pub async fn run<S>(&self, args: &[S]) -> Result<String>
3100 where
3101 S: AsRef<OsStr>,
3102 {
3103 let mut stdout = self.run_raw(args).await?;
3104 if stdout.chars().last() == Some('\n') {
3105 stdout.pop();
3106 }
3107 Ok(stdout)
3108 }
3109
3110 /// Returns the result of the command without trimming the trailing newline.
3111 pub async fn run_raw<S>(&self, args: &[S]) -> Result<String>
3112 where
3113 S: AsRef<OsStr>,
3114 {
3115 let mut command = self.build_command(args);
3116 let output = command.output().await?;
3117 anyhow::ensure!(
3118 output.status.success(),
3119 GitBinaryCommandError {
3120 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
3121 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3122 status: output.status,
3123 }
3124 );
3125 Ok(String::from_utf8(output.stdout)?)
3126 }
3127
3128 #[allow(clippy::disallowed_methods)]
3129 pub(crate) fn build_command<S>(&self, args: &[S]) -> util::command::Command
3130 where
3131 S: AsRef<OsStr>,
3132 {
3133 let mut command = new_command(&self.git_binary_path);
3134 command.current_dir(&self.working_directory);
3135 command.args(["-c", "core.fsmonitor=false"]);
3136 command.arg("--no-optional-locks");
3137 command.arg("--no-pager");
3138
3139 if !self.is_trusted {
3140 command.args(["-c", "core.hooksPath=/dev/null"]);
3141 command.args(["-c", "core.sshCommand=ssh"]);
3142 command.args(["-c", "credential.helper="]);
3143 command.args(["-c", "protocol.ext.allow=never"]);
3144 command.args(["-c", "diff.external="]);
3145 }
3146 command.args(args);
3147
3148 // If the `diff` command is being used, we'll want to add the
3149 // `--no-ext-diff` flag when working on an untrusted repository,
3150 // preventing any external diff programs from being invoked.
3151 if !self.is_trusted && args.iter().any(|arg| arg.as_ref() == "diff") {
3152 command.arg("--no-ext-diff");
3153 }
3154
3155 if let Some(index_file_path) = self.index_file_path.as_ref() {
3156 command.env("GIT_INDEX_FILE", index_file_path);
3157 }
3158 command.envs(&self.envs);
3159 command
3160 }
3161}
3162
3163#[derive(Error, Debug)]
3164#[error("Git command failed:\n{stdout}{stderr}\n")]
3165struct GitBinaryCommandError {
3166 stdout: String,
3167 stderr: String,
3168 status: ExitStatus,
3169}
3170
3171async fn run_git_command(
3172 env: Arc<HashMap<String, String>>,
3173 ask_pass: AskPassDelegate,
3174 mut command: util::command::Command,
3175 executor: BackgroundExecutor,
3176) -> Result<RemoteCommandOutput> {
3177 if env.contains_key("GIT_ASKPASS") {
3178 let git_process = command.spawn()?;
3179 let output = git_process.output().await?;
3180 anyhow::ensure!(
3181 output.status.success(),
3182 "{}",
3183 String::from_utf8_lossy(&output.stderr)
3184 );
3185 Ok(RemoteCommandOutput {
3186 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
3187 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3188 })
3189 } else {
3190 let ask_pass = AskPassSession::new(executor, ask_pass).await?;
3191 command
3192 .env("GIT_ASKPASS", ask_pass.script_path())
3193 .env("SSH_ASKPASS", ask_pass.script_path())
3194 .env("SSH_ASKPASS_REQUIRE", "force");
3195 let git_process = command.spawn()?;
3196
3197 run_askpass_command(ask_pass, git_process).await
3198 }
3199}
3200
3201async fn run_askpass_command(
3202 mut ask_pass: AskPassSession,
3203 git_process: util::command::Child,
3204) -> anyhow::Result<RemoteCommandOutput> {
3205 select_biased! {
3206 result = ask_pass.run().fuse() => {
3207 match result {
3208 AskPassResult::CancelledByUser => {
3209 Err(anyhow!(REMOTE_CANCELLED_BY_USER))?
3210 }
3211 AskPassResult::Timedout => {
3212 Err(anyhow!("Connecting to host timed out"))?
3213 }
3214 }
3215 }
3216 output = git_process.output().fuse() => {
3217 let output = output?;
3218 anyhow::ensure!(
3219 output.status.success(),
3220 "{}",
3221 String::from_utf8_lossy(&output.stderr)
3222 );
3223 Ok(RemoteCommandOutput {
3224 stdout: String::from_utf8_lossy(&output.stdout).to_string(),
3225 stderr: String::from_utf8_lossy(&output.stderr).to_string(),
3226 })
3227 }
3228 }
3229}
3230
3231#[derive(Clone, Ord, Hash, PartialOrd, Eq, PartialEq)]
3232pub struct RepoPath(Arc<RelPath>);
3233
3234impl std::fmt::Debug for RepoPath {
3235 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3236 self.0.fmt(f)
3237 }
3238}
3239
3240impl RepoPath {
3241 pub fn new<S: AsRef<str> + ?Sized>(s: &S) -> Result<Self> {
3242 let rel_path = RelPath::unix(s.as_ref())?;
3243 Ok(Self::from_rel_path(rel_path))
3244 }
3245
3246 pub fn from_std_path(path: &Path, path_style: PathStyle) -> Result<Self> {
3247 let rel_path = RelPath::new(path, path_style)?;
3248 Ok(Self::from_rel_path(&rel_path))
3249 }
3250
3251 pub fn from_proto(proto: &str) -> Result<Self> {
3252 let rel_path = RelPath::from_proto(proto)?;
3253 Ok(Self(rel_path))
3254 }
3255
3256 pub fn from_rel_path(path: &RelPath) -> RepoPath {
3257 Self(Arc::from(path))
3258 }
3259
3260 pub fn as_std_path(&self) -> &Path {
3261 // git2 does not like empty paths and our RelPath infra turns `.` into ``
3262 // so undo that here
3263 if self.is_empty() {
3264 Path::new(".")
3265 } else {
3266 self.0.as_std_path()
3267 }
3268 }
3269}
3270
3271#[cfg(any(test, feature = "test-support"))]
3272pub fn repo_path<S: AsRef<str> + ?Sized>(s: &S) -> RepoPath {
3273 RepoPath(RelPath::unix(s.as_ref()).unwrap().into())
3274}
3275
3276impl AsRef<Arc<RelPath>> for RepoPath {
3277 fn as_ref(&self) -> &Arc<RelPath> {
3278 &self.0
3279 }
3280}
3281
3282impl std::ops::Deref for RepoPath {
3283 type Target = RelPath;
3284
3285 fn deref(&self) -> &Self::Target {
3286 &self.0
3287 }
3288}
3289
3290#[derive(Debug)]
3291pub struct RepoPathDescendants<'a>(pub &'a RepoPath);
3292
3293impl MapSeekTarget<RepoPath> for RepoPathDescendants<'_> {
3294 fn cmp_cursor(&self, key: &RepoPath) -> Ordering {
3295 if key.starts_with(self.0) {
3296 Ordering::Greater
3297 } else {
3298 self.0.cmp(key)
3299 }
3300 }
3301}
3302
3303fn parse_branch_input(input: &str) -> Result<Vec<Branch>> {
3304 let mut branches = Vec::new();
3305 for line in input.split('\n') {
3306 if line.is_empty() {
3307 continue;
3308 }
3309 let mut fields = line.split('\x00');
3310 let Some(head) = fields.next() else {
3311 continue;
3312 };
3313 let Some(head_sha) = fields.next().map(|f| f.to_string().into()) else {
3314 continue;
3315 };
3316 let Some(parent_sha) = fields.next().map(|f| f.to_string()) else {
3317 continue;
3318 };
3319 let Some(ref_name) = fields.next().map(|f| f.to_string().into()) else {
3320 continue;
3321 };
3322 let Some(upstream_name) = fields.next().map(|f| f.to_string()) else {
3323 continue;
3324 };
3325 let Some(upstream_tracking) = fields.next().and_then(|f| parse_upstream_track(f).ok())
3326 else {
3327 continue;
3328 };
3329 let Some(commiterdate) = fields.next().and_then(|f| f.parse::<i64>().ok()) else {
3330 continue;
3331 };
3332 let Some(author_name) = fields.next().map(|f| f.to_string().into()) else {
3333 continue;
3334 };
3335 let Some(subject) = fields.next().map(|f| f.to_string().into()) else {
3336 continue;
3337 };
3338
3339 branches.push(Branch {
3340 is_head: head == "*",
3341 ref_name,
3342 most_recent_commit: Some(CommitSummary {
3343 sha: head_sha,
3344 subject,
3345 commit_timestamp: commiterdate,
3346 author_name: author_name,
3347 has_parent: !parent_sha.is_empty(),
3348 }),
3349 upstream: if upstream_name.is_empty() {
3350 None
3351 } else {
3352 Some(Upstream {
3353 ref_name: upstream_name.into(),
3354 tracking: upstream_tracking,
3355 })
3356 },
3357 })
3358 }
3359
3360 Ok(branches)
3361}
3362
3363fn parse_upstream_track(upstream_track: &str) -> Result<UpstreamTracking> {
3364 if upstream_track.is_empty() {
3365 return Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
3366 ahead: 0,
3367 behind: 0,
3368 }));
3369 }
3370
3371 let upstream_track = upstream_track.strip_prefix("[").context("missing [")?;
3372 let upstream_track = upstream_track.strip_suffix("]").context("missing [")?;
3373 let mut ahead: u32 = 0;
3374 let mut behind: u32 = 0;
3375 for component in upstream_track.split(", ") {
3376 if component == "gone" {
3377 return Ok(UpstreamTracking::Gone);
3378 }
3379 if let Some(ahead_num) = component.strip_prefix("ahead ") {
3380 ahead = ahead_num.parse::<u32>()?;
3381 }
3382 if let Some(behind_num) = component.strip_prefix("behind ") {
3383 behind = behind_num.parse::<u32>()?;
3384 }
3385 }
3386 Ok(UpstreamTracking::Tracked(UpstreamTrackingStatus {
3387 ahead,
3388 behind,
3389 }))
3390}
3391
3392fn checkpoint_author_envs() -> HashMap<String, String> {
3393 HashMap::from_iter([
3394 ("GIT_AUTHOR_NAME".to_string(), "Zed".to_string()),
3395 ("GIT_AUTHOR_EMAIL".to_string(), "hi@zed.dev".to_string()),
3396 ("GIT_COMMITTER_NAME".to_string(), "Zed".to_string()),
3397 ("GIT_COMMITTER_EMAIL".to_string(), "hi@zed.dev".to_string()),
3398 ])
3399}
3400
3401#[cfg(test)]
3402mod tests {
3403 use std::fs;
3404
3405 use super::*;
3406 use gpui::TestAppContext;
3407
3408 fn disable_git_global_config() {
3409 unsafe {
3410 std::env::set_var("GIT_CONFIG_GLOBAL", "");
3411 std::env::set_var("GIT_CONFIG_SYSTEM", "");
3412 }
3413 }
3414
3415 #[gpui::test]
3416 async fn test_build_command_untrusted_includes_both_safety_args(cx: &mut TestAppContext) {
3417 cx.executor().allow_parking();
3418 let dir = tempfile::tempdir().unwrap();
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(&["version"])
3428 .output()
3429 .await
3430 .expect("git version should succeed");
3431 assert!(output.status.success());
3432
3433 let git = GitBinary::new(
3434 PathBuf::from("git"),
3435 dir.path().to_path_buf(),
3436 dir.path().join(".git"),
3437 cx.executor(),
3438 false,
3439 );
3440 let output = git
3441 .build_command(&["config", "--get", "core.fsmonitor"])
3442 .output()
3443 .await
3444 .expect("git config should run");
3445 let stdout = String::from_utf8_lossy(&output.stdout);
3446 assert_eq!(
3447 stdout.trim(),
3448 "false",
3449 "fsmonitor should be disabled for untrusted repos"
3450 );
3451
3452 git2::Repository::init(dir.path()).unwrap();
3453 let git = GitBinary::new(
3454 PathBuf::from("git"),
3455 dir.path().to_path_buf(),
3456 dir.path().join(".git"),
3457 cx.executor(),
3458 false,
3459 );
3460 let output = git
3461 .build_command(&["config", "--get", "core.hooksPath"])
3462 .output()
3463 .await
3464 .expect("git config should run");
3465 let stdout = String::from_utf8_lossy(&output.stdout);
3466 assert_eq!(
3467 stdout.trim(),
3468 "/dev/null",
3469 "hooksPath should be /dev/null for untrusted repos"
3470 );
3471 }
3472
3473 #[gpui::test]
3474 async fn test_build_command_trusted_only_disables_fsmonitor(cx: &mut TestAppContext) {
3475 cx.executor().allow_parking();
3476 let dir = tempfile::tempdir().unwrap();
3477 git2::Repository::init(dir.path()).unwrap();
3478
3479 let git = GitBinary::new(
3480 PathBuf::from("git"),
3481 dir.path().to_path_buf(),
3482 dir.path().join(".git"),
3483 cx.executor(),
3484 true,
3485 );
3486 let output = git
3487 .build_command(&["config", "--get", "core.fsmonitor"])
3488 .output()
3489 .await
3490 .expect("git config should run");
3491 let stdout = String::from_utf8_lossy(&output.stdout);
3492 assert_eq!(
3493 stdout.trim(),
3494 "false",
3495 "fsmonitor should be disabled even for trusted repos"
3496 );
3497
3498 let git = GitBinary::new(
3499 PathBuf::from("git"),
3500 dir.path().to_path_buf(),
3501 dir.path().join(".git"),
3502 cx.executor(),
3503 true,
3504 );
3505 let output = git
3506 .build_command(&["config", "--get", "core.hooksPath"])
3507 .output()
3508 .await
3509 .expect("git config should run");
3510 assert!(
3511 !output.status.success(),
3512 "hooksPath should NOT be overridden for trusted repos"
3513 );
3514 }
3515
3516 #[gpui::test]
3517 async fn test_path_for_index_id_uses_real_git_directory(cx: &mut TestAppContext) {
3518 cx.executor().allow_parking();
3519 let working_directory = PathBuf::from("/code/worktree");
3520 let git_directory = PathBuf::from("/code/repo/.git/modules/worktree");
3521 let git = GitBinary::new(
3522 PathBuf::from("git"),
3523 working_directory,
3524 git_directory.clone(),
3525 cx.executor(),
3526 false,
3527 );
3528
3529 let path = git.path_for_index_id(Uuid::nil());
3530
3531 assert_eq!(
3532 path,
3533 git_directory.join(format!("index-{}.tmp", Uuid::nil()))
3534 );
3535 }
3536
3537 #[gpui::test]
3538 async fn test_checkpoint_basic(cx: &mut TestAppContext) {
3539 disable_git_global_config();
3540
3541 cx.executor().allow_parking();
3542
3543 let repo_dir = tempfile::tempdir().unwrap();
3544
3545 git2::Repository::init(repo_dir.path()).unwrap();
3546 let file_path = repo_dir.path().join("file");
3547 smol::fs::write(&file_path, "initial").await.unwrap();
3548
3549 let repo = RealGitRepository::new(
3550 &repo_dir.path().join(".git"),
3551 None,
3552 Some("git".into()),
3553 cx.executor(),
3554 )
3555 .unwrap();
3556
3557 repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
3558 .await
3559 .unwrap();
3560 repo.commit(
3561 "Initial commit".into(),
3562 None,
3563 CommitOptions::default(),
3564 AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3565 Arc::new(checkpoint_author_envs()),
3566 )
3567 .await
3568 .unwrap();
3569
3570 smol::fs::write(&file_path, "modified before checkpoint")
3571 .await
3572 .unwrap();
3573 smol::fs::write(repo_dir.path().join("new_file_before_checkpoint"), "1")
3574 .await
3575 .unwrap();
3576 let checkpoint = repo.checkpoint().await.unwrap();
3577
3578 // Ensure the user can't see any branches after creating a checkpoint.
3579 assert_eq!(repo.branches().await.unwrap().len(), 1);
3580
3581 smol::fs::write(&file_path, "modified after checkpoint")
3582 .await
3583 .unwrap();
3584 repo.stage_paths(vec![repo_path("file")], Arc::new(HashMap::default()))
3585 .await
3586 .unwrap();
3587 repo.commit(
3588 "Commit after checkpoint".into(),
3589 None,
3590 CommitOptions::default(),
3591 AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3592 Arc::new(checkpoint_author_envs()),
3593 )
3594 .await
3595 .unwrap();
3596
3597 smol::fs::remove_file(repo_dir.path().join("new_file_before_checkpoint"))
3598 .await
3599 .unwrap();
3600 smol::fs::write(repo_dir.path().join("new_file_after_checkpoint"), "2")
3601 .await
3602 .unwrap();
3603
3604 // Ensure checkpoint stays alive even after a Git GC.
3605 repo.gc().await.unwrap();
3606 repo.restore_checkpoint(checkpoint.clone()).await.unwrap();
3607
3608 assert_eq!(
3609 smol::fs::read_to_string(&file_path).await.unwrap(),
3610 "modified before checkpoint"
3611 );
3612 assert_eq!(
3613 smol::fs::read_to_string(repo_dir.path().join("new_file_before_checkpoint"))
3614 .await
3615 .unwrap(),
3616 "1"
3617 );
3618 // See TODO above
3619 // assert_eq!(
3620 // smol::fs::read_to_string(repo_dir.path().join("new_file_after_checkpoint"))
3621 // .await
3622 // .ok(),
3623 // None
3624 // );
3625 }
3626
3627 #[gpui::test]
3628 async fn test_checkpoint_empty_repo(cx: &mut TestAppContext) {
3629 disable_git_global_config();
3630
3631 cx.executor().allow_parking();
3632
3633 let repo_dir = tempfile::tempdir().unwrap();
3634 git2::Repository::init(repo_dir.path()).unwrap();
3635 let repo = RealGitRepository::new(
3636 &repo_dir.path().join(".git"),
3637 None,
3638 Some("git".into()),
3639 cx.executor(),
3640 )
3641 .unwrap();
3642
3643 smol::fs::write(repo_dir.path().join("foo"), "foo")
3644 .await
3645 .unwrap();
3646 let checkpoint_sha = repo.checkpoint().await.unwrap();
3647
3648 // Ensure the user can't see any branches after creating a checkpoint.
3649 assert_eq!(repo.branches().await.unwrap().len(), 1);
3650
3651 smol::fs::write(repo_dir.path().join("foo"), "bar")
3652 .await
3653 .unwrap();
3654 smol::fs::write(repo_dir.path().join("baz"), "qux")
3655 .await
3656 .unwrap();
3657 repo.restore_checkpoint(checkpoint_sha).await.unwrap();
3658 assert_eq!(
3659 smol::fs::read_to_string(repo_dir.path().join("foo"))
3660 .await
3661 .unwrap(),
3662 "foo"
3663 );
3664 // See TODOs above
3665 // assert_eq!(
3666 // smol::fs::read_to_string(repo_dir.path().join("baz"))
3667 // .await
3668 // .ok(),
3669 // None
3670 // );
3671 }
3672
3673 #[gpui::test]
3674 async fn test_compare_checkpoints(cx: &mut TestAppContext) {
3675 disable_git_global_config();
3676
3677 cx.executor().allow_parking();
3678
3679 let repo_dir = tempfile::tempdir().unwrap();
3680 git2::Repository::init(repo_dir.path()).unwrap();
3681 let repo = RealGitRepository::new(
3682 &repo_dir.path().join(".git"),
3683 None,
3684 Some("git".into()),
3685 cx.executor(),
3686 )
3687 .unwrap();
3688
3689 smol::fs::write(repo_dir.path().join("file1"), "content1")
3690 .await
3691 .unwrap();
3692 let checkpoint1 = repo.checkpoint().await.unwrap();
3693
3694 smol::fs::write(repo_dir.path().join("file2"), "content2")
3695 .await
3696 .unwrap();
3697 let checkpoint2 = repo.checkpoint().await.unwrap();
3698
3699 assert!(
3700 !repo
3701 .compare_checkpoints(checkpoint1, checkpoint2.clone())
3702 .await
3703 .unwrap()
3704 );
3705
3706 let checkpoint3 = repo.checkpoint().await.unwrap();
3707 assert!(
3708 repo.compare_checkpoints(checkpoint2, checkpoint3)
3709 .await
3710 .unwrap()
3711 );
3712 }
3713
3714 #[gpui::test]
3715 async fn test_checkpoint_exclude_binary_files(cx: &mut TestAppContext) {
3716 disable_git_global_config();
3717
3718 cx.executor().allow_parking();
3719
3720 let repo_dir = tempfile::tempdir().unwrap();
3721 let text_path = repo_dir.path().join("main.rs");
3722 let bin_path = repo_dir.path().join("binary.o");
3723
3724 git2::Repository::init(repo_dir.path()).unwrap();
3725
3726 smol::fs::write(&text_path, "fn main() {}").await.unwrap();
3727
3728 smol::fs::write(&bin_path, "some binary file here")
3729 .await
3730 .unwrap();
3731
3732 let repo = RealGitRepository::new(
3733 &repo_dir.path().join(".git"),
3734 None,
3735 Some("git".into()),
3736 cx.executor(),
3737 )
3738 .unwrap();
3739
3740 // initial commit
3741 repo.stage_paths(vec![repo_path("main.rs")], Arc::new(HashMap::default()))
3742 .await
3743 .unwrap();
3744 repo.commit(
3745 "Initial commit".into(),
3746 None,
3747 CommitOptions::default(),
3748 AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
3749 Arc::new(checkpoint_author_envs()),
3750 )
3751 .await
3752 .unwrap();
3753
3754 let checkpoint = repo.checkpoint().await.unwrap();
3755
3756 smol::fs::write(&text_path, "fn main() { println!(\"Modified\"); }")
3757 .await
3758 .unwrap();
3759 smol::fs::write(&bin_path, "Modified binary file")
3760 .await
3761 .unwrap();
3762
3763 repo.restore_checkpoint(checkpoint).await.unwrap();
3764
3765 // Text files should be restored to checkpoint state,
3766 // but binaries should not (they aren't tracked)
3767 assert_eq!(
3768 smol::fs::read_to_string(&text_path).await.unwrap(),
3769 "fn main() {}"
3770 );
3771
3772 assert_eq!(
3773 smol::fs::read_to_string(&bin_path).await.unwrap(),
3774 "Modified binary file"
3775 );
3776 }
3777
3778 #[test]
3779 fn test_branches_parsing() {
3780 // suppress "help: octal escapes are not supported, `\0` is always null"
3781 #[allow(clippy::octal_escapes)]
3782 let input = "*\0060964da10574cd9bf06463a53bf6e0769c5c45e\0\0refs/heads/zed-patches\0refs/remotes/origin/zed-patches\0\01733187470\0John Doe\0generated protobuf\n";
3783 assert_eq!(
3784 parse_branch_input(input).unwrap(),
3785 vec![Branch {
3786 is_head: true,
3787 ref_name: "refs/heads/zed-patches".into(),
3788 upstream: Some(Upstream {
3789 ref_name: "refs/remotes/origin/zed-patches".into(),
3790 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3791 ahead: 0,
3792 behind: 0
3793 })
3794 }),
3795 most_recent_commit: Some(CommitSummary {
3796 sha: "060964da10574cd9bf06463a53bf6e0769c5c45e".into(),
3797 subject: "generated protobuf".into(),
3798 commit_timestamp: 1733187470,
3799 author_name: SharedString::new_static("John Doe"),
3800 has_parent: false,
3801 })
3802 }]
3803 )
3804 }
3805
3806 #[test]
3807 fn test_branches_parsing_containing_refs_with_missing_fields() {
3808 #[allow(clippy::octal_escapes)]
3809 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";
3810
3811 let branches = parse_branch_input(input).unwrap();
3812 assert_eq!(branches.len(), 2);
3813 assert_eq!(
3814 branches,
3815 vec![
3816 Branch {
3817 is_head: false,
3818 ref_name: "refs/heads/dev".into(),
3819 upstream: None,
3820 most_recent_commit: Some(CommitSummary {
3821 sha: "eb0cae33272689bd11030822939dd2701c52f81e".into(),
3822 subject: "Add feature".into(),
3823 commit_timestamp: 1762948725,
3824 author_name: SharedString::new_static("Zed"),
3825 has_parent: true,
3826 })
3827 },
3828 Branch {
3829 is_head: true,
3830 ref_name: "refs/heads/main".into(),
3831 upstream: None,
3832 most_recent_commit: Some(CommitSummary {
3833 sha: "895951d681e5561478c0acdd6905e8aacdfd2249".into(),
3834 subject: "Initial commit".into(),
3835 commit_timestamp: 1762948695,
3836 author_name: SharedString::new_static("Zed"),
3837 has_parent: false,
3838 })
3839 }
3840 ]
3841 )
3842 }
3843
3844 #[test]
3845 fn test_upstream_branch_name() {
3846 let upstream = Upstream {
3847 ref_name: "refs/remotes/origin/feature/branch".into(),
3848 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3849 ahead: 0,
3850 behind: 0,
3851 }),
3852 };
3853 assert_eq!(upstream.branch_name(), Some("feature/branch"));
3854
3855 let upstream = Upstream {
3856 ref_name: "refs/remotes/upstream/main".into(),
3857 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3858 ahead: 0,
3859 behind: 0,
3860 }),
3861 };
3862 assert_eq!(upstream.branch_name(), Some("main"));
3863
3864 let upstream = Upstream {
3865 ref_name: "refs/heads/local".into(),
3866 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3867 ahead: 0,
3868 behind: 0,
3869 }),
3870 };
3871 assert_eq!(upstream.branch_name(), None);
3872
3873 // Test case where upstream branch name differs from what might be the local branch name
3874 let upstream = Upstream {
3875 ref_name: "refs/remotes/origin/feature/git-pull-request".into(),
3876 tracking: UpstreamTracking::Tracked(UpstreamTrackingStatus {
3877 ahead: 0,
3878 behind: 0,
3879 }),
3880 };
3881 assert_eq!(upstream.branch_name(), Some("feature/git-pull-request"));
3882 }
3883
3884 #[test]
3885 fn test_parse_worktrees_from_str() {
3886 // Empty input
3887 let result = parse_worktrees_from_str("");
3888 assert!(result.is_empty());
3889
3890 // Single worktree (main)
3891 let input = "worktree /home/user/project\nHEAD abc123def\nbranch refs/heads/main\n\n";
3892 let result = parse_worktrees_from_str(input);
3893 assert_eq!(result.len(), 1);
3894 assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3895 assert_eq!(result[0].sha.as_ref(), "abc123def");
3896 assert_eq!(result[0].ref_name, Some("refs/heads/main".into()));
3897 assert!(result[0].is_main);
3898
3899 // Multiple worktrees
3900 let input = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n\n\
3901 worktree /home/user/project-wt\nHEAD def456\nbranch refs/heads/feature\n\n";
3902 let result = parse_worktrees_from_str(input);
3903 assert_eq!(result.len(), 2);
3904 assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3905 assert_eq!(result[0].ref_name, Some("refs/heads/main".into()));
3906 assert!(result[0].is_main);
3907 assert_eq!(result[1].path, PathBuf::from("/home/user/project-wt"));
3908 assert_eq!(result[1].ref_name, Some("refs/heads/feature".into()));
3909 assert!(!result[1].is_main);
3910
3911 // Detached HEAD entry (included with ref_name: None)
3912 let input = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n\n\
3913 worktree /home/user/detached\nHEAD def456\ndetached\n\n";
3914 let result = parse_worktrees_from_str(input);
3915 assert_eq!(result.len(), 2);
3916 assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3917 assert_eq!(result[0].ref_name, Some("refs/heads/main".into()));
3918 assert!(result[0].is_main);
3919 assert_eq!(result[1].path, PathBuf::from("/home/user/detached"));
3920 assert_eq!(result[1].ref_name, None);
3921 assert_eq!(result[1].sha.as_ref(), "def456");
3922 assert!(!result[1].is_main);
3923
3924 // Bare repo entry (included with ref_name: None)
3925 let input = "worktree /home/user/bare.git\nHEAD abc123\nbare\n\n\
3926 worktree /home/user/project\nHEAD def456\nbranch refs/heads/main\n\n";
3927 let result = parse_worktrees_from_str(input);
3928 assert_eq!(result.len(), 2);
3929 assert_eq!(result[0].path, PathBuf::from("/home/user/bare.git"));
3930 assert_eq!(result[0].ref_name, None);
3931 assert!(result[0].is_main);
3932 assert_eq!(result[1].path, PathBuf::from("/home/user/project"));
3933 assert_eq!(result[1].ref_name, Some("refs/heads/main".into()));
3934 assert!(!result[1].is_main);
3935
3936 // Extra porcelain lines (locked, prunable) should be ignored
3937 let input = "worktree /home/user/project\nHEAD abc123\nbranch refs/heads/main\n\n\
3938 worktree /home/user/locked-wt\nHEAD def456\nbranch refs/heads/locked-branch\nlocked\n\n\
3939 worktree /home/user/prunable-wt\nHEAD 789aaa\nbranch refs/heads/prunable-branch\nprunable\n\n";
3940 let result = parse_worktrees_from_str(input);
3941 assert_eq!(result.len(), 3);
3942 assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3943 assert_eq!(result[0].ref_name, Some("refs/heads/main".into()));
3944 assert!(result[0].is_main);
3945 assert_eq!(result[1].path, PathBuf::from("/home/user/locked-wt"));
3946 assert_eq!(result[1].ref_name, Some("refs/heads/locked-branch".into()));
3947 assert!(!result[1].is_main);
3948 assert_eq!(result[2].path, PathBuf::from("/home/user/prunable-wt"));
3949 assert_eq!(
3950 result[2].ref_name,
3951 Some("refs/heads/prunable-branch".into())
3952 );
3953 assert!(!result[2].is_main);
3954
3955 // Leading/trailing whitespace on lines should be tolerated
3956 let input =
3957 " worktree /home/user/project \n HEAD abc123 \n branch refs/heads/main \n\n";
3958 let result = parse_worktrees_from_str(input);
3959 assert_eq!(result.len(), 1);
3960 assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3961 assert_eq!(result[0].sha.as_ref(), "abc123");
3962 assert_eq!(result[0].ref_name, Some("refs/heads/main".into()));
3963 assert!(result[0].is_main);
3964
3965 // Windows-style line endings should be handled
3966 let input = "worktree /home/user/project\r\nHEAD abc123\r\nbranch refs/heads/main\r\n\r\n";
3967 let result = parse_worktrees_from_str(input);
3968 assert_eq!(result.len(), 1);
3969 assert_eq!(result[0].path, PathBuf::from("/home/user/project"));
3970 assert_eq!(result[0].sha.as_ref(), "abc123");
3971 assert_eq!(result[0].ref_name, Some("refs/heads/main".into()));
3972 assert!(result[0].is_main);
3973 }
3974
3975 #[gpui::test]
3976 async fn test_create_and_list_worktrees(cx: &mut TestAppContext) {
3977 disable_git_global_config();
3978 cx.executor().allow_parking();
3979
3980 let temp_dir = tempfile::tempdir().unwrap();
3981 let repo_dir = temp_dir.path().join("repo");
3982 let worktrees_dir = temp_dir.path().join("worktrees");
3983
3984 fs::create_dir_all(&repo_dir).unwrap();
3985 fs::create_dir_all(&worktrees_dir).unwrap();
3986
3987 git2::Repository::init(&repo_dir).unwrap();
3988
3989 let repo = RealGitRepository::new(
3990 &repo_dir.join(".git"),
3991 None,
3992 Some("git".into()),
3993 cx.executor(),
3994 )
3995 .unwrap();
3996
3997 // Create an initial commit (required for worktrees)
3998 smol::fs::write(repo_dir.join("file.txt"), "content")
3999 .await
4000 .unwrap();
4001 repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
4002 .await
4003 .unwrap();
4004 repo.commit(
4005 "Initial commit".into(),
4006 None,
4007 CommitOptions::default(),
4008 AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
4009 Arc::new(checkpoint_author_envs()),
4010 )
4011 .await
4012 .unwrap();
4013
4014 // List worktrees — should have just the main one
4015 let worktrees = repo.worktrees().await.unwrap();
4016 assert_eq!(worktrees.len(), 1);
4017 assert_eq!(
4018 worktrees[0].path.canonicalize().unwrap(),
4019 repo_dir.canonicalize().unwrap()
4020 );
4021
4022 let worktree_path = worktrees_dir.join("some-worktree");
4023
4024 // Create a new worktree
4025 repo.create_worktree(
4026 "test-branch".to_string(),
4027 worktree_path.clone(),
4028 Some("HEAD".to_string()),
4029 )
4030 .await
4031 .unwrap();
4032
4033 // List worktrees — should have two
4034 let worktrees = repo.worktrees().await.unwrap();
4035 assert_eq!(worktrees.len(), 2);
4036
4037 let new_worktree = worktrees
4038 .iter()
4039 .find(|w| w.display_name() == "test-branch")
4040 .expect("should find worktree with test-branch");
4041 assert_eq!(
4042 new_worktree.path.canonicalize().unwrap(),
4043 worktree_path.canonicalize().unwrap(),
4044 );
4045 }
4046
4047 #[gpui::test]
4048 async fn test_remove_worktree(cx: &mut TestAppContext) {
4049 disable_git_global_config();
4050 cx.executor().allow_parking();
4051
4052 let temp_dir = tempfile::tempdir().unwrap();
4053 let repo_dir = temp_dir.path().join("repo");
4054 let worktrees_dir = temp_dir.path().join("worktrees");
4055 git2::Repository::init(&repo_dir).unwrap();
4056
4057 let repo = RealGitRepository::new(
4058 &repo_dir.join(".git"),
4059 None,
4060 Some("git".into()),
4061 cx.executor(),
4062 )
4063 .unwrap();
4064
4065 // Create an initial commit
4066 smol::fs::write(repo_dir.join("file.txt"), "content")
4067 .await
4068 .unwrap();
4069 repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
4070 .await
4071 .unwrap();
4072 repo.commit(
4073 "Initial commit".into(),
4074 None,
4075 CommitOptions::default(),
4076 AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
4077 Arc::new(checkpoint_author_envs()),
4078 )
4079 .await
4080 .unwrap();
4081
4082 // Create a worktree
4083 let worktree_path = worktrees_dir.join("worktree-to-remove");
4084 repo.create_worktree(
4085 "to-remove".to_string(),
4086 worktree_path.clone(),
4087 Some("HEAD".to_string()),
4088 )
4089 .await
4090 .unwrap();
4091
4092 // Remove the worktree
4093 repo.remove_worktree(worktree_path.clone(), false)
4094 .await
4095 .unwrap();
4096
4097 // Verify the directory is removed
4098 let worktrees = repo.worktrees().await.unwrap();
4099 assert_eq!(worktrees.len(), 1);
4100 assert!(
4101 worktrees.iter().all(|w| w.display_name() != "to-remove"),
4102 "removed worktree should not appear in list"
4103 );
4104 assert!(!worktree_path.exists());
4105
4106 // Create a worktree
4107 let worktree_path = worktrees_dir.join("dirty-wt");
4108 repo.create_worktree(
4109 "dirty-wt".to_string(),
4110 worktree_path.clone(),
4111 Some("HEAD".to_string()),
4112 )
4113 .await
4114 .unwrap();
4115
4116 assert!(worktree_path.exists());
4117
4118 // Add uncommitted changes in the worktree
4119 smol::fs::write(worktree_path.join("dirty-file.txt"), "uncommitted")
4120 .await
4121 .unwrap();
4122
4123 // Non-force removal should fail with dirty worktree
4124 let result = repo.remove_worktree(worktree_path.clone(), false).await;
4125 assert!(
4126 result.is_err(),
4127 "non-force removal of dirty worktree should fail"
4128 );
4129
4130 // Force removal should succeed
4131 repo.remove_worktree(worktree_path.clone(), true)
4132 .await
4133 .unwrap();
4134
4135 let worktrees = repo.worktrees().await.unwrap();
4136 assert_eq!(worktrees.len(), 1);
4137 assert!(!worktree_path.exists());
4138 }
4139
4140 #[gpui::test]
4141 async fn test_rename_worktree(cx: &mut TestAppContext) {
4142 disable_git_global_config();
4143 cx.executor().allow_parking();
4144
4145 let temp_dir = tempfile::tempdir().unwrap();
4146 let repo_dir = temp_dir.path().join("repo");
4147 let worktrees_dir = temp_dir.path().join("worktrees");
4148
4149 git2::Repository::init(&repo_dir).unwrap();
4150
4151 let repo = RealGitRepository::new(
4152 &repo_dir.join(".git"),
4153 None,
4154 Some("git".into()),
4155 cx.executor(),
4156 )
4157 .unwrap();
4158
4159 // Create an initial commit
4160 smol::fs::write(repo_dir.join("file.txt"), "content")
4161 .await
4162 .unwrap();
4163 repo.stage_paths(vec![repo_path("file.txt")], Arc::new(HashMap::default()))
4164 .await
4165 .unwrap();
4166 repo.commit(
4167 "Initial commit".into(),
4168 None,
4169 CommitOptions::default(),
4170 AskPassDelegate::new(&mut cx.to_async(), |_, _, _| {}),
4171 Arc::new(checkpoint_author_envs()),
4172 )
4173 .await
4174 .unwrap();
4175
4176 // Create a worktree
4177 let old_path = worktrees_dir.join("old-worktree-name");
4178 repo.create_worktree(
4179 "old-name".to_string(),
4180 old_path.clone(),
4181 Some("HEAD".to_string()),
4182 )
4183 .await
4184 .unwrap();
4185
4186 assert!(old_path.exists());
4187
4188 // Move the worktree to a new path
4189 let new_path = worktrees_dir.join("new-worktree-name");
4190 repo.rename_worktree(old_path.clone(), new_path.clone())
4191 .await
4192 .unwrap();
4193
4194 // Verify the old path is gone and new path exists
4195 assert!(!old_path.exists());
4196 assert!(new_path.exists());
4197
4198 // Verify it shows up in worktree list at the new path
4199 let worktrees = repo.worktrees().await.unwrap();
4200 assert_eq!(worktrees.len(), 2);
4201 let moved_worktree = worktrees
4202 .iter()
4203 .find(|w| w.display_name() == "old-name")
4204 .expect("should find worktree by branch name");
4205 assert_eq!(
4206 moved_worktree.path.canonicalize().unwrap(),
4207 new_path.canonicalize().unwrap()
4208 );
4209 }
4210
4211 #[test]
4212 fn test_original_repo_path_from_common_dir() {
4213 // Normal repo: common_dir is <work_dir>/.git
4214 assert_eq!(
4215 original_repo_path_from_common_dir(Path::new("/code/zed5/.git")),
4216 PathBuf::from("/code/zed5")
4217 );
4218
4219 // Worktree: common_dir is the main repo's .git
4220 // (same result — that's the point, it always traces back to the original)
4221 assert_eq!(
4222 original_repo_path_from_common_dir(Path::new("/code/zed5/.git")),
4223 PathBuf::from("/code/zed5")
4224 );
4225
4226 // Bare repo: no .git suffix, returns as-is
4227 assert_eq!(
4228 original_repo_path_from_common_dir(Path::new("/code/zed5.git")),
4229 PathBuf::from("/code/zed5.git")
4230 );
4231
4232 // Root-level .git directory
4233 assert_eq!(
4234 original_repo_path_from_common_dir(Path::new("/.git")),
4235 PathBuf::from("/")
4236 );
4237 }
4238
4239 impl RealGitRepository {
4240 /// Force a Git garbage collection on the repository.
4241 fn gc(&self) -> BoxFuture<'_, Result<()>> {
4242 let working_directory = self.working_directory();
4243 let git_directory = self.path();
4244 let git_binary_path = self.any_git_binary_path.clone();
4245 let executor = self.executor.clone();
4246 self.executor
4247 .spawn(async move {
4248 let git_binary_path = git_binary_path.clone();
4249 let working_directory = working_directory?;
4250 let git = GitBinary::new(
4251 git_binary_path,
4252 working_directory,
4253 git_directory,
4254 executor,
4255 true,
4256 );
4257 git.run(&["gc", "--prune"]).await?;
4258 Ok(())
4259 })
4260 .boxed()
4261 }
4262 }
4263}