make_changelog.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. from __future__ import annotations
  2. # Allow direct execution
  3. import os
  4. import sys
  5. sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
  6. import enum
  7. import itertools
  8. import json
  9. import logging
  10. import re
  11. from collections import defaultdict
  12. from dataclasses import dataclass
  13. from functools import lru_cache
  14. from pathlib import Path
  15. from devscripts.utils import read_file, run_process, write_file
  16. BASE_URL = 'https://github.com'
  17. LOCATION_PATH = Path(__file__).parent
  18. HASH_LENGTH = 7
  19. logger = logging.getLogger(__name__)
  20. class CommitGroup(enum.Enum):
  21. PRIORITY = 'Important'
  22. CORE = 'Core'
  23. EXTRACTOR = 'Extractor'
  24. DOWNLOADER = 'Downloader'
  25. POSTPROCESSOR = 'Postprocessor'
  26. MISC = 'Misc.'
  27. @classmethod
  28. @property
  29. def ignorable_prefixes(cls):
  30. return ('core', 'downloader', 'extractor', 'misc', 'postprocessor', 'upstream')
  31. @classmethod
  32. @lru_cache
  33. def commit_lookup(cls):
  34. return {
  35. name: group
  36. for group, names in {
  37. cls.PRIORITY: {'priority'},
  38. cls.CORE: {
  39. 'aes',
  40. 'cache',
  41. 'compat_utils',
  42. 'compat',
  43. 'cookies',
  44. 'core',
  45. 'dependencies',
  46. 'jsinterp',
  47. 'outtmpl',
  48. 'plugins',
  49. 'update',
  50. 'upstream',
  51. 'utils',
  52. },
  53. cls.MISC: {
  54. 'build',
  55. 'cleanup',
  56. 'devscripts',
  57. 'docs',
  58. 'misc',
  59. 'test',
  60. },
  61. cls.EXTRACTOR: {'extractor'},
  62. cls.DOWNLOADER: {'downloader'},
  63. cls.POSTPROCESSOR: {'postprocessor'},
  64. }.items()
  65. for name in names
  66. }
  67. @classmethod
  68. def get(cls, value):
  69. result = cls.commit_lookup().get(value)
  70. if result:
  71. logger.debug(f'Mapped {value!r} => {result.name}')
  72. return result
  73. @dataclass
  74. class Commit:
  75. hash: str | None
  76. short: str
  77. authors: list[str]
  78. def __str__(self):
  79. result = f'{self.short!r}'
  80. if self.hash:
  81. result += f' ({self.hash[:HASH_LENGTH]})'
  82. if self.authors:
  83. authors = ', '.join(self.authors)
  84. result += f' by {authors}'
  85. return result
  86. @dataclass
  87. class CommitInfo:
  88. details: str | None
  89. sub_details: tuple[str, ...]
  90. message: str
  91. issues: list[str]
  92. commit: Commit
  93. fixes: list[Commit]
  94. def key(self):
  95. return ((self.details or '').lower(), self.sub_details, self.message)
  96. def unique(items):
  97. return sorted({item.strip().lower(): item for item in items if item}.values())
  98. class Changelog:
  99. MISC_RE = re.compile(r'(?:^|\b)(?:lint(?:ing)?|misc|format(?:ting)?|fixes)(?:\b|$)', re.IGNORECASE)
  100. ALWAYS_SHOWN = (CommitGroup.PRIORITY,)
  101. def __init__(self, groups, repo, collapsible=False):
  102. self._groups = groups
  103. self._repo = repo
  104. self._collapsible = collapsible
  105. def __str__(self):
  106. return '\n'.join(self._format_groups(self._groups)).replace('\t', ' ')
  107. def _format_groups(self, groups):
  108. first = True
  109. for item in CommitGroup:
  110. if self._collapsible and item not in self.ALWAYS_SHOWN and first:
  111. first = False
  112. yield '\n<details><summary><h3>Changelog</h3></summary>\n'
  113. group = groups[item]
  114. if group:
  115. yield self.format_module(item.value, group)
  116. if self._collapsible:
  117. yield '\n</details>'
  118. def format_module(self, name, group):
  119. result = f'\n#### {name} changes\n' if name else '\n'
  120. return result + '\n'.join(self._format_group(group))
  121. def _format_group(self, group):
  122. sorted_group = sorted(group, key=CommitInfo.key)
  123. detail_groups = itertools.groupby(sorted_group, lambda item: (item.details or '').lower())
  124. for _, items in detail_groups:
  125. items = list(items)
  126. details = items[0].details
  127. if details == 'cleanup':
  128. items = self._prepare_cleanup_misc_items(items)
  129. prefix = '-'
  130. if details:
  131. if len(items) == 1:
  132. prefix = f'- **{details}**:'
  133. else:
  134. yield f'- **{details}**'
  135. prefix = '\t-'
  136. sub_detail_groups = itertools.groupby(items, lambda item: tuple(map(str.lower, item.sub_details)))
  137. for sub_details, entries in sub_detail_groups:
  138. if not sub_details:
  139. for entry in entries:
  140. yield f'{prefix} {self.format_single_change(entry)}'
  141. continue
  142. entries = list(entries)
  143. sub_prefix = f'{prefix} {", ".join(entries[0].sub_details)}'
  144. if len(entries) == 1:
  145. yield f'{sub_prefix}: {self.format_single_change(entries[0])}'
  146. continue
  147. yield sub_prefix
  148. for entry in entries:
  149. yield f'\t{prefix} {self.format_single_change(entry)}'
  150. def _prepare_cleanup_misc_items(self, items):
  151. cleanup_misc_items = defaultdict(list)
  152. sorted_items = []
  153. for item in items:
  154. if self.MISC_RE.search(item.message):
  155. cleanup_misc_items[tuple(item.commit.authors)].append(item)
  156. else:
  157. sorted_items.append(item)
  158. for commit_infos in cleanup_misc_items.values():
  159. sorted_items.append(CommitInfo(
  160. 'cleanup', ('Miscellaneous',), ', '.join(
  161. self._format_message_link(None, info.commit.hash).strip()
  162. for info in sorted(commit_infos, key=lambda item: item.commit.hash or '')),
  163. [], Commit(None, '', commit_infos[0].commit.authors), []))
  164. return sorted_items
  165. def format_single_change(self, info):
  166. message = self._format_message_link(info.message, info.commit.hash)
  167. if info.issues:
  168. message = message.replace('\n', f' ({self._format_issues(info.issues)})\n', 1)
  169. if info.commit.authors:
  170. message = message.replace('\n', f' by {self._format_authors(info.commit.authors)}\n', 1)
  171. if info.fixes:
  172. fix_message = ', '.join(f'{self._format_message_link(None, fix.hash)}' for fix in info.fixes)
  173. authors = sorted({author for fix in info.fixes for author in fix.authors}, key=str.casefold)
  174. if authors != info.commit.authors:
  175. fix_message = f'{fix_message} by {self._format_authors(authors)}'
  176. message = message.replace('\n', f' (With fixes in {fix_message})\n', 1)
  177. return message[:-1]
  178. def _format_message_link(self, message, hash):
  179. assert message or hash, 'Improperly defined commit message or override'
  180. message = message if message else hash[:HASH_LENGTH]
  181. if not hash:
  182. return f'{message}\n'
  183. return f'[{message}\n'.replace('\n', f']({self.repo_url}/commit/{hash})\n', 1)
  184. def _format_issues(self, issues):
  185. return ', '.join(f'[#{issue}]({self.repo_url}/issues/{issue})' for issue in issues)
  186. @staticmethod
  187. def _format_authors(authors):
  188. return ', '.join(f'[{author}]({BASE_URL}/{author})' for author in authors)
  189. @property
  190. def repo_url(self):
  191. return f'{BASE_URL}/{self._repo}'
  192. class CommitRange:
  193. COMMAND = 'git'
  194. COMMIT_SEPARATOR = '-----'
  195. AUTHOR_INDICATOR_RE = re.compile(r'Authored by:? ', re.IGNORECASE)
  196. MESSAGE_RE = re.compile(r'''
  197. (?:\[(?P<prefix>[^\]]+)\]\ )?
  198. (?:(?P<sub_details>`?[^:`]+`?): )?
  199. (?P<message>.+?)
  200. (?:\ \((?P<issues>\#\d+(?:,\ \#\d+)*)\))?
  201. ''', re.VERBOSE | re.DOTALL)
  202. EXTRACTOR_INDICATOR_RE = re.compile(r'(?:Fix|Add)\s+Extractors?', re.IGNORECASE)
  203. FIXES_RE = re.compile(r'(?i:Fix(?:es)?(?:\s+bugs?)?(?:\s+in|\s+for)?|Revert)\s+([\da-f]{40})')
  204. UPSTREAM_MERGE_RE = re.compile(r'Update to ytdl-commit-([\da-f]+)')
  205. def __init__(self, start, end, default_author=None):
  206. self._start, self._end = start, end
  207. self._commits, self._fixes = self._get_commits_and_fixes(default_author)
  208. self._commits_added = []
  209. def __iter__(self):
  210. return iter(itertools.chain(self._commits.values(), self._commits_added))
  211. def __len__(self):
  212. return len(self._commits) + len(self._commits_added)
  213. def __contains__(self, commit):
  214. if isinstance(commit, Commit):
  215. if not commit.hash:
  216. return False
  217. commit = commit.hash
  218. return commit in self._commits
  219. def _get_commits_and_fixes(self, default_author):
  220. result = run_process(
  221. self.COMMAND, 'log', f'--format=%H%n%s%n%b%n{self.COMMIT_SEPARATOR}',
  222. f'{self._start}..{self._end}' if self._start else self._end).stdout
  223. commits = {}
  224. fixes = defaultdict(list)
  225. lines = iter(result.splitlines(False))
  226. for i, commit_hash in enumerate(lines):
  227. short = next(lines)
  228. skip = short.startswith('Release ') or short == '[version] update'
  229. authors = [default_author] if default_author else []
  230. for line in iter(lambda: next(lines), self.COMMIT_SEPARATOR):
  231. match = self.AUTHOR_INDICATOR_RE.match(line)
  232. if match:
  233. authors = sorted(map(str.strip, line[match.end():].split(',')), key=str.casefold)
  234. commit = Commit(commit_hash, short, authors)
  235. if skip and (self._start or not i):
  236. logger.debug(f'Skipped commit: {commit}')
  237. continue
  238. elif skip:
  239. logger.debug(f'Reached Release commit, breaking: {commit}')
  240. break
  241. fix_match = self.FIXES_RE.search(commit.short)
  242. if fix_match:
  243. commitish = fix_match.group(1)
  244. fixes[commitish].append(commit)
  245. commits[commit.hash] = commit
  246. for commitish, fix_commits in fixes.items():
  247. if commitish in commits:
  248. hashes = ', '.join(commit.hash[:HASH_LENGTH] for commit in fix_commits)
  249. logger.info(f'Found fix(es) for {commitish[:HASH_LENGTH]}: {hashes}')
  250. for fix_commit in fix_commits:
  251. del commits[fix_commit.hash]
  252. else:
  253. logger.debug(f'Commit with fixes not in changes: {commitish[:HASH_LENGTH]}')
  254. return commits, fixes
  255. def apply_overrides(self, overrides):
  256. for override in overrides:
  257. when = override.get('when')
  258. if when and when not in self and when != self._start:
  259. logger.debug(f'Ignored {when!r}, not in commits {self._start!r}')
  260. continue
  261. override_hash = override.get('hash') or when
  262. if override['action'] == 'add':
  263. commit = Commit(override.get('hash'), override['short'], override.get('authors') or [])
  264. logger.info(f'ADD {commit}')
  265. self._commits_added.append(commit)
  266. elif override['action'] == 'remove':
  267. if override_hash in self._commits:
  268. logger.info(f'REMOVE {self._commits[override_hash]}')
  269. del self._commits[override_hash]
  270. elif override['action'] == 'change':
  271. if override_hash not in self._commits:
  272. continue
  273. commit = Commit(override_hash, override['short'], override.get('authors') or [])
  274. logger.info(f'CHANGE {self._commits[commit.hash]} -> {commit}')
  275. self._commits[commit.hash] = commit
  276. self._commits = {key: value for key, value in reversed(self._commits.items())}
  277. def groups(self):
  278. group_dict = defaultdict(list)
  279. for commit in self:
  280. upstream_re = self.UPSTREAM_MERGE_RE.search(commit.short)
  281. if upstream_re:
  282. commit.short = f'[core/upstream] Merged with youtube-dl {upstream_re.group(1)}'
  283. match = self.MESSAGE_RE.fullmatch(commit.short)
  284. if not match:
  285. logger.error(f'Error parsing short commit message: {commit.short!r}')
  286. continue
  287. prefix, sub_details_alt, message, issues = match.groups()
  288. issues = [issue.strip()[1:] for issue in issues.split(',')] if issues else []
  289. if prefix:
  290. groups, details, sub_details = zip(*map(self.details_from_prefix, prefix.split(',')))
  291. group = next(iter(filter(None, groups)), None)
  292. details = ', '.join(unique(details))
  293. sub_details = list(itertools.chain.from_iterable(sub_details))
  294. else:
  295. group = CommitGroup.CORE
  296. details = None
  297. sub_details = []
  298. if sub_details_alt:
  299. sub_details.append(sub_details_alt)
  300. sub_details = tuple(unique(sub_details))
  301. if not group:
  302. if self.EXTRACTOR_INDICATOR_RE.search(commit.short):
  303. group = CommitGroup.EXTRACTOR
  304. else:
  305. group = CommitGroup.POSTPROCESSOR
  306. logger.warning(f'Failed to map {commit.short!r}, selected {group.name.lower()}')
  307. commit_info = CommitInfo(
  308. details, sub_details, message.strip(),
  309. issues, commit, self._fixes[commit.hash])
  310. logger.debug(f'Resolved {commit.short!r} to {commit_info!r}')
  311. group_dict[group].append(commit_info)
  312. return group_dict
  313. @staticmethod
  314. def details_from_prefix(prefix):
  315. if not prefix:
  316. return CommitGroup.CORE, None, ()
  317. prefix, _, details = prefix.partition('/')
  318. prefix = prefix.strip()
  319. details = details.strip()
  320. group = CommitGroup.get(prefix.lower())
  321. if group is CommitGroup.PRIORITY:
  322. prefix, _, details = details.partition('/')
  323. if not details and prefix and prefix not in CommitGroup.ignorable_prefixes:
  324. logger.debug(f'Replaced details with {prefix!r}')
  325. details = prefix or None
  326. if details == 'common':
  327. details = None
  328. if details:
  329. details, *sub_details = details.split(':')
  330. else:
  331. sub_details = []
  332. return group, details, sub_details
  333. def get_new_contributors(contributors_path, commits):
  334. contributors = set()
  335. if contributors_path.exists():
  336. for line in read_file(contributors_path).splitlines():
  337. author, _, _ = line.strip().partition(' (')
  338. authors = author.split('/')
  339. contributors.update(map(str.casefold, authors))
  340. new_contributors = set()
  341. for commit in commits:
  342. for author in commit.authors:
  343. author_folded = author.casefold()
  344. if author_folded not in contributors:
  345. contributors.add(author_folded)
  346. new_contributors.add(author)
  347. return sorted(new_contributors, key=str.casefold)
  348. if __name__ == '__main__':
  349. import argparse
  350. parser = argparse.ArgumentParser(
  351. description='Create a changelog markdown from a git commit range')
  352. parser.add_argument(
  353. 'commitish', default='HEAD', nargs='?',
  354. help='The commitish to create the range from (default: %(default)s)')
  355. parser.add_argument(
  356. '-v', '--verbosity', action='count', default=0,
  357. help='increase verbosity (can be used twice)')
  358. parser.add_argument(
  359. '-c', '--contributors', action='store_true',
  360. help='update CONTRIBUTORS file (default: %(default)s)')
  361. parser.add_argument(
  362. '--contributors-path', type=Path, default=LOCATION_PATH.parent / 'CONTRIBUTORS',
  363. help='path to the CONTRIBUTORS file')
  364. parser.add_argument(
  365. '--no-override', action='store_true',
  366. help='skip override json in commit generation (default: %(default)s)')
  367. parser.add_argument(
  368. '--override-path', type=Path, default=LOCATION_PATH / 'changelog_override.json',
  369. help='path to the changelog_override.json file')
  370. parser.add_argument(
  371. '--default-author', default='pukkandan',
  372. help='the author to use without a author indicator (default: %(default)s)')
  373. parser.add_argument(
  374. '--repo', default='yt-dlp/yt-dlp',
  375. help='the github repository to use for the operations (default: %(default)s)')
  376. parser.add_argument(
  377. '--collapsible', action='store_true',
  378. help='make changelog collapsible (default: %(default)s)')
  379. args = parser.parse_args()
  380. logging.basicConfig(
  381. datefmt='%Y-%m-%d %H-%M-%S', format='{asctime} | {levelname:<8} | {message}',
  382. level=logging.WARNING - 10 * args.verbosity, style='{', stream=sys.stderr)
  383. commits = CommitRange(None, args.commitish, args.default_author)
  384. if not args.no_override:
  385. if args.override_path.exists():
  386. overrides = json.loads(read_file(args.override_path))
  387. commits.apply_overrides(overrides)
  388. else:
  389. logger.warning(f'File {args.override_path.as_posix()} does not exist')
  390. logger.info(f'Loaded {len(commits)} commits')
  391. new_contributors = get_new_contributors(args.contributors_path, commits)
  392. if new_contributors:
  393. if args.contributors:
  394. write_file(args.contributors_path, '\n'.join(new_contributors) + '\n', mode='a')
  395. logger.info(f'New contributors: {", ".join(new_contributors)}')
  396. print(Changelog(commits.groups(), args.repo, args.collapsible))