fetch_releases.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import json
  2. import optparse
  3. import os
  4. import re
  5. import requests
  6. from packaging.version import Version
  7. IGNORE_VERSIONS_BEFORE = '4.3'
  8. def version_number_and_type(git_hash, ap_source_subdir):
  9. url = (
  10. "https://raw.githubusercontent.com/ArduPilot/ardupilot/"
  11. f"{git_hash}/{ap_source_subdir}/version.h"
  12. )
  13. response = requests.get(url=url)
  14. if response.status_code != 200:
  15. print(response.text)
  16. print(url)
  17. raise Exception(
  18. "Couldn't fetch version.h from github server. "
  19. f"Got status code {response.status_code}"
  20. )
  21. exp = re.compile(
  22. r'#define FIRMWARE_VERSION (\d+),(\d+),(\d+),FIRMWARE_VERSION_TYPE_(\w+)' # noqa
  23. )
  24. matches = re.findall(exp, response.text)
  25. major, minor, patch, fw_type = matches[0]
  26. fw_type = fw_type.lower()
  27. if fw_type == 'official':
  28. # to avoid any confusion, beta is also 'official' ;-)
  29. fw_type = 'stable'
  30. return f'{major}.{minor}.{patch}', fw_type
  31. def fetch_tags_from_github():
  32. url = 'https://api.github.com/repos/ardupilot/ardupilot/git/refs/tags'
  33. headers = {
  34. 'X-GitHub-Api-Version': '2022-11-28',
  35. 'Accept': 'application/vnd.github+json'
  36. }
  37. token = os.getenv("CBS_GITHUB_ACCESS_TOKEN")
  38. if token:
  39. headers['Authorization'] = f"Bearer {token}"
  40. response = requests.get(url=url, headers=headers)
  41. if response.status_code != 200:
  42. print(response.text)
  43. print(url)
  44. raise Exception(
  45. "Couldn't fetch tags from github server. "
  46. f"Got status code {response.status_code}"
  47. )
  48. tags_objs = response.json()
  49. return tags_objs
  50. def remove_duplicate_entries(releases):
  51. temp = {}
  52. for release in releases:
  53. # if we have already seen a version with similar hash
  54. # and we now see a beta release with same hash, we skip it
  55. if temp.get(release['commit_reference']) and \
  56. release['release_type'] == 'beta':
  57. continue
  58. temp[release['commit_reference']] = release
  59. return list(temp.values())
  60. def construct_vehicle_versions_list(vehicle, ap_source_subdir,
  61. fw_server_vehicle_sdir,
  62. tag_filter_exps, tags):
  63. ret = []
  64. for tag_info in tags:
  65. tag = tag_info['ref'].replace('refs/tags/', '')
  66. matches = []
  67. for exp in tag_filter_exps:
  68. # the regexes capture two groups
  69. # first group is the matched substring itself
  70. # second group is the tag body (e.g., beta, stable, 4.5.1 etc)
  71. matches.extend(re.findall(re.compile(exp), tag))
  72. if matches:
  73. matched_string, tag_body = matches[0]
  74. if len(matched_string) < len(tag):
  75. print(
  76. f"Partial match. Ignoring. Matched '{matched_string}' "
  77. f"in '{tag}'."
  78. )
  79. continue
  80. try:
  81. v_num, v_type = version_number_and_type(
  82. tag_info['object']['sha'],
  83. ap_source_subdir
  84. )
  85. except Exception as e:
  86. print(f'Cannot determine version number for tag {tag}')
  87. print(e)
  88. continue
  89. if Version(v_num) < Version(IGNORE_VERSIONS_BEFORE):
  90. print(f"{v_num} Version too old. Ignoring.")
  91. continue
  92. if re.search(r'\d+\.\d+\.\d+', tag_body):
  93. # we do stable version tags in this format
  94. # e.g. Rover-4.5.1, Copter-4.5.1, where Rover and Copter
  95. # are prefixes and 4.5.1 is the tag body
  96. # artifacts for these versions are stored in firmware
  97. # server at stable-x.y.z subdirs
  98. afcts_url = (
  99. f'https://firmware.ardupilot.org/{fw_server_vehicle_sdir}'
  100. f'/stable-{tag_body}'
  101. )
  102. else:
  103. afcts_url = (
  104. f'https://firmware.ardupilot.org/{fw_server_vehicle_sdir}'
  105. f'/{tag_body}'
  106. )
  107. ret.append({
  108. 'release_type': v_type,
  109. 'version_number': v_num,
  110. 'ap_build_artifacts_url': afcts_url,
  111. 'commit_reference': tag_info['object']['sha']
  112. })
  113. ret = remove_duplicate_entries(ret)
  114. # entry for master
  115. ret.append({
  116. 'release_type': 'latest',
  117. 'version_number': 'NA',
  118. 'ap_build_artifacts_url': (
  119. f'https://firmware.ardupilot.org/{fw_server_vehicle_sdir}/latest'
  120. ),
  121. 'commit_reference': 'refs/heads/master'
  122. })
  123. return {
  124. 'name': vehicle,
  125. 'releases': ret
  126. }
  127. def run(base_dir, remote_name):
  128. remotes_json_path = os.path.join(base_dir, 'configs', 'remotes.json')
  129. tags = fetch_tags_from_github()
  130. vehicles = []
  131. vehicles.append(construct_vehicle_versions_list(
  132. "Copter",
  133. "ArduCopter",
  134. "Copter",
  135. [
  136. "(ArduCopter-(beta-4.3|beta|stable))",
  137. "(Copter-(\d+\.\d+\.\d+))" # noqa
  138. ],
  139. tags
  140. ))
  141. vehicles.append(construct_vehicle_versions_list(
  142. "Plane",
  143. "ArduPlane",
  144. "Plane",
  145. [
  146. "(ArduPlane-(beta-4.3|beta|stable))",
  147. "(Plane-(\d+\.\d+\.\d+))" # noqa
  148. ],
  149. tags
  150. ))
  151. vehicles.append(construct_vehicle_versions_list(
  152. "Rover",
  153. "Rover",
  154. "Rover",
  155. [
  156. "(APMrover2-(beta-4.3|beta|stable))",
  157. "(Rover-(\d+\.\d+\.\d+))" # noqa
  158. ],
  159. tags
  160. ))
  161. vehicles.append(construct_vehicle_versions_list(
  162. "Sub",
  163. "ArduSub",
  164. "Sub",
  165. [
  166. "(ArduSub-(beta-4.3|beta|stable))",
  167. "(Sub-(\d+\.\d+\.\d+))" # noqa
  168. ],
  169. tags
  170. ))
  171. vehicles.append(construct_vehicle_versions_list(
  172. "Tracker",
  173. "AntennaTracker",
  174. "AntennaTracker",
  175. [
  176. "(AntennaTracker-(beta-4.3|beta|stable))",
  177. "(Tracker-(\d+\.\d+\.\d+))" # noqa
  178. ],
  179. tags
  180. ))
  181. vehicles.append(construct_vehicle_versions_list(
  182. "Blimp",
  183. "Blimp",
  184. "Blimp",
  185. [
  186. "(Blimp-(beta-4.3|beta|stable|\d+\.\d+\.\d+))" # noqa
  187. ],
  188. tags
  189. ))
  190. vehicles.append(construct_vehicle_versions_list(
  191. "Heli",
  192. "ArduCopter",
  193. "Copter",
  194. [
  195. "(ArduCopter-(beta-4.3|beta|stable)-heli)"
  196. ],
  197. tags
  198. ))
  199. remotes_json = {
  200. "name": remote_name,
  201. "url": "https://github.com/ardupilot/ardupilot.git",
  202. "vehicles": vehicles
  203. }
  204. try:
  205. with open(remotes_json_path, 'r') as f:
  206. remotes = json.loads(f.read())
  207. # remove existing remote entry from the list
  208. temp = []
  209. for remote in remotes:
  210. if remote['name'] != remote_name:
  211. temp.append(remote)
  212. remotes = temp
  213. except Exception as e:
  214. print(e)
  215. print("Writing to empty file")
  216. remotes = []
  217. with open(remotes_json_path, 'w') as f:
  218. remotes.append(remotes_json)
  219. f.write(json.dumps(remotes, indent=2))
  220. print(f"Wrote {remotes_json_path}")
  221. if __name__ == "__main__":
  222. parser = optparse.OptionParser("fetch_releases.py")
  223. parser.add_option(
  224. "", "--basedir", type="string",
  225. default=os.path.abspath(
  226. os.path.join(os.path.dirname(__file__), "..", "base")
  227. ),
  228. help="base directory"
  229. )
  230. parser.add_option(
  231. "", "--remotename", type="string",
  232. default="ardupilot",
  233. help="Remote name to write in json file"
  234. )
  235. cmd_opts, cmd_args = parser.parse_args()
  236. basedir = os.path.abspath(cmd_opts.basedir)
  237. remotename = cmd_opts.remotename
  238. run(base_dir=basedir, remote_name=remotename)