versions.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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')):
  30. @classmethod
  31. def parse(cls, version):
  32. version = version.lstrip('v')
  33. version, _, rc = version.partition('-')
  34. major, minor, patch = version.split('.', 3)
  35. return cls(major, minor, patch, rc)
  36. @property
  37. def major_minor(self):
  38. return self.major, self.minor
  39. @property
  40. def order(self):
  41. """Return a representation that allows this object to be sorted
  42. correctly with the default comparator.
  43. """
  44. # rc releases should appear before official releases
  45. rc = (0, self.rc) if self.rc else (1, )
  46. return (int(self.major), int(self.minor), int(self.patch)) + rc
  47. def __str__(self):
  48. rc = '-{}'.format(self.rc) if self.rc else ''
  49. return '.'.join(map(str, self[:3])) + rc
  50. def group_versions(versions):
  51. """Group versions by `major.minor` releases.
  52. Example:
  53. >>> group_versions([
  54. Version(1, 0, 0),
  55. Version(2, 0, 0, 'rc1'),
  56. Version(2, 0, 0),
  57. Version(2, 1, 0),
  58. ])
  59. [
  60. [Version(1, 0, 0)],
  61. [Version(2, 0, 0), Version(2, 0, 0, 'rc1')],
  62. [Version(2, 1, 0)],
  63. ]
  64. """
  65. return list(
  66. list(releases)
  67. for _, releases
  68. in itertools.groupby(versions, operator.attrgetter('major_minor'))
  69. )
  70. def get_latest_versions(versions, num=1):
  71. """Return a list of the most recent versions for each major.minor version
  72. group.
  73. """
  74. versions = group_versions(versions)
  75. return [versions[index][0] for index in range(num)]
  76. def get_default(versions):
  77. """Return a :class:`Version` for the latest non-rc version."""
  78. for version in versions:
  79. if not version.rc:
  80. return version
  81. def get_versions(tags):
  82. for tag in tags:
  83. try:
  84. yield Version.parse(tag['name'])
  85. except ValueError:
  86. print("Skipping invalid tag: {name}".format(**tag), file=sys.stderr)
  87. def get_github_releases(project):
  88. """Query the Github API for a list of version tags and return them in
  89. sorted order.
  90. See https://developer.github.com/v3/repos/#list-tags
  91. """
  92. url = '{}/{}/tags'.format(GITHUB_API, project)
  93. response = requests.get(url)
  94. response.raise_for_status()
  95. versions = get_versions(response.json())
  96. return sorted(versions, reverse=True, key=operator.attrgetter('order'))
  97. def parse_args(argv):
  98. parser = argparse.ArgumentParser(description=__doc__)
  99. parser.add_argument('project', help="Github project name (ex: docker/docker)")
  100. parser.add_argument('command', choices=['recent', 'default'])
  101. parser.add_argument('-n', '--num', type=int, default=2,
  102. help="Number of versions to return from `recent`")
  103. return parser.parse_args(argv)
  104. def main(argv=None):
  105. args = parse_args(argv)
  106. versions = get_github_releases(args.project)
  107. if args.command == 'recent':
  108. print(' '.join(map(str, get_latest_versions(versions, args.num))))
  109. elif args.command == 'default':
  110. print(get_default(versions))
  111. else:
  112. raise ValueError("Unknown command {}".format(args.command))
  113. if __name__ == "__main__":
  114. main()