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