Search code examples
gitgithubgit-branchgit-pushgit-remote

Having git pull and push to different default remotes based on the branch


Im trying to figure out how to setup git where I can pull/push from/to one remote and it by default pulls/pushes it into its own local branch.

This remote won't be the origin remote and Id like to merge the branch occasionally to the master branch which will be pushed/pulled to/from origin.

But its important to note that the other remote(s) will be completely independent and have their own master and such branches. So it may look something like this

remote-a (master) -> local (remote-a-branch)

Any help will be much appreciated, thanks in advance


Solution

    1. You can have as many remotes as you want. Please note all remotes are equal - origin is not special remote in any sense. It is just first default remote you have after clonning new repo. You can manage them with git remote command (reference)

    git remote add remote123 <REMOTE_URL>

    1. You can have as many branches as you want. You may setup a local branch to track a single remote branch. git checkout helps you to do this. (reference). git branch can do this too using --set-upstream-to key (reference)

    Example:

    # create branch, checkout to newly created branch and setup tracking
    git checkout -b remote123_master remote123/master
    

    this will set up local branch remote123_master to track master branch from remote remote123.

    So as far as I understand your needs you'll have this workflow:

    git checkout master // switch to default master (tracked from origin/master)
    git pull // if needed from origin
    git push // if needed to origin
    // do the job, commit
    git checkout remote123_master // switch to master from other remote
    git pull // if needed from remote123
    git push // if needed to remote123
    // do the job, commit
    git checkout master // go back to master
    git merge remote123_master // merge master from remote123 to master
    git push // if needed to origin
    

    update

    If you are not planning to do commits to other remotes you may skip the step with creating local branch for remote123. Then it look like:

    git remote add remote123 <REMOTE_URL>
    git fetch remote123 // fetch data from remote but do not modify local branches
    git checkout master // switch to default master (tracked from origin/master)
    git pull // if needed from origin
    git push // if needed to origin
    // do the job, commit
    git fetch remote123 // fetch data from remote but do not modify local branches
    git merge remote123/master // merge directly with remote branch reference without creating local one
    git push // if needed to origin