make_release_notes.py 8.0 KB

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