I often start my journey with a small fix on the master branch that eventually appear more complex than initially thought.
So I easily fall in this situation:
* Damned I have more stuff to check (HEAD -> master)
* Forgot to fix this as well...
* Oops, fixed that too
* Fixed this
* (origin/master)
And at that point somebody ask me to quickly do a small change on the master branch. So I need to create a feature
/bugfix
branch and revert master
to its origin
:
$ git branch --magic bug/foobar
$ git log
* Damned I have more stuff to check (HEAD -> bug/foobar)
* Forgot to fix this as well...
* Oops, fixed that too
* Fixed this
* (master, origin/master)
Currently I solve my issue with this:
$ git branch bug/foobar
$ git reset --hard origin/master
$ git checkout bug/foobar
I can obviously create an alias for it (not tested yet):
swap-to="!git branch $@ && \
git reset --hard \
\$(git config --get branch.\$(git rev-parse --abbrev-ref HEAD).remote)/\
\$(git rev-parse --abbrev-ref HEAD) && \
git checkout $@"
Is there a quicker/smarter way to do this?
The git branch command can be used to create a new branch. When you want to start a new feature, you create a new branch off main using git branch new_branch . Once created you can then use git checkout new_branch to switch to that branch.
In order to switch to the master branch, on this specific commit, we are going to execute the “git checkout” command and specify the “master” branch as well as the commit SHA. In order to check that you are correctly on a specific commit, you can use the “git log” command again.
You should be able to just check out the master branch as a new branch
$ git checkout origin/master -b feature/new_featur
The above solution, while it works, it sets the new branch to track the master branch. (Which i don't like)
I usually untrack before I continue.
I looked at how IntelliJ checks out new branch, and here is how.
$ git checkout origin/master
After this, git will tell you that you're on a detached head. Now that you have a HEAD that is the same as origin/master
, go ahead and check that commit as an new branch.
$ git checkout -b feature/new_feature
DON"T FORGET to git fetch
:) Magic wound, ha? I hope it helps!
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