make_release_notes.py 7.9 KB

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