make_release_notes.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. #!/usr/bin/env python3
  2. # Copyright 2019 Google LLC
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. """Converts GitHub flavored markdown changelogs to release notes.
  16. """
  17. import argparse
  18. import re
  19. import subprocess
  20. import string
  21. NO_HEADING = 'PRODUCT HAS NO HEADING'
  22. PRODUCTS = {
  23. 'FirebaseABTesting/CHANGELOG.md': '{{ab_testing}}',
  24. 'FirebaseAppCheck/CHANGELOG.md': 'App Check',
  25. 'FirebaseAppDistribution/CHANGELOG.md': 'App Distribution',
  26. 'FirebaseAuth/CHANGELOG.md': '{{auth}}',
  27. 'FirebaseCore/CHANGELOG.md': NO_HEADING,
  28. 'Crashlytics/CHANGELOG.md': '{{crashlytics}}',
  29. 'FirebaseDatabase/CHANGELOG.md': '{{database}}',
  30. 'FirebaseDynamicLinks/CHANGELOG.md': '{{ddls}}',
  31. 'FirebaseInAppMessaging/CHANGELOG.md': '{{inapp_messaging}}',
  32. 'FirebaseInstallations/CHANGELOG.md': 'Installations',
  33. 'FirebaseMessaging/CHANGELOG.md': '{{messaging}}',
  34. 'FirebaseStorage/CHANGELOG.md': '{{storage}}',
  35. 'Firestore/CHANGELOG.md': '{{firestore}}',
  36. 'FirebaseFunctions/CHANGELOG.md': '{{cloud_functions}}',
  37. 'FirebaseRemoteConfig/CHANGELOG.md': '{{remote_config}}',
  38. 'FirebasePerformance/CHANGELOG.md': '{{perfmon}}',
  39. 'FirebaseVertexAI/CHANGELOG.md': '{{firebase_vertexai}}',
  40. # Assumes firebase-ios-sdk and data-connect-ios-sdk are cloned to the same
  41. # directory.
  42. '../data-connect-ios-sdk/CHANGELOG.md': '{{data_connect_short}}',
  43. }
  44. def main():
  45. local_repo = find_local_repo()
  46. parser = argparse.ArgumentParser(description='Create release notes.')
  47. parser.add_argument('--repo', '-r', default=local_repo,
  48. help='Specify which GitHub repo is local.')
  49. parser.add_argument('--only', metavar='VERSION',
  50. help='Convert only a specific version')
  51. parser.add_argument('--all', action='store_true',
  52. help='Emits entries for all versions')
  53. parser.add_argument('changelog',
  54. help='The CHANGELOG.md file to parse')
  55. args = parser.parse_args()
  56. if args.all:
  57. text = read_file(args.changelog)
  58. else:
  59. text = read_changelog_section(args.changelog, args.only)
  60. product = None
  61. if not args.all:
  62. product = PRODUCTS.get(args.changelog)
  63. renderer = Renderer(args.repo, product)
  64. translator = Translator(renderer)
  65. result = translator.translate(text)
  66. print(result)
  67. def find_local_repo():
  68. url = subprocess.check_output(['git', 'config', '--get', 'remote.origin.url'],
  69. text=True, errors='replace')
  70. # ssh or https style URL
  71. m = re.match(r'^(?:git@github\.com:|https://github\.com/)(.*)\.git$', url)
  72. if m:
  73. return m.group(1)
  74. raise LookupError('Can\'t figure local repo from remote URL %s' % url)
  75. CHANGE_TYPE_MAPPING = {
  76. 'added': 'feature'
  77. }
  78. class Renderer(object):
  79. def __init__(self, local_repo, product):
  80. self.local_repo = local_repo
  81. self.product = product
  82. def heading(self, heading):
  83. if self.product:
  84. if self.product == NO_HEADING:
  85. return ''
  86. else:
  87. return '### %s\n' % self.product
  88. return heading
  89. def bullet(self, spacing):
  90. """Renders a bullet in a list.
  91. All bulleted lists in devsite are '*' style.
  92. """
  93. return '%s* ' % spacing
  94. def change_type(self, tag):
  95. """Renders a change type tag as the appropriate double-braced macro.
  96. That is "[fixed]" is rendered as "{{fixed}}".
  97. """
  98. tag = CHANGE_TYPE_MAPPING.get(tag, tag)
  99. return '{{%s}}' % tag
  100. def url(self, url):
  101. m = re.match(r'^(?:https:)?(//github.com/(.*)/issues/(\d+))$', url)
  102. if m:
  103. link = m.group(1)
  104. repo = m.group(2)
  105. issue = m.group(3)
  106. if repo == self.local_repo:
  107. text = '#' + issue
  108. else:
  109. text = repo + '#' + issue
  110. return '[%s](%s)' % (text, link)
  111. return url
  112. def local_issue_link(self, issues):
  113. """Renders a local issue link as a proper markdown URL.
  114. Transforms (#1234, #1235) into
  115. ([#1234](//github.com/firebase/firebase-ios-sdk/issues/1234),
  116. [#1235](//github.com/firebase/firebase-ios-sdk/issues/1235)).
  117. """
  118. issue_link_list = []
  119. issue_list = issues.split(", ")
  120. translate = str.maketrans('', '', string.punctuation)
  121. for issue in issue_list:
  122. issue = issue.translate(translate)
  123. link = '//github.com/%s/issues/%s' % (self.local_repo, issue)
  124. issue_link_list.append('[#%s](%s)' % (issue, link))
  125. return "(" + ", ".join(issue_link_list) + ")"
  126. def text(self, text):
  127. """Passes through any other text."""
  128. return text
  129. class Translator(object):
  130. def __init__(self, renderer):
  131. self.renderer = renderer
  132. def translate(self, text):
  133. result = ''
  134. while text:
  135. for key in self.rules:
  136. rule = getattr(self, key)
  137. m = rule.match(text)
  138. if not m:
  139. continue
  140. callback = getattr(self, 'parse_' + key)
  141. callback_result = callback(m)
  142. result += callback_result
  143. text = text[len(m.group(0)):]
  144. break
  145. return result
  146. heading = re.compile(
  147. r'^#{1,6} .*'
  148. )
  149. def parse_heading(self, m):
  150. return self.renderer.heading(m.group(0))
  151. bullet = re.compile(
  152. r'^(\s*)[*+-] '
  153. )
  154. def parse_bullet(self, m):
  155. return self.renderer.bullet(m.group(1))
  156. change_type = re.compile(
  157. r'\[' # opening square bracket
  158. r'(\w+)' # tag word (like "feature" or "changed")
  159. r'\]' # closing square bracket
  160. r'(?!\()' # not followed by opening paren (that would be a link)
  161. )
  162. def parse_change_type(self, m):
  163. return self.renderer.change_type(m.group(1))
  164. url = re.compile(r'^(https?://[^\s<]+[^<.,:;"\')\]\s])')
  165. def parse_url(self, m):
  166. return self.renderer.url(m.group(1))
  167. local_issue_link = re.compile(
  168. r'\(' # opening paren
  169. r'(#(\d+)(, )?)+' # list of hash and issue number, comma-delimited
  170. r'\)' # closing paren
  171. )
  172. def parse_local_issue_link(self, m):
  173. return self.renderer.local_issue_link(m.group(0))
  174. text = re.compile(
  175. r'^[\s\S]+?(?=[(\[\n]|https?://|$)'
  176. )
  177. def parse_text(self, m):
  178. return self.renderer.text(m.group(0))
  179. rules = [
  180. 'heading', 'bullet', 'change_type', 'url', 'local_issue_link', 'text'
  181. ]
  182. def read_file(filename):
  183. """Reads the contents of the file as a single string."""
  184. with open(filename, 'r') as fd:
  185. return fd.read()
  186. def read_changelog_section(filename, single_version=None):
  187. """Reads a single section of the changelog from the given filename.
  188. If single_version is None, reads the first section with a number in its
  189. heading. Otherwise, reads the first section with single_version in its
  190. heading.
  191. Args:
  192. - single_version: specifies a string to look for in headings.
  193. Returns:
  194. A string containing the heading and contents of the heading.
  195. """
  196. with open(filename, 'r') as fd:
  197. # Discard all lines until we see a heading that either has the version the
  198. # user asked for or any version.
  199. if single_version:
  200. initial_heading = re.compile(r'^#{1,6} .*%s' % re.escape(single_version))
  201. else:
  202. initial_heading = re.compile(r'^#{1,6} ([^\d]*)\d')
  203. heading = re.compile(r'^#{1,6} ')
  204. initial = True
  205. result = []
  206. for line in fd:
  207. if initial:
  208. if initial_heading.match(line):
  209. initial = False
  210. result.append(line)
  211. else:
  212. if heading.match(line):
  213. break
  214. result.append(line)
  215. # Prune extra newlines
  216. while result and result[-1] == '\n':
  217. result.pop()
  218. return ''.join(result)
  219. if __name__ == '__main__':
  220. main()