Commit and push your unfinished work, like you're doing. A message of "wip" (Work In Progress) is sufficient, but write more if you need to remind yourself what you were doing.
When you get to the other computer pull the changes, like you're doing, and continue your work.
# git pull
origin
A - B - WIP [main]
local
A - B - WIP [main]
When you're ready to commit, instead of making a new commit, amend the existing commit. Use git commit --amend
. This will add your changes to the last commit and give you an opportunity to rewrite the commit message.
git commit --amend
actually replaces the wip commit with a new commit combining the wip commit with your edits. This is an important detail.
# edit edit edit
# git commit -a --amend
origin
A - B - WIP [main]
local
A - B - C [main]
Here commit C combines WIP with your new edits. You local branch has diverged from origin.
This is important because pushes can only add to history, a push can't change history. If you try to push it will be rejected because you'd overwrite the WIP commit. To overwrite a branch with your local one you need to force the push using git push --force-with-lease
(don't use --force
). I like to alias that as git repush
.
# git push --force-with-lease
origin
A - B - C [main]
local
A - B - C [main]
This WIP/amend approach works well even if you just need to interrupt your work to change branches. It's more robust than stashing.
An alternative to the WIP/amend approach is WIP/redo. Do all the same stuff, but after you pull run git reset --soft HEAD~
. This will undo the last commit, but leave all the changes in your staging area. Now you can continue to work on your unfinished edit as normal, commit as normal, and then force the push.
I like to alias git reset --soft HEAD~
as git redo
.
Going back to our example above, here we are just after pulling the WIP.
origin
A - B - WIP [main]
local
A - B - WIP [main]
Then we git reset --soft HEAD~
to undo the WIP but keep the changes staged.
# git reset --soft HEAD~
origin
A - B - WIP [main]
local
A - B [main]
And then finish your edits and commit as normal.
# edit edit edit
# git commit -a
origin
A - B - WIP [main]
local
A - B - C [main]
The advantage of WIP/redo vs WIP/amend is with WIP/redo you can see and diff the complete change like normal. Either approach is fine, the end result is the same, it's a matter of taste.
Amending is fine if it's just the latest commit you want to rewrite. More general editing of the history can be done with an interactive rebase where you can rewrite commits, change commit messages, squash commits together, and so on. In your case, your "switching to laptop" commits would be squashed as a "fixup".
See Rewriting History for more information on amending and rebasing.