git_migrate_default_branch.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. #!/usr/bin/env vpython3
  2. # Copyright 2020 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. """Migrate local repository onto new default branch."""
  6. import gerrit_util
  7. import git_common
  8. import metrics
  9. import scm
  10. import sys
  11. import logging
  12. import urllib.parse
  13. def GetGerritProject(remote_url):
  14. """Returns Gerrit project name based on remote git URL."""
  15. if remote_url is None:
  16. raise RuntimeError('can\'t detect Gerrit project.')
  17. project = urllib.parse.urlparse(remote_url).path.strip('/')
  18. if project.endswith('.git'):
  19. project = project[:-len('.git')]
  20. # *.googlesource.com hosts ensure that Git/Gerrit projects don't start with
  21. # 'a/' prefix, because 'a/' prefix is used to force authentication in
  22. # gitiles/git-over-https protocol. E.g.,
  23. # https://chromium.googlesource.com/a/v8/v8 refers to the same repo/project
  24. # as
  25. # https://chromium.googlesource.com/v8/v8
  26. if project.startswith('a/'):
  27. project = project[len('a/'):]
  28. return project
  29. def GetGerritHost(git_host):
  30. parts = git_host.split('.')
  31. parts[0] = parts[0] + '-review'
  32. return '.'.join(parts)
  33. def main():
  34. remote = git_common.run('remote')
  35. # Use first remote as source of truth
  36. remote = remote.split("\n")[0]
  37. if not remote:
  38. raise RuntimeError('Could not find any remote')
  39. url = scm.GIT.GetConfig(git_common.repo_root(), 'remote.%s.url' % remote)
  40. host = urllib.parse.urlparse(url).netloc
  41. if not host:
  42. raise RuntimeError('Could not find remote host')
  43. project_head = gerrit_util.GetProjectHead(GetGerritHost(host),
  44. GetGerritProject(url))
  45. if project_head != 'refs/heads/main':
  46. raise RuntimeError("The repository is not migrated yet.")
  47. # User may have set to fetch only old default branch. Ensure fetch is
  48. # tracking main too.
  49. git_common.run('config', '--unset-all', 'remote.origin.fetch',
  50. 'refs/heads/*')
  51. git_common.run('config', '--add', 'remote.origin.fetch',
  52. '+refs/heads/*:refs/remotes/origin/*')
  53. logging.info("Running fetch...")
  54. git_common.run('fetch', remote)
  55. logging.info("Updating remote HEAD...")
  56. git_common.run('remote', 'set-head', '-a', remote)
  57. branches = git_common.get_branches_info(True)
  58. if 'master' in branches:
  59. logging.info("Migrating master branch...")
  60. if 'main' in branches:
  61. logging.info(
  62. 'You already have master and main branch, consider removing '
  63. 'master manually:\n'
  64. ' $ git branch -d master\n')
  65. else:
  66. git_common.run('branch', '-m', 'master', 'main')
  67. branches = git_common.get_branches_info(True)
  68. for name in branches:
  69. branch = branches[name]
  70. if not branch:
  71. continue
  72. if 'master' in branch.upstream:
  73. logging.info("Migrating %s branch..." % name)
  74. new_upstream = branch.upstream.replace('master', 'main')
  75. git_common.run('branch', '--set-upstream-to', new_upstream, name)
  76. git_common.remove_merge_base(name)
  77. if __name__ == '__main__':
  78. logging.basicConfig(level=logging.INFO)
  79. with metrics.collector.print_notice_and_exit():
  80. try:
  81. logging.info("Starting migration")
  82. main()
  83. logging.info("Migration completed")
  84. except RuntimeError as e:
  85. logging.error("Error %s" % str(e))
  86. sys.exit(1)