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 repair_worktrees(&self) -> BoxFuture<'_, Result<()>>;
925
926 fn stage_all_including_untracked(&self) -> BoxFuture<'_, Result<()>>;
927
928 fn set_trusted(&self, trusted: bool);
929 fn is_trusted(&self) -> bool;
930}
931
932pub enum DiffType {
933 HeadToIndex,
934 HeadToWorktree,
935 MergeBase { base_ref: SharedString },
936}
937
938#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]
939pub enum PushOptions {
940 SetUpstream,
941 Force,
942}
943
944impl std::fmt::Debug for dyn GitRepository {
945 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
946 f.debug_struct("dyn GitRepository<...>").finish()
947 }
948}
949
950pub struct RealGitRepository {
951 pub repository: Arc<Mutex<git2::Repository>>,
952 pub system_git_binary_path: Option<PathBuf>,
953 pub any_git_binary_path: PathBuf,
954 any_git_binary_help_output: Arc<Mutex<Option<SharedString>>>,
955 executor: BackgroundExecutor,
956 is_trusted: Arc<AtomicBool>,
957}
958
959impl RealGitRepository {
960 pub fn new(
961 dotgit_path: &Path,
962 bundled_git_binary_path: Option<PathBuf>,
963 system_git_binary_path: Option<PathBuf>,
964 executor: BackgroundExecutor,
965 ) -> Result<Self> {
966 let any_git_binary_path = system_git_binary_path
967 .clone()
968 .or(bundled_git_binary_path)
969 .context("no git binary available")?;
970 log::info!(
971 "opening git repository at {dotgit_path:?} using git binary {any_git_binary_path:?}"
972 );
973 let workdir_root = dotgit_path.parent().context(".git has no parent")?;
974 let repository =
975 git2::Repository::open(workdir_root).context("creating libgit2 repository")?;
976 Ok(Self {
977 repository: Arc::new(Mutex::new(repository)),
978 system_git_binary_path,
979 any_git_binary_path,
980 executor,
981 any_git_binary_help_output: Arc::new(Mutex::new(None)),
982 is_trusted: Arc::new(AtomicBool::new(false)),
983 })
984 }
985
986 fn working_directory(&self) -> Result<PathBuf> {
987 self.repository
988 .lock()
989 .workdir()
990 .context("failed to read git work directory")
991 .map(Path::to_path_buf)
992 }
993
994 fn git_binary(&self) -> Result<GitBinary> {
995 Ok(GitBinary::new(
996 self.any_git_binary_path.clone(),
997 self.working_directory()
998 .with_context(|| "Can't run git commands without a working directory")?,
999 self.path(),
1000 self.executor.clone(),
1001 self.is_trusted(),
1002 ))
1003 }
1004
1005 async fn any_git_binary_help_output(&self) -> SharedString {
1006 if let Some(output) = self.any_git_binary_help_output.lock().clone() {
1007 return output;
1008 }
1009 let git_binary = self.git_binary();
1010 let output: SharedString = self
1011 .executor
1012 .spawn(async move { git_binary?.run(&["help", "-a"]).await })
1013 .await
1014 .unwrap_or_default()
1015 .into();
1016 *self.any_git_binary_help_output.lock() = Some(output.clone());
1017 output
1018 }
1019}
1020
1021#[derive(Clone, Debug)]
1022pub struct GitRepositoryCheckpoint {
1023 pub commit_sha: Oid,
1024}
1025
1026#[derive(Debug)]
1027pub struct GitCommitter {
1028 pub name: Option<String>,
1029 pub email: Option<String>,
1030}
1031
1032pub async fn get_git_committer(cx: &AsyncApp) -> GitCommitter {
1033 if cfg!(any(feature = "test-support", test)) {
1034 return GitCommitter {
1035 name: None,
1036 email: None,
1037 };
1038 }
1039
1040 let git_binary_path =
1041 if cfg!(target_os = "macos") && option_env!("ZED_BUNDLE").as_deref() == Some("true") {
1042 cx.update(|cx| {
1043 cx.path_for_auxiliary_executable("git")
1044 .context("could not find git binary path")
1045 .log_err()
1046 })
1047 } else {
1048 None
1049 };
1050
1051 let git = GitBinary::new(
1052 git_binary_path.unwrap_or(PathBuf::from("git")),
1053 paths::home_dir().clone(),
1054 paths::home_dir().join(".git"),
1055 cx.background_executor().clone(),
1056 true,
1057 );
1058
1059 cx.background_spawn(async move {
1060 let name = git
1061 .run(&["config", "--global", "user.name"])
1062 .await
1063 .log_err();
1064 let email = git
1065 .run(&["config", "--global", "user.email"])
1066 .await
1067 .log_err();
1068 GitCommitter { name, email }
1069 })
1070 .await
1071}
1072
1073impl GitRepository for RealGitRepository {
1074 fn reload_index(&self) {
1075 if let Ok(mut index) = self.repository.lock().index() {
1076 _ = index.read(false);
1077 }
1078 }
1079
1080 fn path(&self) -> PathBuf {
1081 let repo = self.repository.lock();
1082 repo.path().into()
1083 }
1084
1085 fn main_repository_path(&self) -> PathBuf {
1086 let repo = self.repository.lock();
1087 repo.commondir().into()
1088 }
1089
1090 fn show(&self, commit: String) -> BoxFuture<'_, Result<CommitDetails>> {
1091 let git_binary = self.git_binary();
1092 self.executor
1093 .spawn(async move {
1094 let git = git_binary?;
1095 let output = git
1096 .build_command(&[
1097 "show",
1098 "--no-patch",
1099 "--format=%H%x00%B%x00%at%x00%ae%x00%an%x00",
1100 &commit,
1101 ])
1102 .output()
1103 .await?;
1104 let output = std::str::from_utf8(&output.stdout)?;
1105 let fields = output.split('\0').collect::<Vec<_>>();
1106 if fields.len() != 6 {
1107 bail!("unexpected git-show output for {commit:?}: {output:?}")
1108 }
1109 let sha = fields[0].to_string().into();
1110 let message = fields[1].to_string().into();
1111 let commit_timestamp = fields[2].parse()?;
1112 let author_email = fields[3].to_string().into();
1113 let author_name = fields[4].to_string().into();
1114 Ok(CommitDetails {
1115 sha,
1116 message,
1117 commit_timestamp,
1118 author_email,
1119 author_name,
1120 })
1121 })
1122 .boxed()
1123 }
1124
1125 fn load_commit(&self, commit: String, cx: AsyncApp) -> BoxFuture<'_, Result<CommitDiff>> {
1126 if self.repository.lock().workdir().is_none() {
1127 return future::ready(Err(anyhow!("no working directory"))).boxed();
1128 }
1129 let git_binary = self.git_binary();
1130 cx.background_spawn(async move {
1131 let git = git_binary?;
1132 let show_output = git
1133 .build_command(&[
1134 "show",
1135 "--format=",
1136 "-z",
1137 "--no-renames",
1138 "--name-status",
1139 "--first-parent",
1140 ])
1141 .arg(&commit)
1142 .stdin(Stdio::null())
1143 .stdout(Stdio::piped())
1144 .stderr(Stdio::piped())
1145 .output()
1146 .await
1147 .context("starting git show process")?;
1148
1149 let show_stdout = String::from_utf8_lossy(&show_output.stdout);
1150 let changes = parse_git_diff_name_status(&show_stdout);
1151 let parent_sha = format!("{}^", commit);
1152
1153 let mut cat_file_process = git
1154 .build_command(&["cat-file", "--batch=%(objectsize)"])
1155 .stdin(Stdio::piped())
1156 .stdout(Stdio::piped())
1157 .stderr(Stdio::piped())
1158 .spawn()
1159 .context("starting git cat-file process")?;
1160
1161 let mut files = Vec::<CommitFile>::new();
1162 let mut stdin = BufWriter::with_capacity(512, cat_file_process.stdin.take().unwrap());
1163 let mut stdout = BufReader::new(cat_file_process.stdout.take().unwrap());
1164 let mut info_line = String::new();
1165 let mut newline = [b'\0'];
1166 for (path, status_code) in changes {
1167 // git-show outputs `/`-delimited paths even on Windows.
1168 let Some(rel_path) = RelPath::unix(path).log_err() else {
1169 continue;
1170 };
1171
1172 match status_code {
1173 StatusCode::Modified => {
1174 stdin.write_all(commit.as_bytes()).await?;
1175 stdin.write_all(b":").await?;
1176 stdin.write_all(path.as_bytes()).await?;
1177 stdin.write_all(b"\n").await?;
1178 stdin.write_all(parent_sha.as_bytes()).await?;
1179 stdin.write_all(b":").await?;
1180 stdin.write_all(path.as_bytes()).await?;
1181 stdin.write_all(b"\n").await?;
1182 }
1183 StatusCode::Added => {
1184 stdin.write_all(commit.as_bytes()).await?;
1185 stdin.write_all(b":").await?;
1186 stdin.write_all(path.as_bytes()).await?;
1187 stdin.write_all(b"\n").await?;
1188 }
1189 StatusCode::Deleted => {
1190 stdin.write_all(parent_sha.as_bytes()).await?;
1191 stdin.write_all(b":").await?;
1192 stdin.write_all(path.as_bytes()).await?;
1193 stdin.write_all(b"\n").await?;
1194 }
1195 _ => continue,
1196 }
1197 stdin.flush().await?;
1198
1199 info_line.clear();
1200 stdout.read_line(&mut info_line).await?;
1201
1202 let len = info_line.trim_end().parse().with_context(|| {
1203 format!("invalid object size output from cat-file {info_line}")
1204 })?;
1205 let mut text_bytes = vec![0; len];
1206 stdout.read_exact(&mut text_bytes).await?;
1207 stdout.read_exact(&mut newline).await?;
1208
1209 let mut old_text = None;
1210 let mut new_text = None;
1211 let mut is_binary = is_binary_content(&text_bytes);
1212 let text = if is_binary {
1213 String::new()
1214 } else {
1215 String::from_utf8_lossy(&text_bytes).to_string()
1216 };
1217
1218 match status_code {
1219 StatusCode::Modified => {
1220 info_line.clear();
1221 stdout.read_line(&mut info_line).await?;
1222 let len = info_line.trim_end().parse().with_context(|| {
1223 format!("invalid object size output from cat-file {}", info_line)
1224 })?;
1225 let mut parent_bytes = vec![0; len];
1226 stdout.read_exact(&mut parent_bytes).await?;
1227 stdout.read_exact(&mut newline).await?;
1228 is_binary = is_binary || is_binary_content(&parent_bytes);
1229 if is_binary {
1230 old_text = Some(String::new());
1231 new_text = Some(String::new());
1232 } else {
1233 old_text = Some(String::from_utf8_lossy(&parent_bytes).to_string());
1234 new_text = Some(text);
1235 }
1236 }
1237 StatusCode::Added => new_text = Some(text),
1238 StatusCode::Deleted => old_text = Some(text),
1239 _ => continue,
1240 }
1241
1242 files.push(CommitFile {
1243 path: RepoPath(Arc::from(rel_path)),
1244 old_text,
1245 new_text,
1246 is_binary,
1247 })
1248 }
1249
1250 Ok(CommitDiff { files })
1251 })
1252 .boxed()
1253 }
1254
1255 fn reset(
1256 &self,
1257 commit: String,
1258 mode: ResetMode,
1259 env: Arc<HashMap<String, String>>,
1260 ) -> BoxFuture<'_, Result<()>> {
1261 let git_binary = self.git_binary();
1262 async move {
1263 let mode_flag = match mode {
1264 ResetMode::Mixed => "--mixed",
1265 ResetMode::Soft => "--soft",
1266 };
1267
1268 let git = git_binary?;
1269 let output = git
1270 .build_command(&["reset", mode_flag, &commit])
1271 .envs(env.iter())
1272 .output()
1273 .await?;
1274 anyhow::ensure!(
1275 output.status.success(),
1276 "Failed to reset:\n{}",
1277 String::from_utf8_lossy(&output.stderr),
1278 );
1279 Ok(())
1280 }
1281 .boxed()
1282 }
1283
1284 fn checkout_files(
1285 &self,
1286 commit: String,
1287 paths: Vec<RepoPath>,
1288 env: Arc<HashMap<String, String>>,
1289 ) -> BoxFuture<'_, Result<()>> {
1290 let git_binary = self.git_binary();
1291 async move {
1292 if paths.is_empty() {
1293 return Ok(());
1294 }
1295
1296 let git = git_binary?;
1297 let output = git
1298 .build_command(&["checkout", &commit, "--"])
1299 .envs(env.iter())
1300 .args(paths.iter().map(|path| path.as_unix_str()))
1301 .output()
1302 .await?;
1303 anyhow::ensure!(
1304 output.status.success(),
1305 "Failed to checkout files:\n{}",
1306 String::from_utf8_lossy(&output.stderr),
1307 );
1308 Ok(())
1309 }
1310 .boxed()
1311 }
1312
1313 fn load_index_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>> {
1314 // https://git-scm.com/book/en/v2/Git-Internals-Git-Objects
1315 const GIT_MODE_SYMLINK: u32 = 0o120000;
1316
1317 let repo = self.repository.clone();
1318 self.executor
1319 .spawn(async move {
1320 fn logic(repo: &git2::Repository, path: &RepoPath) -> Result<Option<String>> {
1321 let mut index = repo.index()?;
1322 index.read(false)?;
1323
1324 const STAGE_NORMAL: i32 = 0;
1325 // git2 unwraps internally on empty paths or `.`
1326 if path.is_empty() {
1327 bail!("empty path has no index text");
1328 }
1329 let Some(entry) = index.get_path(path.as_std_path(), STAGE_NORMAL) else {
1330 return Ok(None);
1331 };
1332 if entry.mode == GIT_MODE_SYMLINK {
1333 return Ok(None);
1334 }
1335
1336 let content = repo.find_blob(entry.id)?.content().to_owned();
1337 Ok(String::from_utf8(content).ok())
1338 }
1339
1340 logic(&repo.lock(), &path)
1341 .context("loading index text")
1342 .log_err()
1343 .flatten()
1344 })
1345 .boxed()
1346 }
1347
1348 fn load_committed_text(&self, path: RepoPath) -> BoxFuture<'_, Option<String>> {
1349 let repo = self.repository.clone();
1350 self.executor
1351 .spawn(async move {
1352 fn logic(repo: &git2::Repository, path: &RepoPath) -> Result<Option<String>> {
1353 let head = repo.head()?.peel_to_tree()?;
1354 // git2 unwraps internally on empty paths or `.`
1355 if path.is_empty() {
1356 return Err(anyhow!("empty path has no committed text"));
1357 }
1358 let Some(entry) = head.get_path(path.as_std_path()).ok() else {
1359 return Ok(None);
1360 };
1361 if entry.filemode() == i32::from(git2::FileMode::Link) {
1362 return Ok(None);
1363 }
1364 let content = repo.find_blob(entry.id())?.content().to_owned();
1365 Ok(String::from_utf8(content).ok())
1366 }
1367
1368 logic(&repo.lock(), &path)
1369 .context("loading committed text")
1370 .log_err()
1371 .flatten()
1372 })
1373 .boxed()
1374 }
1375
1376 fn load_blob_content(&self, oid: Oid) -> BoxFuture<'_, Result<String>> {
1377 let repo = self.repository.clone();
1378 self.executor
1379 .spawn(async move {
1380 let repo = repo.lock();
1381 let content = repo.find_blob(oid.0)?.content().to_owned();
1382 Ok(String::from_utf8(content)?)
1383 })
1384 .boxed()
1385 }
1386
1387 fn set_index_text(
1388 &self,
1389 path: RepoPath,
1390 content: Option<String>,
1391 env: Arc<HashMap<String, String>>,
1392 is_executable: bool,
1393 ) -> BoxFuture<'_, anyhow::Result<()>> {
1394 let git_binary = self.git_binary();
1395 self.executor
1396 .spawn(async move {
1397 let git = git_binary?;
1398 let mode = if is_executable { "100755" } else { "100644" };
1399
1400 if let Some(content) = content {
1401 let mut child = git
1402 .build_command(&["hash-object", "-w", "--stdin"])
1403 .envs(env.iter())
1404 .stdin(Stdio::piped())
1405 .stdout(Stdio::piped())
1406 .spawn()?;
1407 let mut stdin = child.stdin.take().unwrap();
1408 stdin.write_all(content.as_bytes()).await?;
1409 stdin.flush().await?;
1410 drop(stdin);
1411 let output = child.output().await?.stdout;
1412 let sha = str::from_utf8(&output)?.trim();
1413
1414 log::debug!("indexing SHA: {sha}, path {path:?}");
1415
1416 let output = git
1417 .build_command(&["update-index", "--add", "--cacheinfo", mode, sha])
1418 .envs(env.iter())
1419 .arg(path.as_unix_str())
1420 .output()
1421 .await?;
1422
1423 anyhow::ensure!(
1424 output.status.success(),
1425 "Failed to stage:\n{}",
1426 String::from_utf8_lossy(&output.stderr)
1427 );
1428 } else {
1429 log::debug!("removing path {path:?} from the index");
1430 let output = git
1431 .build_command(&["update-index", "--force-remove"])
1432 .envs(env.iter())
1433 .arg(path.as_unix_str())
1434 .output()
1435 .await?;
1436 anyhow::ensure!(
1437 output.status.success(),
1438 "Failed to unstage:\n{}",
1439 String::from_utf8_lossy(&output.stderr)
1440 );
1441 }
1442
1443 Ok(())
1444 })
1445 .boxed()
1446 }
1447
1448 fn remote_url(&self, name: &str) -> BoxFuture<'_, Option<String>> {
1449 let repo = self.repository.clone();
1450 let name = name.to_owned();
1451 self.executor
1452 .spawn(async move {
1453 let repo = repo.lock();
1454 let remote = repo.find_remote(&name).ok()?;
1455 remote.url().map(|url| url.to_string())
1456 })
1457 .boxed()
1458 }
1459
1460 fn revparse_batch(&self, revs: Vec<String>) -> BoxFuture<'_, Result<Vec<Option<String>>>> {
1461 let git_binary = self.git_binary();
1462 self.executor
1463 .spawn(async move {
1464 let git = git_binary?;
1465 let mut process = git
1466 .build_command(&["cat-file", "--batch-check=%(objectname)"])
1467 .stdin(Stdio::piped())
1468 .stdout(Stdio::piped())
1469 .stderr(Stdio::piped())
1470 .spawn()?;
1471
1472 let stdin = process
1473 .stdin
1474 .take()
1475 .context("no stdin for git cat-file subprocess")?;
1476 let mut stdin = BufWriter::new(stdin);
1477 for rev in &revs {
1478 stdin.write_all(rev.as_bytes()).await?;
1479 stdin.write_all(b"\n").await?;
1480 }
1481 stdin.flush().await?;
1482 drop(stdin);
1483
1484 let output = process.output().await?;
1485 let output = std::str::from_utf8(&output.stdout)?;
1486 let shas = output
1487 .lines()
1488 .map(|line| {
1489 if line.ends_with("missing") {
1490 None
1491 } else {
1492 Some(line.to_string())
1493 }
1494 })
1495 .collect::<Vec<_>>();
1496
1497 if shas.len() != revs.len() {
1498 // In an octopus merge, git cat-file still only outputs the first sha from MERGE_HEAD.
1499 bail!("unexpected number of shas")
1500 }
1501
1502 Ok(shas)
1503 })
1504 .boxed()
1505 }
1506
1507 fn merge_message(&self) -> BoxFuture<'_, Option<String>> {
1508 let path = self.path().join("MERGE_MSG");
1509 self.executor
1510 .spawn(async move { std::fs::read_to_string(&path).ok() })
1511 .boxed()
1512 }
1513
1514 fn status(&self, path_prefixes: &[RepoPath]) -> Task<Result<GitStatus>> {
1515 let git = match self.git_binary() {
1516 Ok(git) => git,
1517 Err(e) => return Task::ready(Err(e)),
1518 };
1519 let args = git_status_args(path_prefixes);
1520 log::debug!("Checking for git status in {path_prefixes:?}");
1521 self.executor.spawn(async move {
1522 let output = git.build_command(&args).output().await?;
1523 if output.status.success() {
1524 let stdout = String::from_utf8_lossy(&output.stdout);
1525 stdout.parse()
1526 } else {
1527 let stderr = String::from_utf8_lossy(&output.stderr);
1528 anyhow::bail!("git status failed: {stderr}");
1529 }
1530 })
1531 }
1532
1533 fn diff_tree(&self, request: DiffTreeType) -> BoxFuture<'_, Result<TreeDiff>> {
1534 let git = match self.git_binary() {
1535 Ok(git) => git,
1536 Err(e) => return Task::ready(Err(e)).boxed(),
1537 };
1538
1539 let mut args = vec![
1540 OsString::from("diff-tree"),
1541 OsString::from("-r"),
1542 OsString::from("-z"),
1543 OsString::from("--no-renames"),
1544 ];
1545 match request {
1546 DiffTreeType::MergeBase { base, head } => {
1547 args.push("--merge-base".into());
1548 args.push(OsString::from(base.as_str()));
1549 args.push(OsString::from(head.as_str()));
1550 }
1551 DiffTreeType::Since { base, head } => {
1552 args.push(OsString::from(base.as_str()));
1553 args.push(OsString::from(head.as_str()));
1554 }
1555 }
1556
1557 self.executor
1558 .spawn(async move {
1559 let output = git.build_command(&args).output().await?;
1560 if output.status.success() {
1561 let stdout = String::from_utf8_lossy(&output.stdout);
1562 stdout.parse()
1563 } else {
1564 let stderr = String::from_utf8_lossy(&output.stderr);
1565 anyhow::bail!("git status failed: {stderr}");
1566 }
1567 })
1568 .boxed()
1569 }
1570
1571 fn stash_entries(&self) -> BoxFuture<'_, Result<GitStash>> {
1572 let git_binary = self.git_binary();
1573 self.executor
1574 .spawn(async move {
1575 let git = git_binary?;
1576 let output = git
1577 .build_command(&["stash", "list", "--pretty=format:%gd%x00%H%x00%ct%x00%s"])
1578 .output()
1579 .await?;
1580 if output.status.success() {
1581 let stdout = String::from_utf8_lossy(&output.stdout);
1582 stdout.parse()
1583 } else {
1584 let stderr = String::from_utf8_lossy(&output.stderr);
1585 anyhow::bail!("git status failed: {stderr}");
1586 }
1587 })
1588 .boxed()
1589 }
1590
1591 fn branches(&self) -> BoxFuture<'_, Result<Vec<Branch>>> {
1592 let git_binary = self.git_binary();
1593 self.executor
1594 .spawn(async move {
1595 let fields = [
1596 "%(HEAD)",
1597 "%(objectname)",
1598 "%(parent)",
1599 "%(refname)",
1600 "%(upstream)",
1601 "%(upstream:track)",
1602 "%(committerdate:unix)",
1603 "%(authorname)",
1604 "%(contents:subject)",
1605 ]
1606 .join("%00");
1607 let args = vec![
1608 "for-each-ref",
1609 "refs/heads/**/*",
1610 "refs/remotes/**/*",
1611 "--format",
1612 &fields,
1613 ];
1614 let git = git_binary?;
1615 let output = git.build_command(&args).output().await?;
1616
1617 anyhow::ensure!(
1618 output.status.success(),
1619 "Failed to git git branches:\n{}",
1620 String::from_utf8_lossy(&output.stderr)
1621 );
1622
1623 let input = String::from_utf8_lossy(&output.stdout);
1624
1625 let mut branches = parse_branch_input(&input)?;
1626 if branches.is_empty() {
1627 let args = vec!["symbolic-ref", "--quiet", "HEAD"];
1628
1629 let output = git.build_command(&args).output().await?;
1630
1631 // git symbolic-ref returns a non-0 exit code if HEAD points
1632 // to something other than a branch
1633 if output.status.success() {
1634 let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
1635
1636 branches.push(Branch {
1637 ref_name: name.into(),
1638 is_head: true,
1639 upstream: None,
1640 most_recent_commit: None,
1641 });
1642 }
1643 }
1644
1645 Ok(branches)
1646 })
1647 .boxed()
1648 }
1649
1650 fn worktrees(&self) -> BoxFuture<'_, Result<Vec<Worktree>>> {
1651 let git_binary = self.git_binary();
1652 self.executor
1653 .spawn(async move {
1654 let git = git_binary?;
1655 let output = git
1656 .build_command(&["worktree", "list", "--porcelain"])
1657 .output()
1658 .await?;
1659 if output.status.success() {
1660 let stdout = String::from_utf8_lossy(&output.stdout);
1661 Ok(parse_worktrees_from_str(&stdout))
1662 } else {
1663 let stderr = String::from_utf8_lossy(&output.stderr);
1664 anyhow::bail!("git worktree list failed: {stderr}");
1665 }
1666 })
1667 .boxed()
1668 }
1669
1670 fn create_worktree(
1671 &self,
1672 branch_name: Option<String>,
1673 path: PathBuf,
1674 from_commit: Option<String>,
1675 ) -> BoxFuture<'_, Result<()>> {
1676 let git_binary = self.git_binary();
1677 let mut args = vec![OsString::from("worktree"), OsString::from("add")];
1678 if let Some(branch_name) = &branch_name {
1679 args.push(OsString::from("-b"));
1680 args.push(OsString::from(branch_name.as_str()));
1681 } else {
1682 args.push(OsString::from("--detach"));
1683 }
1684 args.push(OsString::from("--"));
1685 args.push(OsString::from(path.as_os_str()));
1686 if let Some(from_commit) = from_commit {
1687 args.push(OsString::from(from_commit));
1688 } else {
1689 args.push(OsString::from("HEAD"));
1690 }
1691
1692 self.executor
1693 .spawn(async move {
1694 std::fs::create_dir_all(path.parent().unwrap_or(&path))?;
1695 let git = git_binary?;
1696 let output = git.build_command(&args).output().await?;
1697 if output.status.success() {
1698 Ok(())
1699 } else {
1700 let stderr = String::from_utf8_lossy(&output.stderr);
1701 anyhow::bail!("git worktree add failed: {stderr}");
1702 }
1703 })
1704 .boxed()
1705 }
1706
1707 fn remove_worktree(&self, path: PathBuf, force: bool) -> BoxFuture<'_, Result<()>> {
1708 let git_binary = self.git_binary();
1709
1710 self.executor
1711 .spawn(async move {
1712 let mut args: Vec<OsString> = vec!["worktree".into(), "remove".into()];
1713 if force {
1714 args.push("--force".into());
1715 }
1716 args.push("--".into());
1717 args.push(path.as_os_str().into());
1718 git_binary?.run(&args).await?;
1719 anyhow::Ok(())
1720 })
1721 .boxed()
1722 }
1723
1724 fn rename_worktree(&self, old_path: PathBuf, new_path: PathBuf) -> BoxFuture<'_, Result<()>> {
1725 let git_binary = self.git_binary();
1726
1727 self.executor
1728 .spawn(async move {
1729 let args: Vec<OsString> = vec![
1730 "worktree".into(),
1731 "move".into(),
1732 "--".into(),
1733 old_path.as_os_str().into(),
1734 new_path.as_os_str().into(),
1735 ];
1736 git_binary?.run(&args).await?;
1737 anyhow::Ok(())
1738 })
1739 .boxed()
1740 }
1741
1742 fn change_branch(&self, name: String) -> BoxFuture<'_, Result<()>> {
1743 let repo = self.repository.clone();
1744 let git_binary = self.git_binary();
1745 let branch = self.executor.spawn(async move {
1746 let repo = repo.lock();
1747 let branch = if let Ok(branch) = repo.find_branch(&name, BranchType::Local) {
1748 branch
1749 } else if let Ok(revision) = repo.find_branch(&name, BranchType::Remote) {
1750 let (_, branch_name) = name.split_once("/").context("Unexpected branch format")?;
1751
1752 let revision = revision.get();
1753 let branch_commit = revision.peel_to_commit()?;
1754 let mut branch = match repo.branch(&branch_name, &branch_commit, false) {
1755 Ok(branch) => branch,
1756 Err(err) if err.code() == ErrorCode::Exists => {
1757 repo.find_branch(&branch_name, BranchType::Local)?
1758 }
1759 Err(err) => {
1760 return Err(err.into());
1761 }
1762 };
1763
1764 branch.set_upstream(Some(&name))?;
1765 branch
1766 } else {
1767 anyhow::bail!("Branch '{}' not found", name);
1768 };
1769
1770 Ok(branch
1771 .name()?
1772 .context("cannot checkout anonymous branch")?
1773 .to_string())
1774 });
1775
1776 self.executor
1777 .spawn(async move {
1778 let branch = branch.await?;
1779 git_binary?.run(&["checkout", &branch]).await?;
1780 anyhow::Ok(())
1781 })
1782 .boxed()
1783 }
1784
1785 fn create_branch(
1786 &self,
1787 name: String,
1788 base_branch: Option<String>,
1789 ) -> BoxFuture<'_, Result<()>> {
1790 let git_binary = self.git_binary();
1791
1792 self.executor
1793 .spawn(async move {
1794 let mut args = vec!["switch", "-c", &name];
1795 let base_branch_str;
1796 if let Some(ref base) = base_branch {
1797 base_branch_str = base.clone();
1798 args.push(&base_branch_str);
1799 }
1800
1801 git_binary?.run(&args).await?;
1802 anyhow::Ok(())
1803 })
1804 .boxed()
1805 }
1806
1807 fn rename_branch(&self, branch: String, new_name: String) -> BoxFuture<'_, Result<()>> {
1808 let git_binary = self.git_binary();
1809
1810 self.executor
1811 .spawn(async move {
1812 git_binary?
1813 .run(&["branch", "-m", &branch, &new_name])
1814 .await?;
1815 anyhow::Ok(())
1816 })
1817 .boxed()
1818 }
1819
1820 fn delete_branch(&self, is_remote: bool, name: String) -> BoxFuture<'_, Result<()>> {
1821 let git_binary = self.git_binary();
1822
1823 self.executor
1824 .spawn(async move {
1825 git_binary?
1826 .run(&["branch", if is_remote { "-dr" } else { "-d" }, &name])
1827 .await?;
1828 anyhow::Ok(())
1829 })
1830 .boxed()
1831 }
1832
1833 fn blame(
1834 &self,
1835 path: RepoPath,
1836 content: Rope,
1837 line_ending: LineEnding,
1838 ) -> BoxFuture<'_, Result<crate::blame::Blame>> {
1839 let git = self.git_binary();
1840
1841 self.executor
1842 .spawn(async move {
1843 crate::blame::Blame::for_path(&git?, &path, &content, line_ending).await
1844 })
1845 .boxed()
1846 }
1847
1848 fn file_history(&self, path: RepoPath) -> BoxFuture<'_, Result<FileHistory>> {
1849 self.file_history_paginated(path, 0, None)
1850 }
1851
1852 fn file_history_paginated(
1853 &self,
1854 path: RepoPath,
1855 skip: usize,
1856 limit: Option<usize>,
1857 ) -> BoxFuture<'_, Result<FileHistory>> {
1858 let git_binary = self.git_binary();
1859 self.executor
1860 .spawn(async move {
1861 let git = git_binary?;
1862 // Use a unique delimiter with a hardcoded UUID to separate commits
1863 // This essentially eliminates any chance of encountering the delimiter in actual commit data
1864 let commit_delimiter =
1865 concat!("<<COMMIT_END-", "3f8a9c2e-7d4b-4e1a-9f6c-8b5d2a1e4c3f>>",);
1866
1867 let format_string = format!(
1868 "--pretty=format:%H%x00%s%x00%B%x00%at%x00%an%x00%ae{}",
1869 commit_delimiter
1870 );
1871
1872 let mut args = vec!["log", "--follow", &format_string];
1873
1874 let skip_str;
1875 let limit_str;
1876 if skip > 0 {
1877 skip_str = skip.to_string();
1878 args.push("--skip");
1879 args.push(&skip_str);
1880 }
1881 if let Some(n) = limit {
1882 limit_str = n.to_string();
1883 args.push("-n");
1884 args.push(&limit_str);
1885 }
1886
1887 args.push("--");
1888
1889 let output = git
1890 .build_command(&args)
1891 .arg(path.as_unix_str())
1892 .output()
1893 .await?;
1894
1895 if !output.status.success() {
1896 let stderr = String::from_utf8_lossy(&output.stderr);
1897 bail!("git log failed: {stderr}");
1898 }
1899
1900 let stdout = std::str::from_utf8(&output.stdout)?;
1901 let mut entries = Vec::new();
1902
1903 for commit_block in stdout.split(commit_delimiter) {
1904 let commit_block = commit_block.trim();
1905 if commit_block.is_empty() {
1906 continue;
1907 }
1908
1909 let fields: Vec<&str> = commit_block.split('\0').collect();
1910 if fields.len() >= 6 {
1911 let sha = fields[0].trim().to_string().into();
1912 let subject = fields[1].trim().to_string().into();
1913 let message = fields[2].trim().to_string().into();
1914 let commit_timestamp = fields[3].trim().parse().unwrap_or(0);
1915 let author_name = fields[4].trim().to_string().into();
1916 let author_email = fields[5].trim().to_string().into();
1917
1918 entries.push(FileHistoryEntry {
1919 sha,
1920 subject,
1921 message,
1922 commit_timestamp,
1923 author_name,
1924 author_email,
1925 });
1926 }
1927 }
1928
1929 Ok(FileHistory { entries, path })
1930 })
1931 .boxed()
1932 }
1933
1934 fn diff(&self, diff: DiffType) -> BoxFuture<'_, Result<String>> {
1935 let git_binary = self.git_binary();
1936 self.executor
1937 .spawn(async move {
1938 let git = git_binary?;
1939 let output = match diff {
1940 DiffType::HeadToIndex => {
1941 git.build_command(&["diff", "--staged"]).output().await?
1942 }
1943 DiffType::HeadToWorktree => git.build_command(&["diff"]).output().await?,
1944 DiffType::MergeBase { base_ref } => {
1945 git.build_command(&["diff", "--merge-base", base_ref.as_ref()])
1946 .output()
1947 .await?
1948 }
1949 };
1950
1951 anyhow::ensure!(
1952 output.status.success(),
1953 "Failed to run git diff:\n{}",
1954 String::from_utf8_lossy(&output.stderr)
1955 );
1956 Ok(String::from_utf8_lossy(&output.stdout).to_string())
1957 })
1958 .boxed()
1959 }
1960
1961 fn diff_stat(
1962 &self,
1963 path_prefixes: &[RepoPath],
1964 ) -> BoxFuture<'_, Result<crate::status::GitDiffStat>> {
1965 let path_prefixes = path_prefixes.to_vec();
1966 let git_binary = self.git_binary();
1967
1968 self.executor
1969 .spawn(async move {
1970 let git_binary = git_binary?;
1971 let mut args: Vec<String> = vec![
1972 "diff".into(),
1973 "--numstat".into(),
1974 "--no-renames".into(),
1975 "HEAD".into(),
1976 ];
1977 if !path_prefixes.is_empty() {
1978 args.push("--".into());
1979 args.extend(
1980 path_prefixes
1981 .iter()
1982 .map(|p| p.as_std_path().to_string_lossy().into_owned()),
1983 );
1984 }
1985 let output = git_binary.run(&args).await?;
1986 Ok(crate::status::parse_numstat(&output))
1987 })
1988 .boxed()
1989 }
1990
1991 fn stage_paths(
1992 &self,
1993 paths: Vec<RepoPath>,
1994 env: Arc<HashMap<String, String>>,
1995 ) -> BoxFuture<'_, Result<()>> {
1996 let git_binary = self.git_binary();
1997 self.executor
1998 .spawn(async move {
1999 if !paths.is_empty() {
2000 let git = git_binary?;
2001 let output = git
2002 .build_command(&["update-index", "--add", "--remove", "--"])
2003 .envs(env.iter())
2004 .args(paths.iter().map(|p| p.as_unix_str()))
2005 .output()
2006 .await?;
2007 anyhow::ensure!(
2008 output.status.success(),
2009 "Failed to stage paths:\n{}",
2010 String::from_utf8_lossy(&output.stderr),
2011 );
2012 }
2013 Ok(())
2014 })
2015 .boxed()
2016 }
2017
2018 fn unstage_paths(
2019 &self,
2020 paths: Vec<RepoPath>,
2021 env: Arc<HashMap<String, String>>,
2022 ) -> BoxFuture<'_, Result<()>> {
2023 let git_binary = self.git_binary();
2024
2025 self.executor
2026 .spawn(async move {
2027 if !paths.is_empty() {
2028 let git = git_binary?;
2029 let output = git
2030 .build_command(&["reset", "--quiet", "--"])
2031 .envs(env.iter())
2032 .args(paths.iter().map(|p| p.as_std_path()))
2033 .output()
2034 .await?;
2035
2036 anyhow::ensure!(
2037 output.status.success(),
2038 "Failed to unstage:\n{}",
2039 String::from_utf8_lossy(&output.stderr),
2040 );
2041 }
2042 Ok(())
2043 })
2044 .boxed()
2045 }
2046
2047 fn stash_paths(
2048 &self,
2049 paths: Vec<RepoPath>,
2050 env: Arc<HashMap<String, String>>,
2051 ) -> BoxFuture<'_, Result<()>> {
2052 let git_binary = self.git_binary();
2053 self.executor
2054 .spawn(async move {
2055 let git = git_binary?;
2056 let output = git
2057 .build_command(&["stash", "push", "--quiet", "--include-untracked"])
2058 .envs(env.iter())
2059 .args(paths.iter().map(|p| p.as_unix_str()))
2060 .output()
2061 .await?;
2062
2063 anyhow::ensure!(
2064 output.status.success(),
2065 "Failed to stash:\n{}",
2066 String::from_utf8_lossy(&output.stderr)
2067 );
2068 Ok(())
2069 })
2070 .boxed()
2071 }
2072
2073 fn stash_pop(
2074 &self,
2075 index: Option<usize>,
2076 env: Arc<HashMap<String, String>>,
2077 ) -> BoxFuture<'_, Result<()>> {
2078 let git_binary = self.git_binary();
2079 self.executor
2080 .spawn(async move {
2081 let git = git_binary?;
2082 let mut args = vec!["stash".to_string(), "pop".to_string()];
2083 if let Some(index) = index {
2084 args.push(format!("stash@{{{}}}", index));
2085 }
2086 let output = git.build_command(&args).envs(env.iter()).output().await?;
2087
2088 anyhow::ensure!(
2089 output.status.success(),
2090 "Failed to stash pop:\n{}",
2091 String::from_utf8_lossy(&output.stderr)
2092 );
2093 Ok(())
2094 })
2095 .boxed()
2096 }
2097
2098 fn stash_apply(
2099 &self,
2100 index: Option<usize>,
2101 env: Arc<HashMap<String, String>>,
2102 ) -> BoxFuture<'_, Result<()>> {
2103 let git_binary = self.git_binary();
2104 self.executor
2105 .spawn(async move {
2106 let git = git_binary?;
2107 let mut args = vec!["stash".to_string(), "apply".to_string()];
2108 if let Some(index) = index {
2109 args.push(format!("stash@{{{}}}", index));
2110 }
2111 let output = git.build_command(&args).envs(env.iter()).output().await?;
2112
2113 anyhow::ensure!(
2114 output.status.success(),
2115 "Failed to apply stash:\n{}",
2116 String::from_utf8_lossy(&output.stderr)
2117 );
2118 Ok(())
2119 })
2120 .boxed()
2121 }
2122
2123 fn stash_drop(
2124 &self,
2125 index: Option<usize>,
2126 env: Arc<HashMap<String, String>>,
2127 ) -> BoxFuture<'_, Result<()>> {
2128 let git_binary = self.git_binary();
2129 self.executor
2130 .spawn(async move {
2131 let git = git_binary?;
2132 let mut args = vec!["stash".to_string(), "drop".to_string()];
2133 if let Some(index) = index {
2134 args.push(format!("stash@{{{}}}", index));
2135 }
2136 let output = git.build_command(&args).envs(env.iter()).output().await?;
2137
2138 anyhow::ensure!(
2139 output.status.success(),
2140 "Failed to stash drop:\n{}",
2141 String::from_utf8_lossy(&output.stderr)
2142 );
2143 Ok(())
2144 })
2145 .boxed()
2146 }
2147
2148 fn commit(
2149 &self,
2150 message: SharedString,
2151 name_and_email: Option<(SharedString, SharedString)>,
2152 options: CommitOptions,
2153 ask_pass: AskPassDelegate,
2154 env: Arc<HashMap<String, String>>,
2155 ) -> BoxFuture<'_, Result<()>> {
2156 let git_binary = self.git_binary();
2157 let executor = self.executor.clone();
2158 // Note: Do not spawn this command on the background thread, it might pop open the credential helper
2159 // which we want to block on.
2160 async move {
2161 let git = git_binary?;
2162 let mut cmd = git.build_command(&["commit", "--quiet", "-m"]);
2163 cmd.envs(env.iter())
2164 .arg(&message.to_string())
2165 .arg("--cleanup=strip")
2166 .arg("--no-verify")
2167 .stdout(Stdio::piped())
2168 .stderr(Stdio::piped());
2169
2170 if options.amend {
2171 cmd.arg("--amend");
2172 }
2173
2174 if options.signoff {
2175 cmd.arg("--signoff");
2176 }
2177
2178 if options.allow_empty {
2179 cmd.arg("--allow-empty");
2180 }
2181
2182 if let Some((name, email)) = name_and_email {
2183 cmd.arg("--author").arg(&format!("{name} <{email}>"));
2184 }
2185
2186 run_git_command(env, ask_pass, cmd, executor).await?;
2187
2188 Ok(())
2189 }
2190 .boxed()
2191 }
2192
2193 fn update_ref(&self, ref_name: String, commit: String) -> BoxFuture<'_, Result<()>> {
2194 let git_binary = self.git_binary();
2195 self.executor
2196 .spawn(async move {
2197 let args: Vec<OsString> = vec!["update-ref".into(), ref_name.into(), commit.into()];
2198 git_binary?.run(&args).await?;
2199 Ok(())
2200 })
2201 .boxed()
2202 }
2203
2204 fn delete_ref(&self, ref_name: String) -> BoxFuture<'_, Result<()>> {
2205 let git_binary = self.git_binary();
2206 self.executor
2207 .spawn(async move {
2208 let args: Vec<OsString> = vec!["update-ref".into(), "-d".into(), ref_name.into()];
2209 git_binary?.run(&args).await?;
2210 Ok(())
2211 })
2212 .boxed()
2213 }
2214
2215 fn repair_worktrees(&self) -> BoxFuture<'_, Result<()>> {
2216 let git_binary = self.git_binary();
2217 self.executor
2218 .spawn(async move {
2219 let args: Vec<OsString> = vec!["worktree".into(), "repair".into()];
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}