Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a feature branch and reset to origin/master in a single operation?

Tags:

git

git-branch

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?

like image 300
nowox Avatar asked Nov 25 '16 09:11

nowox


People also ask

How can you create a new branch and switch to it with a single command?

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.

How do I move from feature branch to master?

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.


1 Answers

You should be able to just check out the master branch as a new branch

 $ git checkout origin/master -b feature/new_featur

Edit

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!

like image 92
Amanuel Nega Avatar answered Nov 10 '22 14:11

Amanuel Nega