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