1
0

versions.py 3.7 KB

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