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
):
71 cls
.EXTRACTOR
: {'extractor', 'extractors'}
,
72 cls
.DOWNLOADER
: {'downloader'}
,
73 cls
.POSTPROCESSOR
: {'postprocessor'}
,
80 result
= cls
.commit_lookup().get(value
)
82 logger
.debug(f
'Mapped {value!r} => {result.name}')
93 result
= f
'{self.short!r}'
96 result
+= f
' ({self.hash[:HASH_LENGTH]})'
99 authors
= ', '.join(self
.authors
)
100 result
+= f
' by {authors}'
108 sub_details
: tuple[str, ...]
115 return ((self
.details
or '').lower(), self
.sub_details
, self
.message
)
119 return sorted({item.strip().lower(): item for item in items if item}
.values())
123 MISC_RE
= re
.compile(r
'(?:^|\b)(?:lint(?:ing)?|misc|format(?:ting)?|fixes)(?:\b|$)', re
.IGNORECASE
)
124 ALWAYS_SHOWN
= (CommitGroup
.PRIORITY
,)
126 def __init__(self
, groups
, repo
, collapsible
=False):
127 self
._groups
= groups
129 self
._collapsible
= collapsible
132 return '\n'.join(self
._format
_groups
(self
._groups
)).replace('\t', ' ')
134 def _format_groups(self
, groups
):
136 for item
in CommitGroup
:
137 if self
._collapsible
and item
not in self
.ALWAYS_SHOWN
and first
:
139 yield '\n<details><summary><h3>Changelog</h3></summary>\n'
143 yield self
.format_module(item
.value
, group
)
145 if self
._collapsible
:
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
))
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())
155 for _
, items
in detail_groups
:
157 details
= items
[0].details
159 if details
== 'cleanup':
160 items
= self
._prepare
_cleanup
_misc
_items
(items
)
165 prefix
= f
'- **{details}**:'
167 yield f
'- **{details}**'
170 sub_detail_groups
= itertools
.groupby(items
, lambda item
: tuple(map(str.lower
, item
.sub_details
)))
171 for sub_details
, entries
in sub_detail_groups
:
173 for entry
in entries
:
174 yield f
'{prefix} {self.format_single_change(entry)}'
177 entries
= list(entries
)
178 sub_prefix
= f
'{prefix} {", ".join(entries[0].sub_details)}'
179 if len(entries
) == 1:
180 yield f
'{sub_prefix}: {self.format_single_change(entries[0])}'
184 for entry
in entries
:
185 yield f
'\t{prefix} {self.format_single_change(entry)}'
187 def _prepare_cleanup_misc_items(self
, items
):
188 cleanup_misc_items
= defaultdict(list)
191 if self
.MISC_RE
.search(item
.message
):
192 cleanup_misc_items
[tuple(item
.commit
.authors
)].append(item
)
194 sorted_items
.append(item
)
196 for commit_infos
in cleanup_misc_items
.values():
197 sorted_items
.append(CommitInfo(
198 'cleanup', ('Miscellaneous',), ', '.join(
199 self
._format
_message
_link
(None, info
.commit
.hash)
200 for info
in sorted(commit_infos
, key
=lambda item
: item
.commit
.hash or '')),
201 [], Commit(None, '', commit_infos
[0].commit
.authors
), []))
205 def format_single_change(self
, info
):
206 message
= self
._format
_message
_link
(info
.message
, info
.commit
.hash)
208 message
= f
'{message} ({self._format_issues(info.issues)})'
210 if info
.commit
.authors
:
211 message
= f
'{message} by {self._format_authors(info.commit.authors)}'
214 fix_message
= ', '.join(f
'{self._format_message_link(None, fix.hash)}' for fix
in info
.fixes
)
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)}'
220 message
= f
'{message} (With fixes in {fix_message})'
224 def _format_message_link(self
, message
, hash):
225 assert message
or hash, 'Improperly defined commit message or override'
226 message
= message
if message
else hash[:HASH_LENGTH
]
227 return f
'[{message}]({self.repo_url}/commit/{hash})' if hash else message
229 def _format_issues(self
, issues
):
230 return ', '.join(f
'[#{issue}]({self.repo_url}/issues/{issue})' for issue
in issues
)
233 def _format_authors(authors
):
234 return ', '.join(f
'[{author}]({BASE_URL}/{author})' for author
in authors
)
238 return f
'{BASE_URL}/{self._repo}'
243 COMMIT_SEPARATOR
= '-----'
245 AUTHOR_INDICATOR_RE
= re
.compile(r
'Authored by:? ', re
.IGNORECASE
)
246 MESSAGE_RE
= re
.compile(r
'''
247 (?:\[(?P<prefix>[^\]]+)\]\ )?
248 (?:(?P<sub_details>`?[^:`]+`?): )?
250 (?:\ \((?P<issues>\#\d+(?:,\ \#\d+)*)\))?
251 ''', re
.VERBOSE | re
.DOTALL
)
252 EXTRACTOR_INDICATOR_RE
= re
.compile(r
'(?:Fix|Add)\s+Extractors?', re
.IGNORECASE
)
253 FIXES_RE
= re
.compile(r
'(?i:Fix(?:es)?(?:\s+bugs?)?(?:\s+in|\s+for)?|Revert)\s+([\da-f]{40})')
254 UPSTREAM_MERGE_RE
= re
.compile(r
'Update to ytdl-commit-([\da-f]+)')
256 def __init__(self
, start
, end
, default_author
=None):
257 self
._start
, self
._end
= start
, end
258 self
._commits
, self
._fixes
= self
._get
_commits
_and
_fixes
(default_author
)
259 self
._commits
_added
= []
262 return iter(itertools
.chain(self
._commits
.values(), self
._commits
_added
))
265 return len(self
._commits
) + len(self
._commits
_added
)
267 def __contains__(self
, commit
):
268 if isinstance(commit
, Commit
):
273 return commit
in self
._commits
275 def _get_commits_and_fixes(self
, default_author
):
276 result
= run_process(
277 self
.COMMAND
, 'log', f
'--format=%H%n%s%n%b%n{self.COMMIT_SEPARATOR}',
278 f
'{self._start}..{self._end}' if self
._start
else self
._end
).stdout
281 fixes
= defaultdict(list)
282 lines
= iter(result
.splitlines(False))
283 for i
, commit_hash
in enumerate(lines
):
285 skip
= short
.startswith('Release ') or short
== '[version] update'
287 authors
= [default_author
] if default_author
else []
288 for line
in iter(lambda: next(lines
), self
.COMMIT_SEPARATOR
):
289 match
= self
.AUTHOR_INDICATOR_RE
.match(line
)
291 authors
= sorted(map(str.strip
, line
[match
.end():].split(',')), key
=str.casefold
)
293 commit
= Commit(commit_hash
, short
, authors
)
294 if skip
and (self
._start
or not i
):
295 logger
.debug(f
'Skipped commit: {commit}')
298 logger
.debug(f
'Reached Release commit, breaking: {commit}')
301 fix_match
= self
.FIXES_RE
.search(commit
.short
)
303 commitish
= fix_match
.group(1)
304 fixes
[commitish
].append(commit
)
306 commits
[commit
.hash] = commit
308 for commitish
, fix_commits
in fixes
.items():
309 if commitish
in commits
:
310 hashes
= ', '.join(commit
.hash[:HASH_LENGTH
] for commit
in fix_commits
)
311 logger
.info(f
'Found fix(es) for {commitish[:HASH_LENGTH]}: {hashes}')
312 for fix_commit
in fix_commits
:
313 del commits
[fix_commit
.hash]
315 logger
.debug(f
'Commit with fixes not in changes: {commitish[:HASH_LENGTH]}')
317 return commits
, fixes
319 def apply_overrides(self
, overrides
):
320 for override
in overrides
:
321 when
= override
.get('when')
322 if when
and when
not in self
and when
!= self
._start
:
323 logger
.debug(f
'Ignored {when!r}, not in commits {self._start!r}')
326 override_hash
= override
.get('hash')
327 if override
['action'] == 'add':
328 commit
= Commit(override
.get('hash'), override
['short'], override
.get('authors') or [])
329 logger
.info(f
'ADD {commit}')
330 self
._commits
_added
.append(commit
)
332 elif override
['action'] == 'remove':
333 if override_hash
in self
._commits
:
334 logger
.info(f
'REMOVE {self._commits[override_hash]}')
335 del self
._commits
[override_hash
]
337 elif override
['action'] == 'change':
338 if override_hash
not in self
._commits
:
340 commit
= Commit(override_hash
, override
['short'], override
['authors'])
341 logger
.info(f
'CHANGE {self._commits[commit.hash]} -> {commit}')
342 self
._commits
[commit
.hash] = commit
344 self
._commits
= {key: value for key, value in reversed(self._commits.items())}
347 group_dict
= defaultdict(list)
349 upstream_re
= self
.UPSTREAM_MERGE_RE
.search(commit
.short
)
351 commit
.short
= f
'[upstream] Merged with youtube-dl {upstream_re.group(1)}'
353 match
= self
.MESSAGE_RE
.fullmatch(commit
.short
)
355 logger
.error(f
'Error parsing short commit message: {commit.short!r}')
358 prefix
, sub_details_alt
, message
, issues
= match
.groups()
359 issues
= [issue
.strip()[1:] for issue
in issues
.split(',')] if issues
else []
362 groups
, details
, sub_details
= zip(*map(self
.details_from_prefix
, prefix
.split(',')))
363 group
= next(iter(filter(None, groups
)), None)
364 details
= ', '.join(unique(details
))
365 sub_details
= list(itertools
.chain
.from_iterable(sub_details
))
367 group
= CommitGroup
.CORE
372 sub_details
.append(sub_details_alt
)
373 sub_details
= tuple(unique(sub_details
))
376 if self
.EXTRACTOR_INDICATOR_RE
.search(commit
.short
):
377 group
= CommitGroup
.EXTRACTOR
379 group
= CommitGroup
.POSTPROCESSOR
380 logger
.warning(f
'Failed to map {commit.short!r}, selected {group.name.lower()}')
382 commit_info
= CommitInfo(
383 details
, sub_details
, message
.strip(),
384 issues
, commit
, self
._fixes
[commit
.hash])
386 logger
.debug(f
'Resolved {commit.short!r} to {commit_info!r}')
387 group_dict
[group
].append(commit_info
)
392 def details_from_prefix(prefix
):
394 return CommitGroup
.CORE
, None, ()
396 prefix
, _
, details
= prefix
.partition('/')
397 prefix
= prefix
.strip().lower()
398 details
= details
.strip()
400 group
= CommitGroup
.get(prefix
)
401 if group
is CommitGroup
.PRIORITY
:
402 prefix
, _
, details
= details
.partition('/')
404 if not details
and prefix
and prefix
not in CommitGroup
.ignorable_prefixes
:
405 logger
.debug(f
'Replaced details with {prefix!r}')
406 details
= prefix
or None
408 if details
== 'common':
412 details
, *sub_details
= details
.split(':')
416 return group
, details
, sub_details
419 def get_new_contributors(contributors_path
, commits
):
421 if contributors_path
.exists():
422 for line
in read_file(contributors_path
).splitlines():
423 author
, _
, _
= line
.strip().partition(' (')
424 authors
= author
.split('/')
425 contributors
.update(map(str.casefold
, authors
))
427 new_contributors
= set()
428 for commit
in commits
:
429 for author
in commit
.authors
:
430 author_folded
= author
.casefold()
431 if author_folded
not in contributors
:
432 contributors
.add(author_folded
)
433 new_contributors
.add(author
)
435 return sorted(new_contributors
, key
=str.casefold
)
438 if __name__
== '__main__':
441 parser
= argparse
.ArgumentParser(
442 description
='Create a changelog markdown from a git commit range')
444 'commitish', default
='HEAD', nargs
='?',
445 help='The commitish to create the range from (default: %(default)s)')
447 '-v', '--verbosity', action
='count', default
=0,
448 help='increase verbosity (can be used twice)')
450 '-c', '--contributors', action
='store_true',
451 help='update CONTRIBUTORS file (default: %(default)s)')
453 '--contributors-path', type=Path
, default
=LOCATION_PATH
.parent
/ 'CONTRIBUTORS',
454 help='path to the CONTRIBUTORS file')
456 '--no-override', action
='store_true',
457 help='skip override json in commit generation (default: %(default)s)')
459 '--override-path', type=Path
, default
=LOCATION_PATH
/ 'changelog_override.json',
460 help='path to the changelog_override.json file')
462 '--default-author', default
='pukkandan',
463 help='the author to use without a author indicator (default: %(default)s)')
465 '--repo', default
='yt-dlp/yt-dlp',
466 help='the github repository to use for the operations (default: %(default)s)')
468 '--collapsible', action
='store_true',
469 help='make changelog collapsible (default: %(default)s)')
470 args
= parser
.parse_args()
473 datefmt
='%Y-%m-%d %H-%M-%S', format
='{asctime} | {levelname:<8} | {message}',
474 level
=logging
.WARNING
- 10 * args
.verbosity
, style
='{', stream
=sys
.stderr
)
476 commits
= CommitRange(None, args
.commitish
, args
.default_author
)
478 if not args
.no_override
:
479 if args
.override_path
.exists():
480 overrides
= json
.loads(read_file(args
.override_path
))
481 commits
.apply_overrides(overrides
)
483 logger
.warning(f
'File {args.override_path.as_posix()} does not exist')
485 logger
.info(f
'Loaded {len(commits)} commits')
487 new_contributors
= get_new_contributors(args
.contributors_path
, commits
)
489 if args
.contributors
:
490 write_file(args
.contributors_path
, '\n'.join(new_contributors
) + '\n', mode
='a')
491 logger
.info(f
'New contributors: {", ".join(new_contributors)}')
493 print(Changelog(commits
.groups(), args
.repo
, args
.collapsible
))