gitversion-controlbranch

Configure git to automatically track _specific_ (different) remote branch when creating branch locally


Imagine I have a repo with two branches A and B. I clone it:

$ git clone git@my.company:group/project.git
$ cd project

I checkout A:

$ git checkout A
Branch 'A' set up to track remote branch 'A' from 'origin'.
Switched to a new branch 'A'

(I can't remember if this behaviour is set by a config or not, but it's the behaviour I want).

Now I want to work on a feature:

$ git checkout -b A-feature
Switched to a new branch 'A-feature'

I have my git configured so when I push, it will automatically make A-feature on the remote. That part is fine (I use push.default = current to get this behaviour).

The issue comes when something has been merged in to A. I would like to a) know about it, and b) rebase my A-feature on A. I can achieve this with:

$ git branch --set-upstream-to=origin/A

Now git status will tell me if I am ahead/behind A, and git rebase will automatically use A. While git push still goes to origin/A-feature

However I'd like that tracking information to be set up at the time I do git checkout -b A-feature. i.e., I would like git to check if the current branch has tracking set up, and if it does, make the new branch track the same thing as the old one. So if I repeated these steps using B instead of A, B-feature would track origin/B. Note: I am aware there is a git config that automatically does that for local branches (i.e., it tracks the branch you checked out from, not the remote one) - I don't want this. I want it to track origin/A not A.

Every setting and flow I've seen online seems to be about everyone working on the same remote branch. But that's not how our workflows work. We make something like A-feature-123 and that branch is basically just for the dev working on it (i.e., no one else would ever push to A-feature-123 except for a single dev). Eventually it gets merged in to A. At which point everyone else who has a feature branch would rebase on A.

Is it possible to have get set things up for me automatically with a flow like this?


Solution

  • Yes, it is possible to do that using --track=inherit:

    git checkout A
    git checkout -b A-feature --track=inherit
    

    If you always want that behaviour, you can set it through the branch.autoSetupMerge config:

    git config --global branch.autoSetupMerge inherit