I have changed a lot of files and I realized my approach is not good. So, I want to try another approach. I know two solutions in this case:
What I am looking for is to save my current changes somehow (without losing my current changes) and then discard some changes I don't want while keeping the rest of the changes. In this case, if I realize my second approach doesn't work either then I only need to switch to previous state.
Is there such a feature?
I think @Signey_Gijzen's answer is probably best, but you can do this with git stash apply
, too. That is, you'll want to do:
$ git stash # as usual, stashes the changes
... now your changes are gone from the working tree ...
$ git stash apply # unstashes, but keeps stash around
... now they're all back ...
$ git stash list # the stash will still be there
stash@{0}: WIP on master: ...
$ git show stash@{0} # what did that stash look like again?
Checkout a new branch, add your files and commit your changes there. Then change back to the branch you're previously working on.
I would use the same method for trying your second approach.
This is a general question (e.g. there's no specific code/tree example to work from) so you're going to get a general answer. The short version is: No, Git can't save work outside of making a commit or adding something to the index. Even the stash command is a special case of a commit, and leverages these basic processes.
However, there are certainly things you can do, both inside and outside Git. Some examples include (in no particular order):
git commit --patch
to select diff hunks to add to the index.Copy your working tree to another directory, revert to your last known-good commit, and copy files or hunks back into your working tree as you go. For example:
mkdir /tmp/broken_wip
cp * /tmp/broken_wip
git reset --hard
cp /tmp/broken_wip/somefile .
Create a temporary branch to store your "dirty" commits, and then change back to the main branch. You can then bring over whatever you like from your temporary branch. For example, assuming you're currently on master:
git checkout -b broken_branch
git add .
git commit -am 'broken WIP'
git checkout master
Using RCS to store your current state, while being sure not to commit the RCS directory or any *,v
files.
Even if you don't want to publish your history, you're generally better off committing your problem code to a temporary topic branch, fixing or importing things, and then disposing of the topic branch. However, if you really need to avoid committing things to history or the index, you should probably leverage a secondary revision control system or make use of your filesystem.
Your mileage may vary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With