1
0

release.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. from __future__ import absolute_import
  2. from __future__ import print_function
  3. from __future__ import unicode_literals
  4. import argparse
  5. import os
  6. import shutil
  7. import sys
  8. import time
  9. from distutils.core import run_setup
  10. import pypandoc
  11. from jinja2 import Template
  12. from release.bintray import BintrayAPI
  13. from release.const import BINTRAY_ORG
  14. from release.const import NAME
  15. from release.const import REPO_ROOT
  16. from release.downloader import BinaryDownloader
  17. from release.images import ImageManager
  18. from release.repository import delete_assets
  19. from release.repository import get_contributors
  20. from release.repository import Repository
  21. from release.repository import upload_assets
  22. from release.utils import branch_name
  23. from release.utils import compatibility_matrix
  24. from release.utils import read_release_notes_from_changelog
  25. from release.utils import ScriptError
  26. from release.utils import update_init_py_version
  27. from release.utils import update_run_sh_version
  28. from release.utils import yesno
  29. from requests.exceptions import HTTPError
  30. from twine.commands.upload import main as twine_upload
  31. def create_initial_branch(repository, args):
  32. release_branch = repository.create_release_branch(args.release, args.base)
  33. if args.base and args.cherries:
  34. print('Detected patch version.')
  35. cherries = input('Indicate (space-separated) PR numbers to cherry-pick then press Enter:\n')
  36. repository.cherry_pick_prs(release_branch, cherries.split())
  37. return create_bump_commit(repository, release_branch, args.bintray_user, args.bintray_org)
  38. def create_bump_commit(repository, release_branch, bintray_user, bintray_org):
  39. with release_branch.config_reader() as cfg:
  40. release = cfg.get('release')
  41. print('Updating version info in __init__.py and run.sh')
  42. update_run_sh_version(release)
  43. update_init_py_version(release)
  44. input('Please add the release notes to the CHANGELOG.md file, then press Enter to continue.')
  45. proceed = None
  46. while not proceed:
  47. print(repository.diff())
  48. proceed = yesno('Are these changes ok? y/N ', default=False)
  49. if repository.diff():
  50. repository.create_bump_commit(release_branch, release)
  51. repository.push_branch_to_remote(release_branch)
  52. bintray_api = BintrayAPI(os.environ['BINTRAY_TOKEN'], bintray_user)
  53. print('Creating data repository {} on bintray'.format(release_branch.name))
  54. bintray_api.create_repository(bintray_org, release_branch.name, 'generic')
  55. def monitor_pr_status(pr_data):
  56. print('Waiting for CI to complete...')
  57. last_commit = pr_data.get_commits().reversed[0]
  58. while True:
  59. status = last_commit.get_combined_status()
  60. if status.state == 'pending' or status.state == 'failure':
  61. summary = {
  62. 'pending': 0,
  63. 'success': 0,
  64. 'failure': 0,
  65. }
  66. for detail in status.statuses:
  67. if detail.context == 'dco-signed':
  68. # dco-signed check breaks on merge remote-tracking ; ignore it
  69. continue
  70. summary[detail.state] += 1
  71. print('{pending} pending, {success} successes, {failure} failures'.format(**summary))
  72. if summary['pending'] == 0 and summary['failure'] == 0 and summary['success'] > 0:
  73. # This check assumes at least 1 non-DCO CI check to avoid race conditions.
  74. # If testing on a repo without CI, use --skip-ci-check to avoid looping eternally
  75. return True
  76. elif summary['failure'] > 0:
  77. raise ScriptError('CI failures detected!')
  78. time.sleep(30)
  79. elif status.state == 'success':
  80. print('{} successes: all clear!'.format(status.total_count))
  81. return True
  82. def check_pr_mergeable(pr_data):
  83. if not pr_data.mergeable:
  84. print(
  85. 'WARNING!! PR #{} can not currently be merged. You will need to '
  86. 'resolve the conflicts manually before finalizing the release.'.format(pr_data.number)
  87. )
  88. return pr_data.mergeable
  89. def create_release_draft(repository, version, pr_data, files):
  90. print('Creating Github release draft')
  91. with open(os.path.join(os.path.dirname(__file__), 'release.md.tmpl'), 'r') as f:
  92. template = Template(f.read())
  93. print('Rendering release notes based on template')
  94. release_notes = template.render(
  95. version=version,
  96. compat_matrix=compatibility_matrix(),
  97. integrity=files,
  98. contributors=get_contributors(pr_data),
  99. changelog=read_release_notes_from_changelog(),
  100. )
  101. gh_release = repository.create_release(
  102. version, release_notes, draft=True, prerelease='-rc' in version,
  103. target_commitish='release'
  104. )
  105. print('Release draft initialized')
  106. return gh_release
  107. def print_final_instructions(args):
  108. print(
  109. "You're almost done! Please verify that everything is in order and "
  110. "you are ready to make the release public, then run the following "
  111. "command:\n{exe} -b {user} finalize {version}".format(
  112. exe='./script/release/release.sh', user=args.bintray_user, version=args.release
  113. )
  114. )
  115. def distclean():
  116. print('Running distclean...')
  117. dirs = [
  118. os.path.join(REPO_ROOT, 'build'), os.path.join(REPO_ROOT, 'dist'),
  119. os.path.join(REPO_ROOT, 'docker-compose.egg-info')
  120. ]
  121. files = []
  122. for base, dirnames, fnames in os.walk(REPO_ROOT):
  123. for fname in fnames:
  124. path = os.path.normpath(os.path.join(base, fname))
  125. if fname.endswith('.pyc'):
  126. files.append(path)
  127. elif fname.startswith('.coverage.'):
  128. files.append(path)
  129. for dirname in dirnames:
  130. path = os.path.normpath(os.path.join(base, dirname))
  131. if dirname == '__pycache__':
  132. dirs.append(path)
  133. elif dirname == '.coverage-binfiles':
  134. dirs.append(path)
  135. for file in files:
  136. os.unlink(file)
  137. for folder in dirs:
  138. shutil.rmtree(folder, ignore_errors=True)
  139. def pypi_upload(args):
  140. print('Uploading to PyPi')
  141. try:
  142. twine_upload([
  143. 'dist/docker_compose-{}*.whl'.format(args.release),
  144. 'dist/docker-compose-{}*.tar.gz'.format(args.release)
  145. ])
  146. except HTTPError as e:
  147. if e.response.status_code == 400 and 'File already exists' in e.message:
  148. if not args.finalize_resume:
  149. raise ScriptError(
  150. 'Package already uploaded on PyPi.'
  151. )
  152. print('Skipping PyPi upload - package already uploaded')
  153. else:
  154. raise ScriptError('Unexpected HTTP error uploading package to PyPi: {}'.format(e))
  155. def resume(args):
  156. try:
  157. distclean()
  158. repository = Repository(REPO_ROOT, args.repo)
  159. br_name = branch_name(args.release)
  160. if not repository.branch_exists(br_name):
  161. raise ScriptError('No local branch exists for this release.')
  162. gh_release = repository.find_release(args.release)
  163. if gh_release and not gh_release.draft:
  164. print('WARNING!! Found non-draft (public) release for this version!')
  165. proceed = yesno(
  166. 'Are you sure you wish to proceed? Modifying an already '
  167. 'released version is dangerous! y/N ', default=False
  168. )
  169. if proceed.lower() is not True:
  170. raise ScriptError('Aborting release')
  171. release_branch = repository.checkout_branch(br_name)
  172. if args.cherries:
  173. cherries = input('Indicate (space-separated) PR numbers to cherry-pick then press Enter:\n')
  174. repository.cherry_pick_prs(release_branch, cherries.split())
  175. create_bump_commit(repository, release_branch, args.bintray_user, args.bintray_org)
  176. pr_data = repository.find_release_pr(args.release)
  177. if not pr_data:
  178. pr_data = repository.create_release_pull_request(args.release)
  179. check_pr_mergeable(pr_data)
  180. if not args.skip_ci:
  181. monitor_pr_status(pr_data)
  182. downloader = BinaryDownloader(args.destination)
  183. files = downloader.download_all(args.release)
  184. if not gh_release:
  185. gh_release = create_release_draft(repository, args.release, pr_data, files)
  186. delete_assets(gh_release)
  187. upload_assets(gh_release, files)
  188. img_manager = ImageManager(args.release)
  189. img_manager.build_images(repository, files)
  190. except ScriptError as e:
  191. print(e)
  192. return 1
  193. print_final_instructions(args)
  194. return 0
  195. def cancel(args):
  196. try:
  197. repository = Repository(REPO_ROOT, args.repo)
  198. repository.close_release_pr(args.release)
  199. repository.remove_release(args.release)
  200. repository.remove_bump_branch(args.release)
  201. bintray_api = BintrayAPI(os.environ['BINTRAY_TOKEN'], args.bintray_user)
  202. print('Removing Bintray data repository for {}'.format(args.release))
  203. bintray_api.delete_repository(args.bintray_org, branch_name(args.release))
  204. distclean()
  205. except ScriptError as e:
  206. print(e)
  207. return 1
  208. print('Release cancellation complete.')
  209. return 0
  210. def start(args):
  211. distclean()
  212. try:
  213. repository = Repository(REPO_ROOT, args.repo)
  214. create_initial_branch(repository, args)
  215. pr_data = repository.create_release_pull_request(args.release)
  216. check_pr_mergeable(pr_data)
  217. if not args.skip_ci:
  218. monitor_pr_status(pr_data)
  219. downloader = BinaryDownloader(args.destination)
  220. files = downloader.download_all(args.release)
  221. gh_release = create_release_draft(repository, args.release, pr_data, files)
  222. upload_assets(gh_release, files)
  223. img_manager = ImageManager(args.release)
  224. img_manager.build_images(repository, files)
  225. except ScriptError as e:
  226. print(e)
  227. return 1
  228. print_final_instructions(args)
  229. return 0
  230. def finalize(args):
  231. distclean()
  232. try:
  233. repository = Repository(REPO_ROOT, args.repo)
  234. img_manager = ImageManager(args.release)
  235. pr_data = repository.find_release_pr(args.release)
  236. if not pr_data:
  237. raise ScriptError('No PR found for {}'.format(args.release))
  238. if not check_pr_mergeable(pr_data):
  239. raise ScriptError('Can not finalize release with an unmergeable PR')
  240. if not img_manager.check_images(args.release):
  241. raise ScriptError('Missing release image')
  242. br_name = branch_name(args.release)
  243. if not repository.branch_exists(br_name):
  244. raise ScriptError('No local branch exists for this release.')
  245. gh_release = repository.find_release(args.release)
  246. if not gh_release:
  247. raise ScriptError('No Github release draft for this version')
  248. repository.checkout_branch(br_name)
  249. pypandoc.convert_file(
  250. os.path.join(REPO_ROOT, 'README.md'), 'rst', outputfile=os.path.join(REPO_ROOT, 'README.rst')
  251. )
  252. run_setup(os.path.join(REPO_ROOT, 'setup.py'), script_args=['sdist', 'bdist_wheel'])
  253. merge_status = pr_data.merge()
  254. if not merge_status.merged and not args.finalize_resume:
  255. raise ScriptError(
  256. 'Unable to merge PR #{}: {}'.format(pr_data.number, merge_status.message)
  257. )
  258. pypi_upload(args)
  259. img_manager.push_images()
  260. repository.publish_release(gh_release)
  261. except ScriptError as e:
  262. print(e)
  263. return 1
  264. return 0
  265. ACTIONS = [
  266. 'start',
  267. 'cancel',
  268. 'resume',
  269. 'finalize',
  270. ]
  271. EPILOG = '''Example uses:
  272. * Start a new feature release (includes all changes currently in master)
  273. release.sh -b user start 1.23.0
  274. * Start a new patch release
  275. release.sh -b user --patch 1.21.0 start 1.21.1
  276. * Cancel / rollback an existing release draft
  277. release.sh -b user cancel 1.23.0
  278. * Restart a previously aborted patch release
  279. release.sh -b user -p 1.21.0 resume 1.21.1
  280. '''
  281. def main():
  282. if 'GITHUB_TOKEN' not in os.environ:
  283. print('GITHUB_TOKEN environment variable must be set')
  284. return 1
  285. if 'BINTRAY_TOKEN' not in os.environ:
  286. print('BINTRAY_TOKEN environment variable must be set')
  287. return 1
  288. parser = argparse.ArgumentParser(
  289. description='Orchestrate a new release of docker/compose. This tool assumes that you have '
  290. 'obtained a Github API token and Bintray API key and set the GITHUB_TOKEN and '
  291. 'BINTRAY_TOKEN environment variables accordingly.',
  292. epilog=EPILOG, formatter_class=argparse.RawTextHelpFormatter)
  293. parser.add_argument(
  294. 'action', choices=ACTIONS, help='The action to be performed for this release'
  295. )
  296. parser.add_argument('release', help='Release number, e.g. 1.9.0-rc1, 2.1.1')
  297. parser.add_argument(
  298. '--patch', '-p', dest='base',
  299. help='Which version is being patched by this release'
  300. )
  301. parser.add_argument(
  302. '--repo', '-r', dest='repo', default=NAME,
  303. help='Start a release for the given repo (default: {})'.format(NAME)
  304. )
  305. parser.add_argument(
  306. '-b', dest='bintray_user', required=True, metavar='USER',
  307. help='Username associated with the Bintray API key'
  308. )
  309. parser.add_argument(
  310. '--bintray-org', dest='bintray_org', metavar='ORG', default=BINTRAY_ORG,
  311. help='Organization name on bintray where the data repository will be created.'
  312. )
  313. parser.add_argument(
  314. '--destination', '-o', metavar='DIR', default='binaries',
  315. help='Directory where release binaries will be downloaded relative to the project root'
  316. )
  317. parser.add_argument(
  318. '--no-cherries', '-C', dest='cherries', action='store_false',
  319. help='If set, the program will not prompt the user for PR numbers to cherry-pick'
  320. )
  321. parser.add_argument(
  322. '--skip-ci-checks', dest='skip_ci', action='store_true',
  323. help='If set, the program will not wait for CI jobs to complete'
  324. )
  325. parser.add_argument(
  326. '--finalize-resume', dest='finalize_resume', action='store_true',
  327. help='If set, finalize will continue through steps that have already been completed.'
  328. )
  329. args = parser.parse_args()
  330. if args.action == 'start':
  331. return start(args)
  332. elif args.action == 'resume':
  333. return resume(args)
  334. elif args.action == 'cancel':
  335. return cancel(args)
  336. elif args.action == 'finalize':
  337. return finalize(args)
  338. print('Unexpected action "{}"'.format(args.action), file=sys.stderr)
  339. return 1
  340. if __name__ == '__main__':
  341. sys.exit(main())