versions.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  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. def group_versions(versions):
  59. """Group versions by `major.minor` releases.
  60. Example:
  61. >>> group_versions([
  62. Version(1, 0, 0),
  63. Version(2, 0, 0, 'rc1'),
  64. Version(2, 0, 0),
  65. Version(2, 1, 0),
  66. ])
  67. [
  68. [Version(1, 0, 0)],
  69. [Version(2, 0, 0), Version(2, 0, 0, 'rc1')],
  70. [Version(2, 1, 0)],
  71. ]
  72. """
  73. return list(
  74. list(releases)
  75. for _, releases
  76. in itertools.groupby(versions, operator.attrgetter('major_minor'))
  77. )
  78. def get_latest_versions(versions, num=1):
  79. """Return a list of the most recent versions for each major.minor version
  80. group.
  81. """
  82. versions = group_versions(versions)
  83. num = min(len(versions), num)
  84. return [versions[index][0] for index in range(num)]
  85. def get_default(versions):
  86. """Return a :class:`Version` for the latest non-rc version."""
  87. for version in versions:
  88. if not version.rc:
  89. return version
  90. def get_versions(tags):
  91. for tag in tags:
  92. try:
  93. yield Version.parse(tag['name'])
  94. except ValueError:
  95. print("Skipping invalid tag: {name}".format(**tag), file=sys.stderr)
  96. def get_github_releases(projects):
  97. """Query the Github API for a list of version tags and return them in
  98. sorted order.
  99. See https://developer.github.com/v3/repos/#list-tags
  100. """
  101. versions = []
  102. for project in projects:
  103. url = '{}/{}/tags'.format(GITHUB_API, project)
  104. response = requests.get(url)
  105. response.raise_for_status()
  106. versions.extend(get_versions(response.json()))
  107. return sorted(versions, reverse=True, key=operator.attrgetter('order'))
  108. def parse_args(argv):
  109. parser = argparse.ArgumentParser(description=__doc__)
  110. parser.add_argument('project', help="Github project name (ex: docker/docker)")
  111. parser.add_argument('command', choices=['recent', 'default'])
  112. parser.add_argument('-n', '--num', type=int, default=2,
  113. help="Number of versions to return from `recent`")
  114. return parser.parse_args(argv)
  115. def main(argv=None):
  116. args = parse_args(argv)
  117. versions = get_github_releases(args.project.split(','))
  118. if args.command == 'recent':
  119. print(' '.join(map(str, get_latest_versions(versions, args.num))))
  120. elif args.command == 'default':
  121. print(get_default(versions))
  122. else:
  123. raise ValueError("Unknown command {}".format(args.command))
  124. if __name__ == "__main__":
  125. main()