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