make_changelog.py 18 KB

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