While Git maintains track of your daily changes, it also has organisational capabilities such as branches. However, if you're not ...
While Git maintains track of your daily changes, it also has organisational capabilities such as branches. However, if you're not careful, you could wind up with issues like commits and changes to the wrong branch, which are tough to fix without the right tools.
Changes in Direction (If You Haven't Already Committed)
Git keeps track of your entire folder, but changes to files aren't tied to a single branch until they're committed. You have the ability to move branches and bring those changes with you.
Switching branches is the simplest way, but this will only work if the two branches you're targeting have a similar history:
- [message]
- git checkout feature
There are a couple ways to get around this. The first method is to create a new branch and then merge the divergent histories:
- [message]
- git checkout -b tempfeature
- git checkout feature
- git merge tempfeature
You may also use git stash to save changes and reapply them on a new branch at a later time:
- [message]
- git stash
- git switch feature
- git stash apply
Commitments on the Move (If You Already Committed)
Don't worry if you've already committed—you can always soft reset, and commits aren't final until they've been pushed to remote source control. If you've already done that, you can still correct the issue, but your error will be recorded in your Git history, so it's preferable to do it locally before your coworkers see it.
You may soft reset to undo commits, normally just undoing the most recent one, but you can also send in a reference to the commit ID:
- [message]
- git reset HEAD~1
You'll be in the "haven't committed yet" state after that, and you can fix the problem using the ways above.
You can also use git cherry-pick to accomplish this. This command copies commits from one branch to another, and it's a simple way to select commits and move them to new branches.
To discover the commit ID you wish to rollback, use git log:
- [message]
- git log
Then, assuming your changes have been committed, checkout the feature branch and run cherry-pick:
- [message]
- git switch feature
- git cherry-pick
There will still be a duplicate commit on the main branch after that. If the feature branch is in appropriate order, you can either reset it and discard the changes, or maintain it and let Git sort it out after you merge.
COMMENTS