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