Git: How to automatically create upstream branches

That’s a serious number of branches.

You started a new feature branch, worked hard on initial commits, and you’re ready to send it for review. You try to push and:

$ git push
fatal: The current branch cheese has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin cheese

To have this happen automatically for branches without a tracking
upstream, see 'push.autoSetupRemote' in 'git help config'.

Oh no! You forgot to use --set-upstream to create the remote branch again.

You can copy-paste Git’s suggested command there, and carry on. Or, you can follow the hint and configure Git to always automatically create the branch, and never see this message again.

The push.autoSetupRemote option and the corresponding hint text were added in Git 2.37, which was released months ago in June 2022. To enable the option, run:

$ git config --global push.autoSetupRemote true

That command will add to your ~/.gitconfig:

[push]
    autoSetupRemote = true

From then on, git push on new branches will automatically create the branch:

$ git push
Enumerating objects: 1, done.
Counting objects: 100% (1/1), done.
Writing objects: 100% (1/1), 175 bytes | 175.00 KiB/s, done.
Total 1 (delta 0), reused 0 (delta 0), pack-reused 0
remote:
remote: Create a pull request for 'cheese' on GitHub by visiting:
remote:      https://github.com/adamchainz/example/pull/new/cheese
remote:
To github.com:adamchainz/example.git
 * [new branch]      cheese -> cheese
branch 'cheese' set up to track 'origin/cheese'.

That’s a neat time-saver!

This option is not enabled by default, because it only makes sense if you’re using a centralized Git workflow. But you probably are, with a host like GitHub.

Fin

Thanks to Tao Klerks for authoring this feature in commit 05d5775 and Junio C Hamano for reviewing it. And thanks to James Ide for advertising it on Twitter.

May your pushes forever be smooth,

—Adam


Make your development more pleasant with Boost Your Django DX.


Subscribe via RSS, Twitter, Mastodon, or email:

One summary email a week, no spam, I pinky promise.

Related posts:

Tags: