Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set up branches with different pull/push upstreams

I have a local git repo with two remotes: upstream, the original main repo, and origin, my GitHub fork of it.

I want to create new branches based off of upstream/master, push them to origin for PRs, and periodically pull in new changes from upstream/master.

Is there a way to set up my branches so that this happens by default? I.e.:

$ git checkout -b my-new-branch --some-other-flags
$ git maybe some other command
# branch 'my-new-branch' points to 'upstream/master' and is checked out
# make changes, git commit
$ git push  # pushes to origin/my-new-branch
$ git pull  # pulls from upstream/master
like image 409
alecbz Avatar asked Aug 11 '17 15:08

alecbz


People also ask

How do you set upstream for a branch?

The easiest way to set the upstream branch is to use the “git push” command with the “-u” option for upstream branch. Alternatively, you can use the “–set-upstream” option that is equivalent to the “-u” option.

How do I push changes to a different remote branch?

Push a new Git branch to a remote repo Clone the remote Git repo locally. Create a new branch with the branch, switch or checkout commands. Perform a git push with the –set-upstream option to set the remote repo for the new branch. Continue to perform Git commits locally on the new branch.

Can I push from a local branch to a different remote branch?

Push Branch to Another Branch In some cases, you may want to push your changes to another branch on the remote repository. In order to push your branch to another remote branch, use the “git push” command and specify the remote name, the name of your local branch as the name of the remote branch.


1 Answers

The following seems to work:

git config push.default current && git config remote.pushdefault origin

Then, create branches with git checkout -b new-branch upstream/master.

git push pushes to origin/my-branch, git pull pulls from upstream/master.


For branches based on other local branches instead of upstream/master, things seem a bit trickier. I could git config branch.autoSetupMerge always, but then branches would pull from the local branch they started from, not upstream/master. Or I could set the upstream to upstream/master explicitly with -u when creating the branch. I'm not sure which would be more appropriate though.

Another annoyance is that when I checkout a branch with changes, git sometimes tells me:

Your branch is ahead of 'upstream/master' by 7 commits. (use "git push" to publish your local commits)

But A) it's fine that I'm ahead of my upstream, I'm waiting to merge these changes in a PR, and B) more importantly, git push will push to new-branch at origin, not master at upstream.

This doesn't always happen though, so I think there's some other variable I'm missing here.

like image 179
alecbz Avatar answered Oct 18 '22 16:10

alecbz