Trần Kim Dự
Trần Kim Dự

Reputation: 6102

Git: Command for cancel a commit

When I work, I often meet with this workflow:

  1. Doing something.
  2. Someone comes to my desk and ask something, I must move to another branch for checking.
  3. I commit code on this current branch and checkout another branch.
  4. When I finish, I checkout old branch and continue to work.

This workflow has a disadvantage: it generates a dummy commit in my system. My question is: how can I avoid this situation? For example, when I come back to work, I will cancel previous commit?

Upvotes: 0

Views: 174

Answers (4)

Jon Skeet
Jon Skeet

Reputation: 1503280

In addition to the two existing answers (git reset and git stash), I personally just ignore the extra commit (which almost has a commit message of wip...) until I'm ready to push the change somewhere remote, e.g. to github to create a pull request.

At that point, I use git rebase -i to look at all the commits I've got in that branch, and work out which commits I want to push - squashing commits together and rewording commit messages as required.

I've personally found this to be easier to use than git stash, as I typically find I lose track of what stashes are meant to be about. (My fault rather than a flaw in git, but the effect is still bad.) I suspect that git reset would be fine too, but as I often have to rebase anyway before a final merge - e.g. to react to code review comments - I have git rebase as a more mentally efficient part of my workflow.

Upvotes: 6

Cody
Cody

Reputation: 2853

Sounds like you need git stash. Check out this site for usage. Your workflow will look something like this:

git stash (stashes your changes for this branch)

git checkout otherBranch (then do your work)

git checkout firstBranch (returning to the original job)

git stash apply (puts your uncommitted changes back)

You can also use git rebase -i to get rid of some of your existing dummy commits, see this.

Upvotes: 2

Noufal Ibrahim
Noufal Ibrahim

Reputation: 72845

After you switch back to the old branch, run git reset HEAD^ and you'll get back to your previous state. The latest temporary commit will be discarded. If you've pushed that commit, you'll need to --force a new push.

Upvotes: 3

Sebastian Lenartowicz
Sebastian Lenartowicz

Reputation: 4874

You can use git stash for precisely this. When someone comes to your desk, do a git stash to temporarily "shelve" your current work. Check out the other branch, do your thing, and then, when they leave, switch back to your work branch and do git stash pop.

Make sure you don't have any changes staged, though - git stash, if memory serves, ignores staged changes and untracked files.

Upvotes: 3

Related Questions