]>
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', | |
62b5c94c | 56 | 'formats', |
d400e261 | 57 | 'jsinterp', |
c365dba8 | 58 | 'networking', |
d400e261 SS |
59 | 'outtmpl', |
60 | 'plugins', | |
61 | 'update', | |
23c39a4b | 62 | 'upstream', |
d400e261 SS |
63 | 'utils', |
64 | }, | |
65 | cls.MISC: { | |
66 | 'build', | |
67 | 'cleanup', | |
68 | 'devscripts', | |
69 | 'docs', | |
70 | 'misc', | |
71 | 'test', | |
72 | }, | |
337734d4 | 73 | cls.EXTRACTOR: {'extractor', 'ie'}, |
74 | cls.DOWNLOADER: {'downloader', 'fd'}, | |
75 | cls.POSTPROCESSOR: {'postprocessor', 'pp'}, | |
d400e261 SS |
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: | |
392389b7 | 98 | result += f' ({self.hash[:HASH_LENGTH]})' |
d400e261 SS |
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 | ||
23c39a4b SS |
120 | def unique(items): |
121 | return sorted({item.strip().lower(): item for item in items if item}.values()) | |
122 | ||
123 | ||
d400e261 SS |
124 | class Changelog: |
125 | MISC_RE = re.compile(r'(?:^|\b)(?:lint(?:ing)?|misc|format(?:ting)?|fixes)(?:\b|$)', re.IGNORECASE) | |
23c39a4b | 126 | ALWAYS_SHOWN = (CommitGroup.PRIORITY,) |
d400e261 | 127 | |
23c39a4b | 128 | def __init__(self, groups, repo, collapsible=False): |
d400e261 SS |
129 | self._groups = groups |
130 | self._repo = repo | |
23c39a4b | 131 | self._collapsible = collapsible |
d400e261 SS |
132 | |
133 | def __str__(self): | |
134 | return '\n'.join(self._format_groups(self._groups)).replace('\t', ' ') | |
135 | ||
136 | def _format_groups(self, groups): | |
23c39a4b | 137 | first = True |
d400e261 | 138 | for item in CommitGroup: |
23c39a4b SS |
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 | ||
d400e261 SS |
143 | group = groups[item] |
144 | if group: | |
145 | yield self.format_module(item.value, group) | |
146 | ||
23c39a4b SS |
147 | if self._collapsible: |
148 | yield '\n</details>' | |
149 | ||
d400e261 SS |
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()) | |
93449642 SS |
157 | for _, items in detail_groups: |
158 | items = list(items) | |
159 | details = items[0].details | |
d400e261 SS |
160 | |
161 | if details == 'cleanup': | |
23c39a4b SS |
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-' | |
d400e261 | 171 | |
93449642 | 172 | sub_detail_groups = itertools.groupby(items, lambda item: tuple(map(str.lower, item.sub_details))) |
d400e261 SS |
173 | for sub_details, entries in sub_detail_groups: |
174 | if not sub_details: | |
175 | for entry in entries: | |
23c39a4b | 176 | yield f'{prefix} {self.format_single_change(entry)}' |
d400e261 SS |
177 | continue |
178 | ||
d400e261 | 179 | entries = list(entries) |
23c39a4b | 180 | sub_prefix = f'{prefix} {", ".join(entries[0].sub_details)}' |
d400e261 | 181 | if len(entries) == 1: |
23c39a4b | 182 | yield f'{sub_prefix}: {self.format_single_change(entries[0])}' |
d400e261 SS |
183 | continue |
184 | ||
23c39a4b | 185 | yield sub_prefix |
d400e261 | 186 | for entry in entries: |
23c39a4b | 187 | yield f'\t{prefix} {self.format_single_change(entry)}' |
d400e261 | 188 | |
23c39a4b | 189 | def _prepare_cleanup_misc_items(self, items): |
d400e261 | 190 | cleanup_misc_items = defaultdict(list) |
23c39a4b | 191 | sorted_items = [] |
d400e261 SS |
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: | |
23c39a4b | 196 | sorted_items.append(item) |
d400e261 | 197 | |
23c39a4b SS |
198 | for commit_infos in cleanup_misc_items.values(): |
199 | sorted_items.append(CommitInfo( | |
200 | 'cleanup', ('Miscellaneous',), ', '.join( | |
812cdfa0 | 201 | self._format_message_link(None, info.commit.hash).strip() |
23c39a4b SS |
202 | for info in sorted(commit_infos, key=lambda item: item.commit.hash or '')), |
203 | [], Commit(None, '', commit_infos[0].commit.authors), [])) | |
d400e261 | 204 | |
23c39a4b | 205 | return sorted_items |
d400e261 SS |
206 | |
207 | def format_single_change(self, info): | |
208 | message = self._format_message_link(info.message, info.commit.hash) | |
209 | if info.issues: | |
812cdfa0 | 210 | message = message.replace('\n', f' ({self._format_issues(info.issues)})\n', 1) |
d400e261 SS |
211 | |
212 | if info.commit.authors: | |
812cdfa0 | 213 | message = message.replace('\n', f' by {self._format_authors(info.commit.authors)}\n', 1) |
d400e261 SS |
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 | ||
812cdfa0 | 222 | message = message.replace('\n', f' (With fixes in {fix_message})\n', 1) |
d400e261 | 223 | |
812cdfa0 | 224 | return message[:-1] |
d400e261 SS |
225 | |
226 | def _format_message_link(self, message, hash): | |
227 | assert message or hash, 'Improperly defined commit message or override' | |
392389b7 | 228 | message = message if message else hash[:HASH_LENGTH] |
812cdfa0 | 229 | if not hash: |
230 | return f'{message}\n' | |
231 | return f'[{message}\n'.replace('\n', f']({self.repo_url}/commit/{hash})\n', 1) | |
d400e261 SS |
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''' | |
23c39a4b SS |
251 | (?:\[(?P<prefix>[^\]]+)\]\ )? |
252 | (?:(?P<sub_details>`?[^:`]+`?): )? | |
d400e261 SS |
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) | |
62b5c94c | 257 | REVERT_RE = re.compile(r'(?:\[[^\]]+\]\s+)?(?i:Revert)\s+([\da-f]{40})') |
93449642 | 258 | FIXES_RE = re.compile(r'(?i:Fix(?:es)?(?:\s+bugs?)?(?:\s+in|\s+for)?|Revert)\s+([\da-f]{40})') |
d400e261 SS |
259 | UPSTREAM_MERGE_RE = re.compile(r'Update to ytdl-commit-([\da-f]+)') |
260 | ||
392389b7 | 261 | def __init__(self, start, end, default_author=None): |
262 | self._start, self._end = start, end | |
d400e261 SS |
263 | self._commits, self._fixes = self._get_commits_and_fixes(default_author) |
264 | self._commits_added = [] | |
265 | ||
d400e261 SS |
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 | ||
d400e261 | 280 | def _get_commits_and_fixes(self, default_author): |
392389b7 | 281 | result = run_process( |
d400e261 | 282 | self.COMMAND, 'log', f'--format=%H%n%s%n%b%n{self.COMMIT_SEPARATOR}', |
392389b7 | 283 | f'{self._start}..{self._end}' if self._start else self._end).stdout |
d400e261 | 284 | |
fa448028 | 285 | commits, reverts = {}, {} |
d400e261 SS |
286 | fixes = defaultdict(list) |
287 | lines = iter(result.splitlines(False)) | |
7accdd98 | 288 | for i, commit_hash in enumerate(lines): |
d400e261 SS |
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) | |
7accdd98 | 299 | if skip and (self._start or not i): |
d400e261 SS |
300 | logger.debug(f'Skipped commit: {commit}') |
301 | continue | |
7accdd98 | 302 | elif skip: |
303 | logger.debug(f'Reached Release commit, breaking: {commit}') | |
304 | break | |
d400e261 | 305 | |
fa448028 | 306 | revert_match = self.REVERT_RE.fullmatch(commit.short) |
307 | if revert_match: | |
308 | reverts[revert_match.group(1)] = commit | |
309 | continue | |
310 | ||
d400e261 SS |
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 | ||
fa448028 | 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 | ||
d400e261 SS |
325 | for commitish, fix_commits in fixes.items(): |
326 | if commitish in commits: | |
392389b7 | 327 | hashes = ', '.join(commit.hash[:HASH_LENGTH] for commit in fix_commits) |
328 | logger.info(f'Found fix(es) for {commitish[:HASH_LENGTH]}: {hashes}') | |
d400e261 SS |
329 | for fix_commit in fix_commits: |
330 | del commits[fix_commit.hash] | |
331 | else: | |
392389b7 | 332 | logger.debug(f'Commit with fixes not in changes: {commitish[:HASH_LENGTH]}') |
d400e261 SS |
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 | ||
ad54c913 | 343 | override_hash = override.get('hash') or when |
d400e261 SS |
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 | |
ad54c913 | 357 | commit = Commit(override_hash, override['short'], override.get('authors') or []) |
d400e261 SS |
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): | |
23c39a4b | 364 | group_dict = defaultdict(list) |
d400e261 | 365 | for commit in self: |
23c39a4b | 366 | upstream_re = self.UPSTREAM_MERGE_RE.search(commit.short) |
d400e261 | 367 | if upstream_re: |
ad54c913 | 368 | commit.short = f'[core/upstream] Merged with youtube-dl {upstream_re.group(1)}' |
d400e261 SS |
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 | ||
23c39a4b SS |
375 | prefix, sub_details_alt, message, issues = match.groups() |
376 | issues = [issue.strip()[1:] for issue in issues.split(',')] if issues else [] | |
d400e261 | 377 | |
23c39a4b SS |
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)) | |
d400e261 SS |
383 | else: |
384 | group = CommitGroup.CORE | |
23c39a4b SS |
385 | details = None |
386 | sub_details = [] | |
d400e261 | 387 | |
23c39a4b SS |
388 | if sub_details_alt: |
389 | sub_details.append(sub_details_alt) | |
390 | sub_details = tuple(unique(sub_details)) | |
d400e261 SS |
391 | |
392 | if not group: | |
23c39a4b SS |
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()}') | |
d400e261 SS |
398 | |
399 | commit_info = CommitInfo( | |
400 | details, sub_details, message.strip(), | |
401 | issues, commit, self._fixes[commit.hash]) | |
23c39a4b | 402 | |
d400e261 | 403 | logger.debug(f'Resolved {commit.short!r} to {commit_info!r}') |
23c39a4b SS |
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, () | |
d400e261 | 412 | |
23c39a4b | 413 | prefix, _, details = prefix.partition('/') |
ad54c913 | 414 | prefix = prefix.strip() |
23c39a4b SS |
415 | details = details.strip() |
416 | ||
ad54c913 | 417 | group = CommitGroup.get(prefix.lower()) |
23c39a4b SS |
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 | |
d400e261 SS |
434 | |
435 | ||
436 | def get_new_contributors(contributors_path, commits): | |
437 | contributors = set() | |
438 | if contributors_path.exists(): | |
392389b7 | 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)) | |
d400e261 SS |
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)') | |
23c39a4b SS |
484 | parser.add_argument( |
485 | '--collapsible', action='store_true', | |
486 | help='make changelog collapsible (default: %(default)s)') | |
d400e261 SS |
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 | ||
7accdd98 | 493 | commits = CommitRange(None, args.commitish, args.default_author) |
d400e261 SS |
494 | |
495 | if not args.no_override: | |
496 | if args.override_path.exists(): | |
392389b7 | 497 | overrides = json.loads(read_file(args.override_path)) |
d400e261 SS |
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: | |
392389b7 | 507 | write_file(args.contributors_path, '\n'.join(new_contributors) + '\n', mode='a') |
d400e261 SS |
508 | logger.info(f'New contributors: {", ".join(new_contributors)}') |
509 | ||
23c39a4b | 510 | print(Changelog(commits.groups(), args.repo, args.collapsible)) |