I've been discussing with my team and searching the internet, but I cannot figure out how to create a new git branch locally based on a remote branch hosted on GitHub. It seems like there should be a way to do this.
I've tried the following, but when I push, it pushes to the incorrect (origin/release/1.0) branch instead of pushing to a new branch (feature/123) on GitHub.
git checkout -b feature/123 origin/release/1.0
Currently, the workflow that works is:
git checkout release/1.0
git pull
git checkout -b feature/123
I have to do that quite a bit though and it feels like I should be able to skip having to pull in the release/1.0 branch locally, and instead, create my branch with one command.
Is there a way to do this, or do we have to just keep pulling in the latest release and then branching from there locally?
Solution
Update global git config
git config --global branch.autoSetupMerge false
Create new branch from latest release
$ git fetch --all
$ git checkout -b feature/123 origin/release/1.0
$ git push --set-upstream origin feature/123
CodePudding user response:
When you branch from a remote branch, Git automatically sets up the remote as the "tracking branch". This is the remote branch it will use when pushing and pulling.
$ git checkout -b feature/123 origin/release/1.0
Branch 'feature/123' set up to track remote branch 'release/1.0' from 'origin'.
Switched to a new branch 'feature/123'
You don't want it to track the remote. You can turn it off with --no-track
.
$ git checkout --no-track -b feature/123 origin/release/1.0
And you can change the behavior globally with branch.autoSetupMerge
.
$ git config --global branch.autoSetupMerge false
Now feature/123 has no tracking branch. When you run git push
it has to guess where to push your branch to. This can be configured with push.default
. You probably want simple
which is the default.
simple - pushes the current branch with the same name on the remote.
I have to do that quite a bit though and it feels like I should be able to skip having to pull in the release/1.0 branch locally, and instead, create my branch with one command.
Note that you still have to git fetch
the remote to ensure you have the latest version.
git fetch origin
git checkout -b feature/123 origin/release/1.0
This is the decentralized nature of Git, it does not assume you have a connection to your remotes. Though it's safe to just git fetch
periodically.
And to ensure your feature branch remains up to date with the latest changes, you will have to periodically update your branch from release/1.0.
git fetch origin
git rebase origin/release/1.0
This is the nature of working with others.