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