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