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