Is it possible to delete a single file (i.e the diff of one file) from git stash with several files

StackOverflow https://stackoverflow.com/questions/23671388

  •  23-07-2023
  •  | 
  •  

Question

I'm looking for a way to delete a single change from a stash compiled of several changes, anyone knows of a way to do it? The best way for to describe it (due to the fact that git commit and git stash are so similar) is that I wish I knew a way to git commit --amend the stash.

It all started when I git stash a few changes before pulling from a shared repository. while I was trying to git pop the code from the stash, I had a conflict (I couldn't resolve) with a file I didn't care for duo to the fact that I had a script to generate it automatically, and was more interested in the other files located in my stash.

While I was looking for a solution I've found this Q : How would I extract a single file (or changes to a file) from a git stash? - it seemed promising, and was also given to someone else asking a similar question to mine, but it didn't help...

Was it helpful?

Solution

No, there is no way to delete a single change from a stash - at least not with the high-level commands that git stash provides. As a stash is internally just a commit, you could use the low-level commands to manipulate it, but that is likely more trouble than it is worth.

My rule of thumb is: If things start to get complicated with git stash, it's time to convert the stash to a real commit (typically on a separate branch). Then you can use all the nice git commands for manipulating commits (checkout, reset, rebase etc.).

In your case I'd recommend steps like this:

If git stash pop produces a conflict, clean up your working copy (re-checkout the files with conflict markers, etc.).

Then run:

git stash branch wip-branch

This will create and check out a new branch named "wip-branch", starting from the commit at which the stash was originally created. Then it will apply the changes from the stash. That way there cannot be a conflict, because the stashed changes are re-applied to the commit they are based on.

Now you have a real branch "wip-branch" with your stashed changes, which you can rebase, merge, cherry-pick etc. to your heart's content :-).

Note: While I used to use git stash regularly, I have almost stopped, because creating a real (temporary) commit on a real branch is not much more work, and gives me more options (not to mention that I can use proper commit comments, so I don't forget what the changes mean).

OTHER TIPS

Maybe it is easier to:

  • apply your stash
  • git checkout the file with conflict (to reset it, ignoring any conflict in it)
  • git stash again
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top