diff --git a/git_common.py b/git_common.py index 9feb04b3b..0fa07e8e1 100644 --- a/git_common.py +++ b/git_common.py @@ -665,8 +665,16 @@ def repo_root(): return run('rev-parse', '--show-toplevel') +def upstream_default(): + """Returns the default branch name of the origin repository.""" + try: + return run('rev-parse', '--abbrev-ref', 'origin/HEAD') + except subprocess2.CalledProcessError: + return 'origin/master' + + def root(): - return get_config('depot-tools.upstream', 'origin/master') + return get_config('depot-tools.upstream', upstream_default()) @contextlib.contextmanager diff --git a/man/src/git-new-branch.txt b/man/src/git-new-branch.txt index 6d9bc7211..c14823703 100644 --- a/man/src/git-new-branch.txt +++ b/man/src/git-new-branch.txt @@ -52,7 +52,8 @@ depot-tools.upstream ~~~~~~~~~~~~~~~~~~~~ This configures the default 'upstream' for all new branches. If it is unset, it -defaults to 'origin/master'. This is considered to be the 'root' branch. +defaults to 'origin''s default branch or 'origin/master' if that can't be found. +This is considered to be the 'root' branch. EXAMPLE ------- diff --git a/man/src/git-rebase-update.txt b/man/src/git-rebase-update.txt index 288c2430b..07dc5e734 100644 --- a/man/src/git-rebase-update.txt +++ b/man/src/git-rebase-update.txt @@ -63,7 +63,7 @@ Restoration:: `git rebase-update` checks out the branch that you started on, and 'thaws' it, if necessary (see linkgit:git-thaw[1]). If the branch you started on got cleaned up, `git rebase-update` will checkout the 'root' ref (defaults to - 'origin/master', as configured by `depot-tools.upstream`, see + 'origin''s default branch, as configured by `depot-tools.upstream`, see linkgit:git-new-branch[1]). diff --git a/tests/git_common_test.py b/tests/git_common_test.py index e0424634d..a0ac1ee13 100755 --- a/tests/git_common_test.py +++ b/tests/git_common_test.py @@ -453,6 +453,20 @@ class GitMutableFunctionsTest(git_test_utils.GitRepoReadWriteTestBase, self.assertEqual('catfood', self.repo.run(self.gc.root)) + def testRoot(self): + origin_schema = git_test_utils.GitRepoSchema(""" + A B C + B D + """, self.getRepoContent) + origin = origin_schema.reify() + # Set the default branch to branch_D instead of master. + origin.git('checkout', 'branch_D') + + self.repo.git('remote', 'add', 'origin', origin.repo_path) + self.repo.git('fetch', 'origin') + self.repo.git('remote', 'set-head', 'origin', '-a') + self.assertEqual('origin/branch_D', self.repo.run(self.gc.root)) + def testUpstream(self): self.repo.git('commit', '--allow-empty', '-am', 'foooooo') self.assertEqual(self.repo.run(self.gc.upstream, 'bobly'), None)