Working with Git, I had to go back to a specific commit. I made some changes and I now want to commit them. What is a proper way of doing this?
My project is now in detached-HEAD state. Will my changes be saved if I make a commit with
git commit
? Otherwise, what should I do to not lose my changes?
If you want to keep changes made with a detached HEAD, just create a new branch and switch to it. You can create it right after arriving at a detached HEAD or after creating one or more commits. The result is the same. The only restriction is that you should do it before returning to your normal branch.
Disclaimer: git isn't complicated, it's just versatile. Don't be scared off just because I've rambled into a long answer :)
You had:master: a-b-c-d-e-f
and wanted to change c
. You did:
* git checkout c
(avoid checking out commits in future. Move the branch head instead)
* changed some files
You are in:
master: a-b-c-d-e-f \uncommitted-work,detached
(If you have pushed, people downstream will be have to recover from upstream rebase)
git stash .
git checkout master
git stash pop
(resolve conflicts)git stage .
git commit -m "temporary name for g"
master: a-b-c-d-e-f-g
)git rebase c -i
("re-apply my current branch on to point c, and let me manipulate the commits interactively", i.e, re-parent (rebase) d-e-f
onto a new c
)g
so it's after c, then change the rebase command from pick
to fixup
. dd
to delete a line, P
to place it, i
to enter insert mode to type "fixup" then :wq
to save and exit vim. master: a-b-c'-d'-e'-f'
, where c'
is the result of you merging g
and c
during the rebase. d-e-f
have become d'-e'-f'
as their ancestry has changed so they're not the "same" commits as far as git is concerned, but their contents remain the same)d-e-f
(and rewrite history as if you never made them)(If you have pushed, people downstream will be have to recover from upstream rebase) :
git stash .
git checkout master
master: a-b-c-d-e-f
, with stashed files originally based upon c)git reset --hard c
(discard all files and commits on master since c)master: a-b-c
, with stashed files)git stash pop
(resolve conflicts)master: a-b-c-*
)git stage .
git commit -m "description of g"
master: a-b-c-g
)git stash
git revert --no-commit d
git revert --no-commit e
git revert --no-commit f
git push
git stash pop
(will be no conflicts)git stage .
git commit -m "Undo d-e-f in order to fix..."
git push
git push
d-e-f, and you want to keep them separate:Sounds like your new changes are for a new branch off master. git branch <foo>
.
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