versions.py 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  1. #!/usr/bin/env python
  2. """
  3. Query the github API for the git tags of a project, and return a list of
  4. version tags for recent releases, or the default release.
  5. The default release is the most recent non-RC version.
  6. Recent is a list of unique major.minor versions, where each is the most
  7. recent version in the series.
  8. For example, if the list of versions is:
  9. 1.8.0-rc2
  10. 1.8.0-rc1
  11. 1.7.1
  12. 1.7.0
  13. 1.7.0-rc1
  14. 1.6.2
  15. 1.6.1
  16. `default` would return `1.7.1` and
  17. `recent -n 3` would return `1.8.0-rc2 1.7.1 1.6.2`
  18. """
  19. from __future__ import absolute_import
  20. from __future__ import print_function
  21. from __future__ import unicode_literals
  22. import argparse
  23. import itertools
  24. import operator
  25. import sys
  26. from collections import namedtuple
  27. import requests
  28. GITHUB_API = 'https://api.github.com/repos'
  29. class Version(namedtuple('_Version', 'major minor patch rc edition')):
  30. @classmethod
  31. def parse(cls, version):
  32. edition = None
  33. version = version.lstrip('v')
  34. version, _, rc = version.partition('-')
  35. if rc:
  36. if 'rc' not in rc:
  37. edition = rc
  38. rc = None
  39. elif '-' in rc:
  40. edition, rc = rc.split('-')
  41. major, minor, patch = version.split('.', 3)
  42. return cls(major, minor, patch, rc, edition)
  43. @property
  44. def major_minor(self):
  45. return self.major, self.minor
  46. @property
  47. def order(self):
  48. """Return a representation that allows this object to be sorted
  49. correctly with the default comparator.
  50. """
  51. # rc releases should appear before official releases
  52. rc = (0, self.rc) if self.rc else (1, )
  53. return (int(self.major), int(self.minor), int(self.patch)) + rc
  54. def __str__(self):
  55. rc = '-{}'.format(self.rc) if self.rc else ''
  56. edition = '-{}'.format(self.edition) if self.edition else ''
  57. return '.'.join(map(str, self[:3])) + edition + rc
  58. BLACKLIST = [ # List of versions known to be broken and should not be used
  59. Version.parse('18.03.0-ce-rc2'),
  60. ]
  61. def group_versions(versions):
  62. """Group versions by `major.minor` releases.
  63. Example:
  64. >>> group_versions([
  65. Version(1, 0, 0),
  66. Version(2, 0, 0, 'rc1'),
  67. Version(2, 0, 0),
  68. Version(2, 1, 0),
  69. ])
  70. [
  71. [Version(1, 0, 0)],
  72. [Version(2, 0, 0), Version(2, 0, 0, 'rc1')],
  73. [Version(2, 1, 0)],
  74. ]
  75. """
  76. return list(
  77. list(releases)
  78. for _, releases
  79. in itertools.groupby(versions, operator.attrgetter('major_minor'))
  80. )
  81. def get_latest_versions(versions, num=1):
  82. """Return a list of the most recent versions for each major.minor version
  83. group.
  84. """
  85. versions = group_versions(versions)
  86. num = min(len(versions), num)
  87. return [versions[index][0] for index in range(num)]
  88. def get_default(versions):
  89. """Return a :class:`Version` for the latest non-rc version."""
  90. for version in versions:
  91. if not version.rc:
  92. return version
  93. def get_versions(tags):
  94. for tag in tags:
  95. try:
  96. v = Version.parse(tag['name'])
  97. if v not in BLACKLIST:
  98. yield v
  99. except ValueError:
  100. print("Skipping invalid tag: {name}".format(**tag), file=sys.stderr)
  101. def get_github_releases(projects):
  102. """Query the Github API for a list of version tags and return them in
  103. sorted order.
  104. See https://developer.github.com/v3/repos/#list-tags
  105. """
  106. versions = []
  107. for project in projects:
  108. url = '{}/{}/tags'.format(GITHUB_API, project)
  109. response = requests.get(url)
  110. response.raise_for_status()
  111. versions.extend(get_versions(response.json()))
  112. return sorted(versions, reverse=True, key=operator.attrgetter('order'))
  113. def parse_args(argv):
  114. parser = argparse.ArgumentParser(description=__doc__)
  115. parser.add_argument('project', help="Github project name (ex: docker/docker)")
  116. parser.add_argument('command', choices=['recent', 'default'])
  117. parser.add_argument('-n', '--num', type=int, default=2,
  118. help="Number of versions to return from `recent`")
  119. return parser.parse_args(argv)
  120. def main(argv=None):
  121. args = parse_args(argv)
  122. versions = get_github_releases(args.project.split(','))
  123. if args.command == 'recent':
  124. print(' '.join(map(str, get_latest_versions(versions, args.num))))
  125. elif args.command == 'default':
  126. print(get_default(versions))
  127. else:
  128. raise ValueError("Unknown command {}".format(args.command))
  129. if __name__ == "__main__":
  130. main()