diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index 7ae35d1db..cf15a3212 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -1159,7 +1159,8 @@ impl Repo { write::stage_patch(self, patch, &|path| encoding(path).map(Into::into)) } /// Discards unstaged changes: tracked paths are restored from the index (staged - /// changes are kept), untracked files and directories are deleted. + /// changes are kept), untracked files and directories are deleted. A submodule goes back + /// to the commit the index records, with its tracked files restored. pub fn discard(&self, paths: &[PathBuf]) -> IdeResult<()> { let _scope = crate::ExecutionScope::enter(self.execution_allowed.load(std::sync::atomic::Ordering::Acquire)); write::discard(self, paths) diff --git a/crates/ide-vcs/src/preserve.rs b/crates/ide-vcs/src/preserve.rs index ad5717e04..97839a717 100644 --- a/crates/ide-vcs/src/preserve.rs +++ b/crates/ide-vcs/src/preserve.rs @@ -25,16 +25,19 @@ pub(crate) fn save(r: &Repo, message: &str) -> IdeResult<()> { if run(r.root(), &["status", "--porcelain", "--untracked-files=no"], None)?.stdout_str().trim().is_empty() { return Ok(()); } - let before = run(r.root(), &["rev-parse", "-q", "--verify", "refs/stash"], None).map(|o| o.stdout_str()).ok(); + let before = stash_top(r); run(r.root(), &["stash", "push", "-q", "-m", message], None)?; - let id = run(r.root(), &["rev-parse", "refs/stash"], None)?.stdout_str(); - if before.as_deref().map(str::trim) == Some(id.trim()) { - return Err(IdeError::invalid("could not save the local changes")); - } - std::fs::write(marker, id.trim())?; + // A stash that succeeds without a new entry found nothing it saves: the status above also + // lists submodules at another commit or with changes inside, which a stash leaves in place. + let Some(id) = stash_top(r).filter(|id| Some(id) != before.as_ref()) else { return Ok(()) }; + std::fs::write(marker, id)?; Ok(()) } +fn stash_top(r: &Repo) -> Option { + run(r.root(), &["rev-parse", "-q", "--verify", "refs/stash"], None).ok().map(|o| o.stdout_str().trim().to_owned()) +} + /// Brings the saved changes back once no operation is in progress. Fails when they come /// back with conflicts (they then also stay in the stash). pub(crate) fn restore(r: &Repo) -> IdeResult<()> { diff --git a/crates/ide-vcs/src/write.rs b/crates/ide-vcs/src/write.rs index 1a02ecaf2..12cd0e6e2 100644 --- a/crates/ide-vcs/src/write.rs +++ b/crates/ide-vcs/src/write.rs @@ -391,18 +391,24 @@ pub(crate) fn discard(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> { let rel = r.rel_paths(paths)?; // `git restore --worktree` refuses unmerged paths: roll those back to HEAD first. discard_unmerged(r, &rel)?; - let (mut tracked, mut untracked) = (Vec::new(), Vec::new()); + let (mut tracked, mut untracked, mut submodules) = (Vec::new(), Vec::new(), Vec::new()); { let repo = r.gix()?; let index = repo.index_or_empty().map_err(gx)?; for p in rel { - let exact = index.entry_index_by_path(BStr::new(p.as_bytes())).is_ok(); + let exact = index.entry_index_by_path(BStr::new(p.as_bytes())).ok().map(|i| &index.entries()[i]); let dir_prefix = if p == "." { String::new() } else { format!("{}/", p.trim_end_matches('/')) }; - let has_tracked_children = index.prefixed_entries(BStr::new(dir_prefix.as_bytes())).is_some(); - if exact { - tracked.push(p); + let children = index.prefixed_entries(BStr::new(dir_prefix.as_bytes())); + if let Some(entry) = exact { + if entry.mode.is_submodule() { + submodules.push(p); + } else { + tracked.push(p); + } } else if r.abs_path(&p).is_dir() { - if has_tracked_children { + if let Some(children) = children { + submodules + .extend(children.iter().filter(|e| e.mode.is_submodule()).map(|e| e.path(&index).to_string())); tracked.push(p.clone()); } untracked.push(p); @@ -412,6 +418,11 @@ pub(crate) fn discard(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> { } } run_paths(r, &["restore", "--worktree"], &tracked)?; + // A plain restore leaves a submodule alone. This one checks out the commit the index + // records there and restores its tracked files, keeping its untracked ones. + if crate::execution_allowed() { + run_paths(r, &["restore", "--recurse-submodules", "--worktree"], &submodules)?; + } if !untracked.is_empty() { // `git clean` keeps ignored files and refuses paths outside the worktree. run_paths(r, &["clean", "-f", "-d", "-q"], &untracked)?; diff --git a/crates/ide-vcs/tests/git_workflows.rs b/crates/ide-vcs/tests/git_workflows.rs index bb0d3115d..03550e855 100644 --- a/crates/ide-vcs/tests/git_workflows.rs +++ b/crates/ide-vcs/tests/git_workflows.rs @@ -69,7 +69,8 @@ impl Fixture { fn push_from_other(&self, bare: &Path, rel: &str, content: &str) { let other = self.tmp.path().join(format!("other-{}", rel.replace('/', "_"))); if !other.exists() { - git_in(self.tmp.path(), &["clone", "-q", bare.to_str().unwrap(), other.to_str().unwrap()]); + let (bare, other_dir) = (bare.to_str().unwrap(), other.to_str().unwrap()); + git_in(self.tmp.path(), &["clone", "-q", "-c", "core.autocrlf=false", bare, other_dir]); configure(&other); } git_in(&other, &["pull", "-q", "--rebase"]); @@ -636,6 +637,73 @@ fn update_with_rebase_keeps_a_file_added_then_deleted_added_to_the_index() { assert!(fx.git(&["status", "--porcelain", "--", "ad.txt"]).starts_with('A'), "still added"); } +/// Submodules `dirty` and `moved` (each with commits "one" and "two", at "two") committed in +/// the clone of [`Fixture::with_origin`] and pushed; then `dirty` gets an uncommitted edit of a +/// tracked file plus an untracked file, and `moved` is checked out at "one". Returns the commit +/// the superproject records for `moved`. +fn with_changed_submodules(fx: &Fixture) -> String { + for name in ["dirty", "moved"] { + let lib = fx.tmp.path().join(format!("lib-{name}")); + std::fs::create_dir(&lib).unwrap(); + git_in(&lib, &["init", "-q"]); + configure(&lib); + std::fs::write(lib.join("f.txt"), "one\n").unwrap(); + git_in(&lib, &["add", "-A"]); + git_in(&lib, &["commit", "-q", "-m", "one"]); + std::fs::write(lib.join("f.txt"), "two\n").unwrap(); + git_in(&lib, &["commit", "-q", "-am", "two"]); + let url = lib.to_str().unwrap(); + fx.git(&["-c", "protocol.file.allow=always", "-c", "core.autocrlf=false", "submodule", "add", "-q", url, name]); + configure(&fx.path(name)); + } + fx.commit_all("submodules"); + fx.git(&["push", "-q", "origin", "main"]); + let recorded = git_in(&fx.path("moved"), &["rev-parse", "HEAD"]); + fx.write("dirty/f.txt", "edited\n"); + fx.write("dirty/untracked.txt", "u\n"); + git_in(&fx.path("moved"), &["checkout", "-q", "HEAD~1"]); + recorded +} + +/// git lists submodules at another commit or with changes inside among the superproject's +/// changes, but its stash leaves them in place, so Update Project has nothing to put aside (#3632). +#[test] +fn update_with_changed_submodules_and_no_other_local_changes() { + for (rebase, earlier_stash) in [(false, false), (false, true), (true, false), (true, true)] { + let (fx, bare) = Fixture::with_origin(); + let recorded = with_changed_submodules(&fx); + if earlier_stash { + fx.write("a.txt", "stashed\n"); + fx.git(&["stash", "push", "-q", "-m", "earlier"]); + } + fx.push_from_other(&bare, "remote.txt", "r\n"); + let repo = fx.repo(); + let (cancel, out) = quiet(); + repo.pull(rebase, &cancel, &out).unwrap_or_else(|e| panic!("rebase={rebase} stash={earlier_stash}: {e}")); + assert!(fx.exists("remote.txt")); + assert_eq!(fx.read("dirty/f.txt"), "edited\n"); + assert_ne!(git_in(&fx.path("moved"), &["rev-parse", "HEAD"]), recorded); + let stashes = fx.git(&["stash", "list"]); + assert_eq!(stashes.lines().count(), usize::from(earlier_stash), "{stashes}"); + assert!(!fx.dir.join(".git/openidea-saved-changes").exists()); + } +} + +#[test] +fn rollback_changed_submodules_restores_the_recorded_commit_and_tracked_files() { + for whole_root in [false, true] { + let (fx, _bare) = Fixture::with_origin(); + let recorded = with_changed_submodules(&fx); + let repo = fx.repo(); + let paths = if whole_root { vec![fx.dir.clone()] } else { vec![fx.path("dirty"), fx.path("moved")] }; + repo.discard(&paths).unwrap(); + assert_eq!(fx.read("dirty/f.txt"), "two\n", "whole_root={whole_root}"); + assert_eq!(git_in(&fx.path("moved"), &["rev-parse", "HEAD"]), recorded); + assert_eq!(fx.read("dirty/untracked.txt"), "u\n", "untracked files of a submodule are kept"); + assert_eq!(fx.git(&["status", "--porcelain", "--ignore-submodules=untracked"]), ""); + } +} + #[test] fn reset_to_the_remote_branch_drops_local_commits_and_keeps_local_changes() { let (fx, bare) = Fixture::with_origin();