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