make_release_notes.py 7.5 KB

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