Skip to content

armgit / zed

Public Imported from GitHub
0

Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.

git_ui: Keep staged changes when discarding from the unstaged section (#65559)

Stephen Zuniga1416404b88cf
diff --git a/crates/fs/src/fake_git_repo.rs b/crates/fs/src/fake_git_repo.rs
index 8801d7f4d62..2f274b95507 100644
--- a/crates/fs/src/fake_git_repo.rs
+++ b/crates/fs/src/fake_git_repo.rs
@@ -477,11 +477,51 @@ impl GitRepository for FakeGitRepository {
fn checkout_files(
&self,
- _commit: String,
- _paths: Vec<RepoPath>,
+ commit: Option<String>,
+ paths: Vec<RepoPath>,
_env: Arc<HashMap<String, String>>,
) -> BoxFuture<'_, Result<()>> {
- unimplemented!()
+ let fs = self.fs.clone();
+ let workdir_path = self.dot_git_path.parent().unwrap().to_path_buf();
+ let restored = self.with_state_async(true, move |state| {
+ if let Some(commit) = &commit {
+ let head_sha = state.refs.get("HEAD").map(String::as_str);
+ anyhow::ensure!(
+ commit == "HEAD" || Some(commit.as_str()) == head_sha,
+ "fake git repository can only check out files from HEAD, got {commit}"
+ );
+ }
+ let source = if commit.is_some() {
+ &state.head_contents
+ } else {
+ &state.index_contents
+ };
+ let restored = paths
+ .into_iter()
+ .map(|path| {
+ let content = source.get(&path).cloned().with_context(|| {
+ format!(
+ "pathspec '{}' did not match any file(s) known to git",
+ path.as_unix_str()
+ )
+ })?;
+ Ok((path, content))
+ })
+ .collect::<Result<Vec<_>>>()?;
+ if commit.is_some() {
+ for (path, content) in &restored {
+ state.index_contents.insert(path.clone(), content.clone());
+ }
+ }
+ Ok(restored)
+ });
+ async move {
+ for (path, content) in restored.await? {
+ fs.write_file_internal(workdir_path.join(path.as_std_path()), content, false)?;
+ }
+ Ok(())
+ }
+ .boxed()
}
fn path(&self) -> PathBuf {
diff --git a/crates/git/src/repository.rs b/crates/git/src/repository.rs
index de42e3ec1e9..58423167efc 100644
--- a/crates/git/src/repository.rs
+++ b/crates/git/src/repository.rs
@@ -909,9 +909,14 @@ pub trait GitRepository: Send + Sync {
env: Arc<HashMap<String, String>>,
) -> BoxFuture<'_, Result<()>>;
+ /// Restores `paths` in the working tree.
+ ///
+ /// With `Some(commit)`, both the index and the working tree are reset to the
+ /// commit's version, discarding staged and unstaged changes. With `None`, only
+ /// the working tree is restored from the index, so staged changes are kept.
fn checkout_files(
&self,
- commit: String,
+ commit: Option<String>,
paths: Vec<RepoPath>,
env: Arc<HashMap<String, String>>,
) -> BoxFuture<'_, Result<()>>;
@@ -1601,7 +1606,7 @@ impl GitRepository for RealGitRepository {
fn checkout_files(
&self,
- commit: String,
+ commit: Option<String>,
paths: Vec<RepoPath>,
env: Arc<HashMap<String, String>>,
) -> BoxFuture<'_, Result<()>> {
@@ -1612,8 +1617,12 @@ impl GitRepository for RealGitRepository {
return Ok(());
}
+ let mut args = vec!["checkout"];
+ args.extend(commit.as_deref());
+ args.push("--");
+
let output = git
- .build_command(&["checkout", &commit, "--"])
+ .build_command(&args)
.envs(env.iter())
.args(paths.iter().map(|path| path.as_unix_str()))
.output()
@@ -4539,6 +4548,51 @@ mod tests {
);
}
+ #[gpui::test]
+ async fn test_checkout_files_from_index_keeps_staged_changes(cx: &mut TestAppContext) {
+ disable_git_global_config();
+ cx.executor().allow_parking();
+
+ let repo_dir = tempfile::tempdir().unwrap();
+ git_init_repo(repo_dir.path());
+ let file_path = repo_dir.path().join("file.txt");
+ fs::write(&file_path, "head\n").unwrap();
+ git_command(repo_dir.path(), ["add", "file.txt"]);
+ git_command(repo_dir.path(), ["commit", "-m", "head"]);
+ fs::write(&file_path, "staged\n").unwrap();
+ git_command(repo_dir.path(), ["add", "file.txt"]);
+ fs::write(&file_path, "unstaged\n").unwrap();
+
+ let repository = RealGitRepository::new(
+ &repo_dir.path().join(".git"),
+ None,
+ Some("git".into()),
+ cx.executor(),
+ )
+ .unwrap();
+ let paths = vec![RepoPath::new("file.txt").unwrap()];
+
+ repository
+ .checkout_files(None, paths.clone(), Arc::default())
+ .await
+ .unwrap();
+ assert_eq!(fs::read_to_string(&file_path).unwrap(), "staged\n");
+ assert_eq!(
+ git_command_output(repo_dir.path(), ["show", ":file.txt"]),
+ "staged"
+ );
+
+ repository
+ .checkout_files(Some("HEAD".into()), paths, Arc::default())
+ .await
+ .unwrap();
+ assert_eq!(fs::read_to_string(&file_path).unwrap(), "head\n");
+ assert_eq!(
+ git_command_output(repo_dir.path(), ["show", ":file.txt"]),
+ "head"
+ );
+ }
+
#[gpui::test]
async fn test_merge_base_worktree_diff_handles_committed_deletion_recreated_on_disk(
cx: &mut TestAppContext,
diff --git a/crates/git_ui/src/git_panel.rs b/crates/git_ui/src/git_panel.rs
index 28df7ea3650..0101070516c 100644
--- a/crates/git_ui/src/git_panel.rs
+++ b/crates/git_ui/src/git_panel.rs
@@ -304,6 +304,7 @@ fn git_panel_context_menu(
has_staged_changes: bool,
has_unstaged_changes: bool,
has_new_changes: bool,
+ has_untracked_files: bool,
has_stash_items: bool,
group_by: GitPanelGroupBy,
include_copy_paths: bool,
@@ -358,7 +359,7 @@ fn git_panel_context_menu(
RestoreTrackedFiles.boxed_clone(),
)
.action_disabled_when(
- !has_new_changes,
+ !has_untracked_files,
"Trash Untracked Files",
TrashUntrackedFiles.boxed_clone(),
)
@@ -582,6 +583,14 @@ enum CommitHistory {
Error(SharedString),
}
+/// Discarding only unstaged changes leaves the index alone, so such an op says
+/// nothing about whether the file is staged.
+fn last_op_keeps_staged_changes(ops: &pending_op::PendingOps) -> bool {
+ ops.ops
+ .last()
+ .is_some_and(|op| op.git_status == pending_op::GitStatus::RevertedUnstaged)
+}
+
fn commit_history_from_response(
entries: Rc<[CommitHistoryEntry]>,
is_loading: bool,
@@ -618,6 +627,39 @@ struct ProjectedChangeEntry {
index: usize,
}
+/// Which changes discarding a file removes.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+enum DiscardScope {
+ /// Unstage and restore from `HEAD`, dropping staged and unstaged changes.
+ All,
+ /// Restore the working tree from the index, keeping staged changes.
+ Unstaged,
+}
+
+/// A file to discard and which of its changes to drop.
+#[derive(Debug, Clone)]
+struct DiscardTarget {
+ entry: GitStatusEntry,
+ scope: DiscardScope,
+}
+
+impl DiscardTarget {
+ fn new(entry: GitStatusEntry, scope: DiscardScope) -> Self {
+ Self { entry, scope }
+ }
+
+ fn keeps_staged_changes(&self) -> bool {
+ self.scope == DiscardScope::Unstaged && self.entry.status.staging().has_staged()
+ }
+
+ /// Whether discarding leaves nothing to restore, so the file is trashed.
+ /// A newly added file still has its staged version when only unstaged
+ /// changes are discarded.
+ fn is_trashed(&self) -> bool {
+ self.entry.status.is_created() && !self.keeps_staged_changes()
+ }
+}
+
/// What clicking a staging control should do.
///
/// In the "staged & unstaged" grouping, a partially staged file appears in both the
@@ -762,10 +804,10 @@ impl GitListEntry {
}
}
-/// The identity a row contributes to the multi-selection: files select by
-/// repo path, directories select as a unit covering their descendants.
+/// The identity a row contributes to the multi-selection: files select their
+/// own row, directories select as a unit covering their descendants.
enum RowMark {
- File(RepoPath),
+ File(TreeKey),
Directory(TreeKey),
}
@@ -783,7 +825,7 @@ enum SelectionTargetKind {
/// reversing direction shrinks the range instead of growing it.
struct MarkRangeGesture {
anchor_ix: usize,
- base_files: HashSet<RepoPath>,
+ base_files: HashSet<TreeKey>,
base_directories: HashSet<TreeKey>,
}
@@ -1004,6 +1046,8 @@ struct GitTreeStatusEntry {
depth: usize,
}
+/// Identifies a row by section and path. A partially staged file has a row in
+/// both the "Staged" and "Unstaged" sections, so marks are keyed by both.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
struct TreeKey {
section: Section,
@@ -1160,7 +1204,7 @@ pub struct GitPanel {
scroll_handle: UniformListScrollHandle,
max_width_item_index: Option<usize>,
selected_entry: Option<usize>,
- marked_entries: HashSet<RepoPath>,
+ marked_entries: HashSet<TreeKey>,
marked_directories: HashSet<TreeKey>,
mark_range_gesture: Option<MarkRangeGesture>,
tracked_count: usize,
@@ -1566,10 +1610,25 @@ impl GitPanel {
cx.notify();
}
+ fn file_row_key(&self, ix: usize) -> Option<TreeKey> {
+ let path = &self.entries.get(ix)?.status_entry()?.repo_path;
+ let section = self
+ .projected_entries_by_path
+ .get(path)?
+ .iter()
+ .find(|entry| entry.index == ix)?
+ .section;
+ Some(TreeKey {
+ section,
+ path: path.clone(),
+ })
+ }
+
fn row_mark(&self, ix: usize) -> Option<RowMark> {
match self.entries.get(ix)? {
- GitListEntry::Status(entry) => Some(RowMark::File(entry.repo_path.clone())),
- GitListEntry::TreeStatus(entry) => Some(RowMark::File(entry.entry.repo_path.clone())),
+ GitListEntry::Status(_) | GitListEntry::TreeStatus(_) => {
+ self.file_row_key(ix).map(RowMark::File)
+ }
GitListEntry::Directory(directory) => Some(RowMark::Directory(directory.key.clone())),
GitListEntry::Header(_) => None,
GitListEntry::EmptySection(_) => None,
@@ -1578,8 +1637,8 @@ impl GitPanel {
fn mark_row(&mut self, ix: usize) {
match self.row_mark(ix) {
- Some(RowMark::File(path)) => {
- self.marked_entries.insert(path);
+ Some(RowMark::File(key)) => {
+ self.marked_entries.insert(key);
}
Some(RowMark::Directory(key)) => {
self.marked_directories.insert(key);
@@ -1597,9 +1656,9 @@ impl GitPanel {
self.mark_row(previous);
}
match mark {
- RowMark::File(path) => {
- if !self.marked_entries.remove(&path) {
- self.marked_entries.insert(path);
+ RowMark::File(key) => {
+ if !self.marked_entries.remove(&key) {
+ self.marked_entries.insert(key);
}
}
RowMark::Directory(key) => {
@@ -1650,10 +1709,10 @@ impl GitPanel {
let mut coverage = MarkedDirectoryCoverage::default();
let mut marked = Vec::new();
let mut seen_paths = HashSet::default();
- for entry in &self.entries {
+ for (index, entry) in self.entries.iter().enumerate() {
let covered = coverage.observe(entry, &self.marked_directories);
if let Some(status_entry) = entry.status_entry()
- && (covered || self.marked_entries.contains(&status_entry.repo_path))
+ && (covered || self.row_is_marked(index))
&& seen_paths.insert(status_entry.repo_path.clone())
{
marked.push(status_entry.clone());
@@ -1754,12 +1813,11 @@ impl GitPanel {
/// Checks whether the entry at `index` is explicitly marked.
fn row_is_marked(&self, index: usize) -> bool {
- self.entries.get(index).is_some_and(|entry| match entry {
- GitListEntry::Status(entry) => self.marked_entries.contains(&entry.repo_path),
- GitListEntry::TreeStatus(entry) => self.marked_entries.contains(&entry.entry.repo_path),
- GitListEntry::Directory(entry) => self.marked_directories.contains(&entry.key),
- GitListEntry::Header(_) | GitListEntry::EmptySection(_) => false,
- })
+ match self.row_mark(index) {
+ Some(RowMark::File(key)) => self.marked_entries.contains(&key),
+ Some(RowMark::Directory(key)) => self.marked_directories.contains(&key),
+ None => false,
+ }
}
/// The entries a file operation should act on: the marked set when a
@@ -1801,7 +1859,7 @@ impl GitPanel {
let selected_is_marked = selected_index
.and_then(|index| self.row_mark(index))
.is_some_and(|mark| match mark {
- RowMark::File(path) => self.marked_entries.contains(&path),
+ RowMark::File(key) => self.marked_entries.contains(&key),
RowMark::Directory(key) => self.marked_directories.contains(&key),
});
let mark_count = self.marked_entries.len() + self.marked_directories.len();
@@ -1814,7 +1872,7 @@ impl GitPanel {
let mut seen_paths = HashSet::default();
for (index, entry) in self.entries.iter().enumerate() {
let marked = match self.row_mark(index) {
- Some(RowMark::File(path)) => self.marked_entries.contains(&path),
+ Some(RowMark::File(key)) => self.marked_entries.contains(&key),
Some(RowMark::Directory(key)) => self.marked_directories.contains(&key),
None => false,
};
@@ -2527,6 +2585,11 @@ impl GitPanel {
.unique_by(|entry| entry.repo_path.clone())
}
+ fn has_untracked_files(&self) -> bool {
+ self.change_entries_by_path()
+ .any(|entry| entry.status.is_untracked())
+ }
+
fn directory_descendants(&self, entry_index: usize) -> Option<&[GitStatusEntry]> {
let GitListEntry::Directory(directory) = self.entries.get(entry_index)? else {
return None;
@@ -2777,8 +2840,68 @@ impl GitPanel {
window: &mut Window,
cx: &mut Context<Self>,
) {
- let entries = self.effective_status_entries();
- self.revert_entries(entries, action.skip_prompt, window, cx);
+ let targets = self.discard_targets();
+ self.revert_entries(targets, action.skip_prompt, window, cx);
+ }
+
+ /// The files a discard acts on, mirroring `effective_status_entries`.
+ ///
+ /// A partially staged file has a row in both the "Staged" and "Unstaged"
+ /// sections; discarding through its "Unstaged" row keeps the staged half.
+ fn discard_targets(&self) -> Vec<DiscardTarget> {
+ let section_scope = |section: Option<Section>| {
+ if section == Some(Section::Unstaged) {
+ DiscardScope::Unstaged
+ } else {
+ DiscardScope::All
+ }
+ };
+
+ if self.use_selected_entry() {
+ let scope = section_scope(
+ self.selected_entry
+ .and_then(|index| self.section_for_entry_index(index)),
+ );
+ return self
+ .effective_status_entries()
+ .into_iter()
+ .map(|entry| DiscardTarget::new(entry, scope))
+ .collect();
+ }
+
+ let mut targets: Vec<DiscardTarget> = Vec::new();
+ let mut target_index_by_path: HashMap<RepoPath, usize> = HashMap::default();
+ let mut coverage = MarkedDirectoryCoverage::default();
+ let mut section = None;
+ for (index, entry) in self.entries.iter().enumerate() {
+ if let GitListEntry::Header(header) = entry {
+ section = Some(header.header);
+ }
+ let covered = coverage.observe(entry, &self.marked_directories);
+ let Some(status_entry) = entry.status_entry() else {
+ continue;
+ };
+ if !covered && !self.row_is_marked(index) {
+ continue;
+ }
+
+ // A file selected in both sections loses its whole diff.
+ let scope = section_scope(section);
+ match target_index_by_path.get(&status_entry.repo_path) {
+ Some(&index) => {
+ if scope == DiscardScope::All
+ && let Some(target) = targets.get_mut(index)
+ {
+ target.scope = DiscardScope::All;
+ }
+ }
+ None => {
+ target_index_by_path.insert(status_entry.repo_path.clone(), targets.len());
+ targets.push(DiscardTarget::new(status_entry.clone(), scope));
+ }
+ }
+ }
+ targets
}
/// Returns the repo path and whether it represents a directory for the
@@ -2898,12 +3021,12 @@ impl GitPanel {
fn revert_entries(
&mut self,
- entries: Vec<GitStatusEntry>,
+ targets: Vec<DiscardTarget>,
skip_prompt: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
- if entries.is_empty() {
+ if targets.is_empty() {
return;
}
@@ -2912,28 +3035,49 @@ impl GitPanel {
let workspace = self.workspace.clone();
let path_style = self.project.read(cx).path_style(cx);
- let staged = entries
+ let staged = targets
.iter()
- .filter(|entry| entry.status.staging().has_staged())
- .cloned()
+ .filter(|target| {
+ target.scope == DiscardScope::All && target.entry.status.staging().has_staged()
+ })
+ .map(|target| target.entry.clone())
.collect::<Vec<_>>();
- let (tracked, untracked): (Vec<_>, Vec<_>) = entries
+ let (untracked, tracked): (Vec<_>, Vec<_>) =
+ targets.into_iter().partition(DiscardTarget::is_trashed);
+ let untracked = untracked
.into_iter()
- .partition(|entry| !entry.status.is_created());
+ .map(|target| target.entry)
+ .collect::<Vec<_>>();
+
+ let changes = if tracked
+ .iter()
+ .all(|target| target.scope == DiscardScope::Unstaged)
+ && tracked.iter().any(DiscardTarget::keeps_staged_changes)
+ {
+ "unstaged changes"
+ } else {
+ "changes"
+ };
let prompt = if skip_prompt {
None
} else if tracked.len() + untracked.len() == 1 {
- let entry = tracked.first().or_else(|| untracked.first())?;
+ let (entry, is_trashed) = tracked
+ .first()
+ .map(|target| (&target.entry, false))
+ .or_else(|| untracked.first().map(|entry| (entry, true)))?;
let (message, confirm_text) = if entry.status.is_deleted() {
- ("Are you sure you want to restore ", "Restore File")
- } else if entry.status.is_created() {
- ("Trash ", "Trash")
+ (
+ "Are you sure you want to restore ".to_string(),
+ "Restore File",
+ )
+ } else if is_trashed {
+ ("Trash ".to_string(), "Trash")
} else {
(
- "Are you sure you want to discard changes to ",
+ format!("Are you sure you want to discard {changes} to "),
"Discard Changes",
)
};
@@ -2958,13 +3102,13 @@ impl GitPanel {
let (message, confirm_text) = match (tracked.len(), untracked.len()) {
(0, 0) => return Some(()),
(tracked_count, 0) => (
- format!("Discard changes to {tracked_count} files?"),
+ format!("Discard {changes} to {tracked_count} files?"),
"Discard",
),
(0, untracked_count) => (format!("Trash {untracked_count} files?"), "Trash"),
(tracked_count, untracked_count) => (
format!(
- "Discard changes to {tracked_count} files and trash {untracked_count} files?"
+ "Discard {changes} to {tracked_count} files and trash {untracked_count} files?"
),
"Discard and Trash",
),
@@ -3035,7 +3179,7 @@ impl GitPanel {
fn perform_checkout(
&mut self,
- entries: Vec<GitStatusEntry>,
+ targets: Vec<DiscardTarget>,
window: &mut Window,
cx: &mut Context<Self>,
) {
@@ -3047,12 +3191,12 @@ impl GitPanel {
let task = cx.spawn_in(window, async move |this, cx| {
let tasks: Vec<_> = workspace.update(cx, |workspace, cx| {
workspace.project().update(cx, |project, cx| {
- entries
+ targets
.iter()
- .filter_map(|entry| {
+ .filter_map(|target| {
let path = active_repository
.read(cx)
- .repo_path_to_project_path(&entry.repo_path, cx)?;
+ .repo_path_to_project_path(&target.entry.repo_path, cx)?;
Some(project.open_buffer(path, cx))
})
.collect()
@@ -3061,22 +3205,36 @@ impl GitPanel {
let buffers = futures::future::join_all(tasks).await;
- this.update_in(cx, |this, window, cx| {
- let task = active_repository.update(cx, |repo, cx| {
- repo.checkout_files(
- "HEAD",
- entries
- .into_iter()
- .map(|entries| entries.repo_path)
- .collect(),
- cx,
- )
+ let (unstaged_targets, all_targets): (Vec<_>, Vec<_>) = targets
+ .into_iter()
+ .partition(|target| target.scope == DiscardScope::Unstaged);
+ let checkouts = this.update_in(cx, |this, window, cx| {
+ let checkouts = active_repository.update(cx, |repo, cx| {
+ [(Some("HEAD"), all_targets), (None, unstaged_targets)]
+ .into_iter()
+ .filter(|(_, targets)| !targets.is_empty())
+ .map(|(commit, targets)| {
+ repo.checkout_files(
+ commit,
+ targets
+ .into_iter()
+ .map(|target| target.entry.repo_path)
+ .collect(),
+ cx,
+ )
+ })
+ .collect::<Vec<_>>()
});
this.update_visible_entries(window, cx);
cx.notify();
- task
- })?
- .await?;
+ checkouts
+ })?;
+ // Dropping a checkout task cancels it and leaves its pending op
+ // running, so wait for both before reporting the first error.
+ futures::future::join_all(checkouts)
+ .await
+ .into_iter()
+ .collect::<Result<Vec<_>, _>>()?;
let tasks: Vec<_> = cx.update(|_, cx| {
buffers
@@ -3122,7 +3280,11 @@ impl GitPanel {
match entries.len() {
0 => return,
1 => {
- return self.revert_entries(entries, false, window, cx);
+ let targets = entries
+ .into_iter()
+ .map(|entry| DiscardTarget::new(entry, DiscardScope::All))
+ .collect();
+ return self.revert_entries(targets, false, window, cx);
}
_ => {}
}
@@ -3151,7 +3313,11 @@ impl GitPanel {
cx.spawn_in(window, async move |this, cx| {
if let Ok(RestoreCancel::RestoreTrackedFiles) = prompt.await {
this.update_in(cx, |this, window, cx| {
- this.perform_checkout(entries, window, cx);
+ let targets = entries
+ .into_iter()
+ .map(|entry| DiscardTarget::new(entry, DiscardScope::All))
+ .collect();
+ this.perform_checkout(targets, window, cx);
})
.ok();
}
@@ -3164,16 +3330,22 @@ impl GitPanel {
let Some(active_repo) = self.active_repository.clone() else {
return;
};
+ // Files added to the index are not untracked; trashing them would also
+ // discard their staged contents.
let to_delete = self
.change_entries_by_path()
- .filter(|status_entry| status_entry.status.is_created())
+ .filter(|status_entry| status_entry.status.is_untracked())
.cloned()
.collect::<Vec<_>>();
match to_delete.len() {
0 => return,
1 => {
- return self.revert_entries(to_delete, false, window, cx);
+ let targets = to_delete
+ .into_iter()
+ .map(|entry| DiscardTarget::new(entry, DiscardScope::All))
+ .collect();
+ return self.revert_entries(targets, false, window, cx);
}
_ => {}
};
@@ -3196,7 +3368,7 @@ impl GitPanel {
}
let prompt = prompt("Trash these files?", Some(&details), window, cx);
- cx.spawn_in(window, async move |this, cx| {
+ cx.spawn_in(window, async move |_, cx| {
match prompt.await? {
TrashCancel::Trash => {}
TrashCancel::Cancel => return Ok(()),
@@ -3215,11 +3387,6 @@ impl GitPanel {
.collect::<Vec<_>>()
})?;
let total_count = tasks.len();
- let to_unstage = to_delete
- .into_iter()
- .filter(|entry| !entry.status.staging().is_fully_unstaged())
- .collect();
- this.update(cx, |this, cx| this.change_file_stage(false, to_unstage, cx))?;
let results = futures::future::join_all(tasks).await;
let errors: Vec<anyhow::Error> = results.into_iter().filter_map(|r| r.err()).collect();
@@ -3280,7 +3447,7 @@ impl GitPanel {
// In case the last operation in the list of pending operations
// failed, we can't assume the stage status for this entry and
// need to fallback to the actual state in the repo.
- if ops.last_op_errored() {
+ if ops.last_op_errored() || last_op_keeps_staged_changes(&ops) {
return None;
}
@@ -5567,11 +5734,19 @@ impl GitPanel {
let is_new = status_entry.status.is_created();
let staging = status_entry.status.staging();
- if let Some(pending) = repo.pending_ops_for_path(&status_entry.repo_path)
- && pending
- .ops
- .iter()
- .any(|op| op.git_status == pending_op::GitStatus::Reverted && op.finished())
+ let pending_ops = repo.pending_ops_for_path(&status_entry.repo_path);
+ let finished_revert = |git_status| {
+ pending_ops.as_ref().is_some_and(|pending| {
+ pending
+ .ops
+ .iter()
+ .any(|op| op.git_status == git_status && op.finished())
+ })
+ };
+ // Hide discarded changes until the next status scan confirms them.
+ let unstaged_reverted = finished_revert(pending_op::GitStatus::RevertedUnstaged);
+ if finished_revert(pending_op::GitStatus::Reverted)
+ || (unstaged_reverted && !staging.has_staged())
{
continue;
}
@@ -5601,7 +5776,7 @@ impl GitPanel {
..entry.clone()
});
}
- if staging.has_unstaged() {
+ if staging.has_unstaged() && !unstaged_reverted {
unstaged_entries.push(GitStatusEntry {
diff_stat: status_entry.unstaged_diff_stat,
..entry
@@ -5845,14 +6020,10 @@ impl GitPanel {
GitPanelViewMode::Flat => self.marked_directories.clear(),
}
if !self.marked_entries.is_empty() {
- let present_paths: HashSet<RepoPath> = self
- .entries
- .iter()
- .filter_map(|entry| entry.status_entry())
- .map(|entry| entry.repo_path.clone())
+ let present_rows: HashSet<TreeKey> = (0..self.entries.len())
+ .filter_map(|index| self.file_row_key(index))
.collect();
- self.marked_entries
- .retain(|path| present_paths.contains(path));
+ self.marked_entries.retain(|key| present_rows.contains(key));
}
// The rebuild may have reordered rows, invalidating the anchor index.
self.mark_range_gesture = None;
@@ -6600,6 +6771,7 @@ impl GitPanel {
let has_staged_changes = self.has_staged_changes();
let has_unstaged_changes = self.has_unstaged_changes();
let has_new_changes = self.new_count > 0;
+ let has_untracked_files = self.has_untracked_files();
let has_stash_items = self.stash_entries.entries.len() > 0;
let group_by = GitPanelSettings::get_global(cx).group_by;
@@ -6619,6 +6791,7 @@ impl GitPanel {
has_staged_changes,
has_unstaged_changes,
has_new_changes,
+ has_untracked_files,
has_stash_items,
group_by,
false,
@@ -8007,6 +8180,7 @@ impl GitPanel {
let is_staging_or_staged = repo
.pending_ops_for_path(&repo_path)
+ .filter(|ops| !last_op_keeps_staged_changes(ops))
.map(|ops| !ops.last_op_errored() && (ops.staging() || ops.staged()))
.or_else(|| {
repo.status_for_path(&repo_path)
@@ -8343,6 +8517,7 @@ impl GitPanel {
&self,
will_unstage: bool,
all_created: bool,
+ all_trashed: bool,
all_deleted: bool,
file_count: usize,
target_kind: SelectionTargetKind,
@@ -8367,7 +8542,7 @@ impl GitPanel {
(SelectionTargetKind::Multiple, false) => &format!("Stage {file_count} {file_label}"),
};
- let restore_title = match (target_kind, all_created, all_deleted) {
+ let restore_title = match (target_kind, all_trashed, all_deleted) {
(SelectionTargetKind::Directory, true, _) => "Trash Folder",
(SelectionTargetKind::Directory, false, _) => "Discard Changes",
(SelectionTargetKind::File, true, _) => "Trash File",
@@ -8474,11 +8649,14 @@ impl GitPanel {
let all_created = entries.iter().all(|entry| entry.status.is_created());
let all_deleted = entries.iter().all(|entry| entry.status.is_deleted());
let will_unstage = self.should_unstage(target_kind, &entries, cx);
+ let discard_targets = self.discard_targets();
+ let all_trashed = discard_targets.iter().all(DiscardTarget::is_trashed);
self.set_context_menu(
self.build_context_menu(
will_unstage,
all_created,
+ all_trashed,
all_deleted,
entries.len(),
target_kind,
@@ -8505,6 +8683,7 @@ impl GitPanel {
let has_staged_changes = self.has_staged_changes();
let has_unstaged_changes = self.has_unstaged_changes();
let has_new_changes = self.new_count > 0;
+ let has_untracked_files = self.has_untracked_files();
let has_staged_tracked_changes = target_entry_index
.and_then(|entry_index| self.directory_descendants(entry_index))
.map_or_else(
@@ -8518,6 +8697,7 @@ impl GitPanel {
has_staged_changes,
has_unstaged_changes,
has_new_changes,
+ has_untracked_files,
has_stash_items,
GitPanelSettings::get_global(cx).group_by,
include_copy_paths,
@@ -8584,7 +8764,7 @@ impl GitPanel {
let display_name = entry.display_name(path_style);
let selected = self.selected_entry == Some(ix);
- let marked = self.marked_entries.contains(&entry.repo_path);
+ let marked = self.row_is_marked(ix);
let status_style = settings.status_style;
let status = entry.status;
let file_icon = if settings.file_icons {
@@ -10196,6 +10376,33 @@ mod tests {
})
}
+ /// Marks the first row of `path`.
+ fn mark_file(panel: &mut GitPanel, path: &str) {
+ let index = entry_index_for_repo_path(panel, &repo_path(path))
+ .unwrap_or_else(|| panic!("{path} should have a row"));
+ mark_file_row(panel, index);
+ }
+
+ fn mark_file_in_section(panel: &mut GitPanel, path: &str, section: Section) {
+ let index = panel
+ .entry_by_path_in_section(&repo_path(path), section)
+ .unwrap_or_else(|| panic!("{path} should have a row in {section:?}"));
+ mark_file_row(panel, index);
+ }
+
+ fn mark_file_row(panel: &mut GitPanel, index: usize) {
+ let key = panel.file_row_key(index).expect("row should be a file row");
+ panel.marked_entries.insert(key);
+ }
+
+ fn marked_paths(panel: &GitPanel) -> HashSet<RepoPath> {
+ panel
+ .marked_entries
+ .iter()
+ .map(|key| key.path.clone())
+ .collect()
+ }
+
fn directory_index_for_repo_path(panel: &GitPanel, repo_path: &RepoPath) -> Option<usize> {
panel.entries.iter().position(|entry| {
entry
@@ -10584,7 +10791,8 @@ mod tests {
panel.update_in(&mut cx, |panel, window, cx| {
panel.selected_entry = entry_index_for_repo_path(panel, &repo_path("b.txt"));
- panel.marked_entries = HashSet::from_iter([repo_path("a.txt"), repo_path("b.txt")]);
+ mark_file(panel, "a.txt");
+ mark_file(panel, "b.txt");
panel.copy_relative_path(&CopyRelativePath, window, cx);
assert_eq!(
cx.read_from_clipboard().and_then(|item| item.text()),
@@ -10649,8 +10857,8 @@ mod tests {
panel.update_in(&mut cx, |panel, window, cx| {
panel.selected_entry = entry_index_for_repo_path(panel, &repo_path("new1.txt"));
- panel.marked_entries =
- HashSet::from_iter([repo_path("new1.txt"), repo_path("new2.txt")]);
+ mark_file(panel, "new1.txt");
+ mark_file(panel, "new2.txt");
panel.add_to_gitignore(&git::AddToGitignore, window, cx);
panel.add_to_git_info_exclude(&git::AddToGitInfoExclude, window, cx);
});
@@ -10753,7 +10961,7 @@ mod tests {
.key
.clone();
panel.marked_directories.insert(directory_key);
- panel.marked_entries.insert(repo_path("other.txt"));
+ mark_file(panel, "other.txt");
});
cx.dispatch_action(CopyRelativePath);
let copied_paths = cx
@@ -11965,9 +12173,8 @@ mod tests {
// section, we expect the menu to offer the ability to unstage the
// files.
let partial_path = repo_path("src/partial.rs");
- let staged_path = repo_path("src/staged.rs");
- panel.marked_entries.insert(partial_path.clone());
- panel.marked_entries.insert(staged_path);
+ mark_file_in_section(panel, "src/partial.rs", Section::Staged);
+ mark_file_in_section(panel, "src/staged.rs", Section::Staged);
panel.selected_entry = panel.entry_by_path_in_section(&partial_path, Section::Staged);
let entries = panel.effective_status_entries();
@@ -15379,6 +15586,247 @@ mod tests {
})
}
+ /// Creates a project with the given HEAD, index and working tree contents,
+ /// then opens the Git panel grouped by staging state.
+ async fn setup_git_panel_with_index_contents(
+ cx: &mut TestAppContext,
+ head: &[(&str, &str)],
+ index: &[(&str, &str)],
+ worktree: serde_json::Value,
+ ) -> (Arc<FakeFs>, Entity<GitPanel>, VisualTestContext) {
+ let fs = FakeFs::new(cx.background_executor.clone());
+ fs.insert_tree(path!("/project"), worktree).await;
+ let dot_git = Path::new(path!("/project/.git"));
+ fs.set_head_for_repo(
+ dot_git,
+ &head
+ .iter()
+ .map(|(path, content)| (*path, content.to_string()))
+ .collect::<Vec<_>>(),
+ "deadbeef",
+ );
+ fs.set_index_for_repo(
+ dot_git,
+ &index
+ .iter()
+ .map(|(path, content)| (*path, content.to_string()))
+ .collect::<Vec<_>>(),
+ );
+
+ cx.update(|cx| {
+ SettingsStore::update_global(cx, |store, cx| {
+ store.update_user_settings(cx, |settings| {
+ settings.git_panel.get_or_insert_default().group_by =
+ Some(GitPanelGroupBy::Staging);
+ })
+ });
+ });
+
+ let project = Project::test(fs.clone(), [Path::new(path!("/project"))], cx).await;
+ let window_handle =
+ cx.add_window(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx));
+ let workspace = window_handle
+ .read_with(cx, |mw, _| mw.workspace().clone())
+ .unwrap();
+ let mut cx = VisualTestContext::from_window(window_handle.into(), cx);
+ cx.executor().run_until_parked();
+
+ let panel = workspace.update_in(&mut cx, GitPanel::new);
+ await_git_panel_entries(&panel, &mut cx).await;
+ cx.run_until_parked();
+
+ (fs, panel, cx)
+ }
+
+ fn discard_row(
+ panel: &Entity<GitPanel>,
+ path: &str,
+ section: Section,
+ cx: &mut VisualTestContext,
+ ) {
+ panel.update_in(cx, |panel, window, cx| {
+ let index = panel
+ .entry_by_path_in_section(&repo_path(path), section)
+ .unwrap_or_else(|| panic!("{path} should have a row in {section:?}"));
+ panel.selected_entry = Some(index);
+ panel.revert_selected(&RestoreFile { skip_prompt: true }, window, cx);
+ });
+ cx.run_until_parked();
+ }
+
+ /// Returns the working tree and index contents of `path`.
+ async fn worktree_and_index(fs: &FakeFs, path: &str) -> (String, Option<String>) {
+ let worktree = fs
+ .load(&Path::new(path!("/project")).join(path))
+ .await
+ .unwrap();
+ let index = fs
+ .with_git_state(Path::new(path!("/project/.git")), false, |state| {
+ state
+ .index_contents
+ .get(&repo_path(path))
+ .map(|content| String::from_utf8_lossy(content).into_owned())
+ })
+ .unwrap();
+ (worktree, index)
+ }
+
+ #[gpui::test]
+ async fn test_discard_row_scope_follows_section(cx: &mut TestAppContext) {
+ init_test(cx);
+ let (fs, panel, mut cx) = setup_git_panel_with_index_contents(
+ cx,
+ &[("partial.txt", "head\n")],
+ &[("partial.txt", "staged\n"), ("added.txt", "staged\n")],
+ json!({
+ ".git": {},
+ "partial.txt": "unstaged\n",
+ "added.txt": "unstaged\n",
+ }),
+ )
+ .await;
+
+ // Discarding from the "Unstaged" section keeps the staged version, even
+ // for a newly added file.
+ discard_row(&panel, "partial.txt", Section::Unstaged, &mut cx);
+ discard_row(&panel, "added.txt", Section::Unstaged, &mut cx);
+ await_git_panel_entries(&panel, &mut cx).await;
+ for path in ["partial.txt", "added.txt"] {
+ assert_eq!(
+ worktree_and_index(&fs, path).await,
+ ("staged\n".into(), Some("staged\n".into())),
+ "{path}"
+ );
+ }
+
+ // Discarding from the "Staged" section restores HEAD.
+ discard_row(&panel, "partial.txt", Section::Staged, &mut cx);
+ await_git_panel_entries(&panel, &mut cx).await;
+ assert_eq!(
+ worktree_and_index(&fs, "partial.txt").await,
+ ("head\n".into(), Some("head\n".into()))
+ );
+ }
+
+ #[gpui::test]
+ async fn test_discard_untracked_file_in_unstaged_section_trashes_it(cx: &mut TestAppContext) {
+ init_test(cx);
+ let (fs, panel, mut cx) = setup_git_panel_with_index_contents(
+ cx,
+ &[],
+ &[],
+ json!({
+ ".git": {},
+ "untracked.txt": "untracked\n",
+ }),
+ )
+ .await;
+
+ discard_row(&panel, "untracked.txt", Section::Unstaged, &mut cx);
+
+ assert!(!fs.is_file(path!("/project/untracked.txt").as_ref()).await);
+ }
+
+ #[gpui::test]
+ async fn test_discard_unstaged_changes_keeps_staged_row_staged(cx: &mut TestAppContext) {
+ init_test(cx);
+ let (fs, panel, mut cx) = setup_git_panel_with_index_contents(
+ cx,
+ &[("partial.txt", "head\n")],
+ &[("partial.txt", "staged\n")],
+ json!({
+ ".git": {},
+ "partial.txt": "unstaged\n",
+ }),
+ )
+ .await;
+
+ // Hold back the status scan so the discard's pending op stays around.
+ fs.pause_events();
+ discard_row(&panel, "partial.txt", Section::Unstaged, &mut cx);
+ assert_eq!(
+ worktree_and_index(&fs, "partial.txt").await,
+ ("staged\n".into(), Some("staged\n".into()))
+ );
+
+ panel.update_in(&mut cx, |panel, window, cx| {
+ panel.update_visible_entries(window, cx);
+ let index = panel
+ .entry_by_path_in_section(&repo_path("partial.txt"), Section::Staged)
+ .expect("the staged row should stay");
+ let entry = panel.entries[index].status_entry().unwrap().clone();
+ let repo = panel.active_repository.as_ref().unwrap().read(cx);
+ assert!(GitPanel::stage_status_for_entry(&entry, repo).has_staged());
+ assert!(panel.has_staged_changes());
+ });
+
+ fs.unpause_events_and_flush();
+ await_git_panel_entries(&panel, &mut cx).await;
+ cx.run_until_parked();
+ panel.read_with(&cx, |panel, _| {
+ assert!(
+ panel
+ .entry_by_path_in_section(&repo_path("partial.txt"), Section::Unstaged)
+ .is_none()
+ );
+ assert!(panel.has_staged_changes());
+ });
+ }
+
+ #[gpui::test]
+ async fn test_discard_marked_rows_scope_follows_section(cx: &mut TestAppContext) {
+ init_test(cx);
+ let (fs, panel, mut cx) = setup_git_panel_with_index_contents(
+ cx,
+ &[
+ ("partial.txt", "head\n"),
+ ("both.txt", "head\n"),
+ ("staged.txt", "head\n"),
+ ],
+ &[
+ ("partial.txt", "staged\n"),
+ ("both.txt", "staged\n"),
+ ("staged.txt", "staged\n"),
+ ],
+ json!({
+ ".git": {},
+ "partial.txt": "unstaged\n",
+ "both.txt": "unstaged\n",
+ "staged.txt": "staged\n",
+ }),
+ )
+ .await;
+
+ panel.update_in(&mut cx, |panel, window, cx| {
+ mark_file_in_section(panel, "partial.txt", Section::Unstaged);
+ mark_file_in_section(panel, "both.txt", Section::Unstaged);
+ mark_file_in_section(panel, "both.txt", Section::Staged);
+ mark_file_in_section(panel, "staged.txt", Section::Staged);
+ let partial_staged_row = panel
+ .entry_by_path_in_section(&repo_path("partial.txt"), Section::Staged)
+ .unwrap();
+ assert!(!panel.row_is_marked(partial_staged_row));
+
+ panel.selected_entry =
+ panel.entry_by_path_in_section(&repo_path("partial.txt"), Section::Unstaged);
+ panel.revert_selected(&RestoreFile { skip_prompt: true }, window, cx);
+ });
+ cx.run_until_parked();
+ await_git_panel_entries(&panel, &mut cx).await;
+
+ assert_eq!(
+ worktree_and_index(&fs, "partial.txt").await,
+ ("staged\n".into(), Some("staged\n".into()))
+ );
+ for path in ["both.txt", "staged.txt"] {
+ assert_eq!(
+ worktree_and_index(&fs, path).await,
+ ("head\n".into(), Some("head\n".into())),
+ "{path}"
+ );
+ }
+ }
+
async fn setup_flat_marks_fixture(
cx: &mut TestAppContext,
) -> (
@@ -15481,7 +15929,7 @@ mod tests {
panel.mark_range(a_ix, new1_ix);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([
repo_path("a.txt"),
repo_path("b.txt"),
@@ -15494,7 +15942,7 @@ mod tests {
panel.marked_entries.clear();
panel.mark_range(new1_ix, a_ix);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([
repo_path("a.txt"),
repo_path("b.txt"),
@@ -15545,7 +15993,7 @@ mod tests {
panel.mark_range(0, panel.entries.len() - 1);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([
repo_path("src/a.rs"),
repo_path("src/b.rs"),
@@ -15570,7 +16018,7 @@ mod tests {
let top_ix = entry_index_for_repo_path(panel, &repo_path("top.txt")).unwrap();
panel.mark_range(src_ix, top_ix);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([repo_path("top.txt")]),
"files hidden in the collapsed directory are not marked individually",
);
@@ -15598,7 +16046,7 @@ mod tests {
.expect("collapsed entries should stay in the entry list");
panel.mark_range(hidden_ix, top_ix);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([repo_path("top.txt")]),
"an anchor hidden in a collapsed directory should mark the target only",
);
@@ -15613,7 +16061,7 @@ mod tests {
panel.update_in(&mut cx, |panel, _window, _cx| {
// A mark from before the gesture must survive the whole gesture.
- panel.marked_entries.insert(repo_path("new1.txt"));
+ mark_file(panel, "new1.txt");
let a_ix = entry_index_for_repo_path(panel, &repo_path("a.txt")).unwrap();
panel.selected_entry = Some(a_ix);
});
@@ -15626,7 +16074,7 @@ mod tests {
panel.select_next(&menu::SelectNext, window, cx);
panel.select_next(&menu::SelectNext, window, cx);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([
repo_path("a.txt"),
repo_path("b.txt"),
@@ -15638,7 +16086,7 @@ mod tests {
panel.select_previous(&menu::SelectPrevious, window, cx);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([
repo_path("a.txt"),
repo_path("b.txt"),
@@ -15649,7 +16097,7 @@ mod tests {
panel.select_previous(&menu::SelectPrevious, window, cx);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([repo_path("a.txt"), repo_path("new1.txt")]),
"shrinking to the anchor leaves only the anchor and prior marks",
);
@@ -15661,7 +16109,7 @@ mod tests {
panel.update_in(&mut cx, |panel, window, cx| {
panel.select_next(&menu::SelectNext, window, cx);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([repo_path("a.txt"), repo_path("new1.txt")]),
"plain navigation must not change the marks",
);
@@ -15673,7 +16121,7 @@ mod tests {
panel.update_in(&mut cx, |panel, window, cx| {
panel.select_next(&menu::SelectNext, window, cx);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([
repo_path("a.txt"),
repo_path("b.txt"),
@@ -15738,8 +16186,9 @@ mod tests {
})
.unwrap();
- panel.marked_entries =
- HashSet::from_iter([repo_path("src/a.rs"), repo_path("src/nested/c.rs")]);
+ panel.marked_entries.clear();
+ mark_file(panel, "src/a.rs");
+ mark_file(panel, "src/nested/c.rs");
assert_eq!(
panel.marked_directories,
HashSet::default(),
@@ -15764,7 +16213,7 @@ mod tests {
"operations expand a selected directory to its recursive descendants",
);
- panel.marked_entries.insert(repo_path("top.txt"));
+ mark_file(panel, "top.txt");
panel.toggle_mark(src_ix, cx);
assert_eq!(
panel.marked_directories,
@@ -15786,7 +16235,7 @@ mod tests {
panel.selected_entry = Some(a_ix);
panel.toggle_mark(b_ix, cx);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([repo_path("a.txt"), repo_path("b.txt")]),
"the first toggle should also mark the previously selected entry",
);
@@ -15794,7 +16243,7 @@ mod tests {
panel.toggle_mark(b_ix, cx);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([repo_path("a.txt")]),
"toggling a marked entry should unmark it",
);
@@ -15824,14 +16273,14 @@ mod tests {
"no marks: the selection acts alone",
);
- panel.marked_entries.insert(repo_path("b.txt"));
+ mark_file(panel, "b.txt");
assert_eq!(
paths(panel),
vec![repo_path("a.txt")],
"a single mark elsewhere should not override the selection",
);
- panel.marked_entries.insert(repo_path("c.txt"));
+ mark_file(panel, "c.txt");
assert_eq!(
paths(panel),
vec![repo_path("b.txt"), repo_path("c.txt")],
@@ -15879,8 +16328,8 @@ mod tests {
panel.update_in(&mut cx, |panel, window, cx| {
assert_eq!(staging_for(panel, &repo_path("a.txt")), StageStatus::Staged);
- panel.marked_entries.insert(repo_path("a.txt"));
- panel.marked_entries.insert(repo_path("b.txt"));
+ mark_file(panel, "a.txt");
+ mark_file(panel, "b.txt");
panel.selected_entry = entry_index_for_repo_path(panel, &repo_path("a.txt"));
panel.toggle_staged_for_selected(&git::ToggleStaged, window, cx);
});
@@ -15917,8 +16366,8 @@ mod tests {
let (fs, project, panel, mut cx) = setup_flat_marks_fixture(cx).await;
panel.update_in(&mut cx, |panel, _window, _cx| {
- panel.marked_entries.insert(repo_path("a.txt"));
- panel.marked_entries.insert(repo_path("b.txt"));
+ mark_file(panel, "a.txt");
+ mark_file(panel, "b.txt");
});
fs.set_status_for_repo(
@@ -15934,7 +16383,7 @@ mod tests {
panel.read_with(&cx, |panel, _| {
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([repo_path("b.txt")]),
"marks for entries that left the list should be pruned",
);
@@ -15947,8 +16396,8 @@ mod tests {
let (_fs, _project, panel, mut cx) = setup_flat_marks_fixture(cx).await;
panel.update_in(&mut cx, |panel, _window, cx| {
- panel.marked_entries.insert(repo_path("a.txt"));
- panel.marked_entries.insert(repo_path("b.txt"));
+ mark_file(panel, "a.txt");
+ mark_file(panel, "b.txt");
let c_ix = entry_index_for_repo_path(panel, &repo_path("c.txt")).unwrap();
panel.clear_marks_and_select(c_ix, cx);
@@ -15981,7 +16430,7 @@ mod tests {
panel.read_with(&cx, |panel, _| {
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([repo_path("a.txt"), repo_path("b.txt")]),
"shift+down should mark the origin and the destination",
);
@@ -15996,8 +16445,8 @@ mod tests {
let (fs, _project, panel, mut cx) = setup_flat_marks_fixture(cx).await;
panel.update_in(&mut cx, |panel, window, cx| {
- panel.marked_entries.insert(repo_path("a.txt"));
- panel.marked_entries.insert(repo_path("new1.txt"));
+ mark_file(panel, "a.txt");
+ mark_file(panel, "new1.txt");
panel.selected_entry = entry_index_for_repo_path(panel, &repo_path("a.txt"));
panel.revert_selected(&git::RestoreFile::default(), window, cx);
});
@@ -16064,8 +16513,8 @@ mod tests {
await_git_panel_entries(&panel, &mut cx).await;
panel.update_in(&mut cx, |panel, window, cx| {
- panel.marked_entries.insert(repo_path("new1.txt"));
- panel.marked_entries.insert(repo_path("new2.txt"));
+ mark_file(panel, "new1.txt");
+ mark_file(panel, "new2.txt");
panel.selected_entry = entry_index_for_repo_path(panel, &repo_path("new1.txt"));
panel.revert_selected(&git::RestoreFile::default(), window, cx);
});
@@ -16081,14 +16530,43 @@ mod tests {
assert!(!fs.is_file(path!("/project/new2.txt").as_ref()).await);
}
+ #[gpui::test]
+ async fn test_trash_untracked_files_keeps_added_files(cx: &mut TestAppContext) {
+ init_test(cx);
+ let (fs, panel, mut cx) = setup_git_panel_with_index_contents(
+ cx,
+ &[],
+ &[("added.txt", "staged\n")],
+ json!({
+ ".git": {},
+ "added.txt": "unstaged\n",
+ "untracked.txt": "untracked\n",
+ }),
+ )
+ .await;
+
+ panel.update_in(&mut cx, |panel, window, cx| {
+ panel.clean_all(&TrashUntrackedFiles, window, cx);
+ });
+ assert!(cx.has_pending_prompt());
+ cx.simulate_prompt_answer("Trash");
+ cx.executor().run_until_parked();
+
+ assert!(!fs.is_file(path!("/project/untracked.txt").as_ref()).await);
+ assert_eq!(
+ worktree_and_index(&fs, "added.txt").await,
+ ("unstaged\n".into(), Some("staged\n".into()))
+ );
+ }
+
#[gpui::test]
async fn test_stage_and_unstage_actions_apply_to_marks(cx: &mut TestAppContext) {
init_test(cx);
let (_fs, project, panel, mut cx) = setup_flat_marks_fixture(cx).await;
panel.update_in(&mut cx, |panel, window, cx| {
- panel.marked_entries.insert(repo_path("a.txt"));
- panel.marked_entries.insert(repo_path("b.txt"));
+ mark_file(panel, "a.txt");
+ mark_file(panel, "b.txt");
panel.selected_entry = entry_index_for_repo_path(panel, &repo_path("a.txt"));
panel.stage_selected(&git::StageFile, window, cx);
});
@@ -16125,8 +16603,8 @@ mod tests {
let (_fs, _project, panel, mut cx) = setup_flat_marks_fixture(cx).await;
panel.update_in(&mut cx, |panel, window, cx| {
- panel.marked_entries.insert(repo_path("a.txt"));
- panel.marked_entries.insert(repo_path("b.txt"));
+ mark_file(panel, "a.txt");
+ mark_file(panel, "b.txt");
panel.cancel(&menu::Cancel, window, cx);
assert!(
@@ -16135,10 +16613,10 @@ mod tests {
);
panel.active_tab = GitPanelTab::History;
- panel.marked_entries.insert(repo_path("a.txt"));
+ mark_file(panel, "a.txt");
panel.cancel(&menu::Cancel, window, cx);
assert_eq!(
- panel.marked_entries,
+ marked_paths(panel),
HashSet::from_iter([repo_path("a.txt")]),
"cancel on the history tab should leave changes-tab marks alone",
);
@@ -16217,7 +16695,7 @@ mod tests {
entry_index_for_repo_path(panel, &repo_path("x.txt")).is_some(),
"repo A should list x.txt",
);
- panel.marked_entries.insert(repo_path("x.txt"));
+ mark_file(panel, "x.txt");
});
repository_b.update(&mut cx, |repository, cx| {
diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rs
index 3ee7cf58e55..16d07793ec0 100644
--- a/crates/project/src/git_store.rs
+++ b/crates/project/src/git_store.rs
@@ -4644,10 +4644,11 @@ impl GitStore {
.iter()
.map(|s| RepoPath::from_proto(s))
.collect::<Result<Vec<_>>>()?;
+ let commit = Some(envelope.payload.commit.as_str()).filter(|commit| !commit.is_empty());
repository_handle
.update(&mut cx, |repository_handle, cx| {
- repository_handle.checkout_files(&envelope.payload.commit, paths, cx)
+ repository_handle.checkout_files(commit, paths, cx)
})
.await?;
Ok(proto::Ack {})
@@ -7132,60 +7133,70 @@ impl Repository {
})
}
+ /// Restores `paths` in the working tree.
+ ///
+ /// With `Some(commit)`, the index and working tree are reset to that commit,
+ /// discarding staged and unstaged changes. With `None`, only the working tree
+ /// is restored from the index, so staged changes are kept.
pub fn checkout_files(
&mut self,
- commit: &str,
+ commit: Option<&str>,
paths: Vec<RepoPath>,
cx: &mut Context<Self>,
) -> Task<Result<()>> {
- let commit = commit.to_string();
+ let commit = commit.map(str::to_string);
let id = self.id;
+ let (git_status, description) = match &commit {
+ Some(commit) => (
+ pending_op::GitStatus::Reverted,
+ format!("git checkout {commit}"),
+ ),
+ None => (
+ pending_op::GitStatus::RevertedUnstaged,
+ "git checkout".to_string(),
+ ),
+ };
- self.spawn_job_with_tracking(
- paths.clone(),
- pending_op::GitStatus::Reverted,
- cx,
- async move |this, cx| {
- this.update(cx, |this, _cx| {
- this.send_job(
- "checkout_files",
- Some(format!("git checkout {}", commit).into()),
- move |git_repo, _| async move {
- match git_repo {
- RepositoryState::Local(LocalRepositoryState {
- backend,
- environment,
- ..
- }) => {
- backend
- .checkout_files(commit, paths, environment.clone())
- .await
- }
- RepositoryState::Remote(RemoteRepositoryState {
- project_id,
- client,
- }) => {
- client
- .request(proto::GitCheckoutFiles {
- project_id: project_id.0,
- repository_id: id.to_proto(),
- commit,
- paths: paths
- .into_iter()
- .map(|p| p.as_unix_str().to_owned())
- .collect(),
- })
- .await?;
-
- Ok(())
- }
+ self.spawn_job_with_tracking(paths.clone(), git_status, cx, async move |this, cx| {
+ this.update(cx, |this, _cx| {
+ this.send_job(
+ "checkout_files",
+ Some(description.into()),
+ move |git_repo, _| async move {
+ match git_repo {
+ RepositoryState::Local(LocalRepositoryState {
+ backend,
+ environment,
+ ..
+ }) => {
+ backend
+ .checkout_files(commit, paths, environment.clone())
+ .await
}
- },
- )
- })?
- .await?
- },
- )
+ RepositoryState::Remote(RemoteRepositoryState {
+ project_id,
+ client,
+ }) => {
+ client
+ .request(proto::GitCheckoutFiles {
+ project_id: project_id.0,
+ repository_id: id.to_proto(),
+ commit: commit.unwrap_or_default(),
+ paths: paths
+ .into_iter()
+ .map(|p| p.as_unix_str().to_owned())
+ .collect(),
+ })
+ .await?;
+
+ Ok(())
+ }
+ }
+ },
+ )
+ })?
+ .await?
+ })
}
pub fn reset(
diff --git a/crates/project/src/git_store/pending_op.rs b/crates/project/src/git_store/pending_op.rs
index 269e17a4d4d..2cc34547939 100644
--- a/crates/project/src/git_store/pending_op.rs
+++ b/crates/project/src/git_store/pending_op.rs
@@ -7,7 +7,10 @@ use worktree::{PathKey, PathSummary};
pub enum GitStatus {
Staged,
Unstaged,
+ /// Restored to `HEAD`, dropping staged and unstaged changes.
Reverted,
+ /// Working tree restored from the index; staged changes are kept.
+ RevertedUnstaged,
Unchanged,
}
diff --git a/crates/project_panel/src/project_panel.rs b/crates/project_panel/src/project_panel.rs
index 64854e8c70d..a84ab9b427a 100644
--- a/crates/project_panel/src/project_panel.rs
+++ b/crates/project_panel/src/project_panel.rs
@@ -2676,7 +2676,7 @@ impl ProjectPanel {
let task = panel.update(cx, |_panel, cx| {
repository.update(cx, |repo, cx| {
- repo.checkout_files("HEAD", vec![repo_path], cx)
+ repo.checkout_files(Some("HEAD"), vec![repo_path], cx)
})
})?;
diff --git a/crates/proto/proto/git.proto b/crates/proto/proto/git.proto
index c217707c433..02231fb0fe6 100644
--- a/crates/proto/proto/git.proto
+++ b/crates/proto/proto/git.proto
@@ -329,6 +329,7 @@ message GitCheckoutFiles {
uint64 project_id = 1;
reserved 2;
uint64 repository_id = 3;
+ // When empty, restores the working tree from the index, keeping staged changes.
string commit = 4;
repeated string paths = 5;
}