1 from __future__
import annotations
3 # Allow direct execution
7 sys
.path
.insert(0, os
.path
.dirname(os
.path
.dirname(os
.path
.abspath(__file__
))))
14 from collections
import defaultdict
15 from dataclasses
import dataclass
16 from functools
import lru_cache
17 from pathlib
import Path
19 from devscripts
.utils
import read_file
, run_process
, write_file
21 BASE_URL
= 'https://github.com'
22 LOCATION_PATH
= Path(__file__
).parent
25 logger
= logging
.getLogger(__name__
)
28 class CommitGroup(enum
.Enum
):
29 PRIORITY
= 'Important'
31 EXTRACTOR
= 'Extractor'
32 DOWNLOADER
= 'Downloader'
33 POSTPROCESSOR
= 'Postprocessor'
38 def ignorable_prefixes(cls
):
39 return ('core', 'downloader', 'extractor', 'misc', 'postprocessor', 'upstream')
43 def commit_lookup(cls
):
47 cls
.PRIORITY
: {'priority'},
73 cls
.EXTRACTOR
: {'extractor', 'ie'},
74 cls
.DOWNLOADER
: {'downloader', 'fd'},
75 cls
.POSTPROCESSOR
: {'postprocessor', 'pp'},
82 result
= cls
.commit_lookup().get(value
)
84 logger
.debug(f
'Mapped {value!r} => {result.name}')
95 result
= f
'{self.short!r}'
98 result
+= f
' ({self.hash[:HASH_LENGTH]})'
101 authors
= ', '.join(self
.authors
)
102 result
+= f
' by {authors}'
110 sub_details
: tuple[str, ...]
117 return ((self
.details
or '').lower(), self
.sub_details
, self
.message
)
121 return sorted({item
.strip().lower(): item
for item
in items
if item
}.values())
125 MISC_RE
= re
.compile(r
'(?:^|\b)(?:lint(?:ing)?|misc|format(?:ting)?|fixes)(?:\b|$)', re
.IGNORECASE
)
126 ALWAYS_SHOWN
= (CommitGroup
.PRIORITY
,)
128 def __init__(self
, groups
, repo
, collapsible
=False):
129 self
._groups
= groups
131 self
._collapsible
= collapsible
134 return '\n'.join(self
._format
_groups
(self
._groups
)).replace('\t', ' ')
136 def _format_groups(self
, groups
):
138 for item
in CommitGroup
:
139 if self
._collapsible
and item
not in self
.ALWAYS_SHOWN
and first
:
141 yield '\n<details><summary><h3>Changelog</h3></summary>\n'
145 yield self
.format_module(item
.value
, group
)
147 if self
._collapsible
:
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
))
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
:
159 details
= items
[0].details
161 if details
== 'cleanup':
162 items
= self
._prepare
_cleanup
_misc
_items
(items
)
167 prefix
= f
'- **{details}**:'
169 yield f
'- **{details}**'
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
:
175 for entry
in entries
:
176 yield f
'{prefix} {self.format_single_change(entry)}'
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])}'
186 for entry
in entries
:
187 yield f
'\t{prefix} {self.format_single_change(entry)}'
189 def _prepare_cleanup_misc_items(self
, items
):
190 cleanup_misc_items
= defaultdict(list)
193 if self
.MISC_RE
.search(item
.message
):
194 cleanup_misc_items
[tuple(item
.commit
.authors
)].append(item
)
196 sorted_items
.append(item
)
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
), []))
207 def format_single_change(self
, info
):
208 message
= self
._format
_message
_link
(info
.message
, info
.commit
.hash)
210 message
= message
.replace('\n', f
' ({self._format_issues(info.issues)})\n', 1)
212 if info
.commit
.authors
:
213 message
= message
.replace('\n', f
' by {self._format_authors(info.commit.authors)}\n', 1)
216 fix_message
= ', '.join(f
'{self._format_message_link(None, fix.hash)}' for fix
in info
.fixes
)
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)}'
222 message
= message
.replace('\n', f
' (With fixes in {fix_message})\n', 1)
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
]
230 return f
'{message}\n'
231 return f
'[{message}\n'.replace('\n', f
']({self.repo_url}/commit/{hash})\n', 1)
233 def _format_issues(self
, issues
):
234 return ', '.join(f
'[#{issue}]({self.repo_url}/issues/{issue})' for issue
in issues
)
237 def _format_authors(authors
):
238 return ', '.join(f
'[{author}]({BASE_URL}/{author})' for author
in authors
)
242 return f
'{BASE_URL}/{self._repo}'
247 COMMIT_SEPARATOR
= '-----'
249 AUTHOR_INDICATOR_RE
= re
.compile(r
'Authored by:? ', re
.IGNORECASE
)
250 MESSAGE_RE
= re
.compile(r
'''
251 (?:\[(?P<prefix>[^\]]+)\]\ )?
252 (?:(?P<sub_details>`?[^:`]+`?): )?
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
'(?:\[[^\]]+\]\s+)?(?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]+)')
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
= []
267 return iter(itertools
.chain(self
._commits
.values(), self
._commits
_added
))
270 return len(self
._commits
) + len(self
._commits
_added
)
272 def __contains__(self
, commit
):
273 if isinstance(commit
, Commit
):
278 return commit
in self
._commits
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
285 commits
, reverts
= {}, {}
286 fixes
= defaultdict(list)
287 lines
= iter(result
.splitlines(False))
288 for i
, commit_hash
in enumerate(lines
):
290 skip
= short
.startswith('Release ') or short
== '[version] update'
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
)
296 authors
= sorted(map(str.strip
, line
[match
.end():].split(',')), key
=str.casefold
)
298 commit
= Commit(commit_hash
, short
, authors
)
299 if skip
and (self
._start
or not i
):
300 logger
.debug(f
'Skipped commit: {commit}')
303 logger
.debug(f
'Reached Release commit, breaking: {commit}')
306 revert_match
= self
.REVERT_RE
.fullmatch(commit
.short
)
308 reverts
[revert_match
.group(1)] = commit
311 fix_match
= self
.FIXES_RE
.search(commit
.short
)
313 commitish
= fix_match
.group(1)
314 fixes
[commitish
].append(commit
)
316 commits
[commit
.hash] = commit
318 for commitish
, revert_commit
in reverts
.items():
319 reverted
= commits
.pop(commitish
, None)
321 logger
.debug(f
'{commit} fully reverted {reverted}')
323 commits
[revert_commit
.hash] = revert_commit
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]
332 logger
.debug(f
'Commit with fixes not in changes: {commitish[:HASH_LENGTH]}')
334 return commits
, fixes
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}')
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
)
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
]
354 elif override
['action'] == 'change':
355 if override_hash
not in self
._commits
:
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
361 self
._commits
= {key
: value
for key
, value
in reversed(self
._commits
.items())}
364 group_dict
= defaultdict(list)
366 upstream_re
= self
.UPSTREAM_MERGE_RE
.search(commit
.short
)
368 commit
.short
= f
'[core/upstream] Merged with youtube-dl {upstream_re.group(1)}'
370 match
= self
.MESSAGE_RE
.fullmatch(commit
.short
)
372 logger
.error(f
'Error parsing short commit message: {commit.short!r}')
375 prefix
, sub_details_alt
, message
, issues
= match
.groups()
376 issues
= [issue
.strip()[1:] for issue
in issues
.split(',')] if issues
else []
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
))
384 group
= CommitGroup
.CORE
389 sub_details
.append(sub_details_alt
)
390 sub_details
= tuple(unique(sub_details
))
393 if self
.EXTRACTOR_INDICATOR_RE
.search(commit
.short
):
394 group
= CommitGroup
.EXTRACTOR
396 group
= CommitGroup
.POSTPROCESSOR
397 logger
.warning(f
'Failed to map {commit.short!r}, selected {group.name.lower()}')
399 commit_info
= CommitInfo(
400 details
, sub_details
, message
.strip(),
401 issues
, commit
, self
._fixes
[commit
.hash])
403 logger
.debug(f
'Resolved {commit.short!r} to {commit_info!r}')
404 group_dict
[group
].append(commit_info
)
409 def details_from_prefix(prefix
):
411 return CommitGroup
.CORE
, None, ()
413 prefix
, _
, details
= prefix
.partition('/')
414 prefix
= prefix
.strip()
415 details
= details
.strip()
417 group
= CommitGroup
.get(prefix
.lower())
418 if group
is CommitGroup
.PRIORITY
:
419 prefix
, _
, details
= details
.partition('/')
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
425 if details
== 'common':
429 details
, *sub_details
= details
.split(':')
433 return group
, details
, sub_details
436 def get_new_contributors(contributors_path
, commits
):
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
))
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
)
452 return sorted(new_contributors
, key
=str.casefold
)
455 if __name__
== '__main__':
458 parser
= argparse
.ArgumentParser(
459 description
='Create a changelog markdown from a git commit range')
461 'commitish', default
='HEAD', nargs
='?',
462 help='The commitish to create the range from (default: %(default)s)')
464 '-v', '--verbosity', action
='count', default
=0,
465 help='increase verbosity (can be used twice)')
467 '-c', '--contributors', action
='store_true',
468 help='update CONTRIBUTORS file (default: %(default)s)')
470 '--contributors-path', type=Path
, default
=LOCATION_PATH
.parent
/ 'CONTRIBUTORS',
471 help='path to the CONTRIBUTORS file')
473 '--no-override', action
='store_true',
474 help='skip override json in commit generation (default: %(default)s)')
476 '--override-path', type=Path
, default
=LOCATION_PATH
/ 'changelog_override.json',
477 help='path to the changelog_override.json file')
479 '--default-author', default
='pukkandan',
480 help='the author to use without a author indicator (default: %(default)s)')
482 '--repo', default
='yt-dlp/yt-dlp',
483 help='the github repository to use for the operations (default: %(default)s)')
485 '--collapsible', action
='store_true',
486 help='make changelog collapsible (default: %(default)s)')
487 args
= parser
.parse_args()
490 datefmt
='%Y-%m-%d %H-%M-%S', format
='{asctime} | {levelname:<8} | {message}',
491 level
=logging
.WARNING
- 10 * args
.verbosity
, style
='{', stream
=sys
.stderr
)
493 commits
= CommitRange(None, args
.commitish
, args
.default_author
)
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
)
500 logger
.warning(f
'File {args.override_path.as_posix()} does not exist')
502 logger
.info(f
'Loaded {len(commits)} commits')
504 new_contributors
= get_new_contributors(args
.contributors_path
, commits
)
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)}')
510 print(Changelog(commits
.groups(), args
.repo
, args
.collapsible
))