Debian Codegraph @

hgext/releasenotes.py

raw
1 # Copyright 2017-present Gregory Szorc <[email protected]>
2 #
3 # This software may be used and distributed according to the terms of the
4 # GNU General Public License version 2 or any later version.
5
6 """generate release notes from commit messages (EXPERIMENTAL)
7
8 It is common to maintain files detailing changes in a project between
9 releases. Maintaining these files can be difficult and time consuming.
10 The :hg:`releasenotes` command provided by this extension makes the
11 process simpler by automating it.
12 """
13
14 from __future__ import annotations
15
16 import difflib
17 import re
18
19 from mercurial.i18n import _
20 from mercurial.node import hex
21 from mercurial import (
22 cmdutil,
23 config,
24 error,
25 logcmdutil,
26 minirst,
27 registrar,
28 util,
29 )
30 from mercurial.utils import (
31 procutil,
32 stringutil,
33 )
34
35 cmdtable = {}
36 command = registrar.command(cmdtable)
37
38 try:
39 # Silence a warning about python-Levenshtein.
40 #
41 # We don't need the performance that much and it gets annoying in tests.
42 import warnings
43
44 with warnings.catch_warnings():
45 warnings.filterwarnings(
46 action="ignore",
47 message=".*python-Levenshtein.*",
48 category=UserWarning,
49 module="fuzzywuzzy.fuzz",
50 )
51
52 import fuzzywuzzy.fuzz as fuzz # pytype: disable=import-error
53
54 fuzz.token_set_ratio
55 except ImportError:
56 fuzz = None
57
58 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
59 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
60 # be specifying the version(s) of Mercurial they are tested with, or
61 # leave the attribute unspecified.
62 testedwith = b'ships-with-hg-core'
63
64 DEFAULT_SECTIONS = [
65 (b'feature', _(b'New Features')),
66 (b'bc', _(b'Backwards Compatibility Changes')),
67 (b'fix', _(b'Bug Fixes')),
68 (b'perf', _(b'Performance Improvements')),
69 (b'api', _(b'API Changes')),
70 ]
71
72 RE_DIRECTIVE = re.compile(br'^\.\. ([a-zA-Z0-9_]+)::\s*([^$]+)?$', re.MULTILINE)
73 RE_ISSUE = br'\bissue ?[0-9]{4,6}(?![0-9])\b'
74
75 BULLET_SECTION = _(b'Other Changes')
76
77
78 class parsedreleasenotes:
79 def __init__(self):
80 self.sections = {}
81
82 def __contains__(self, section):
83 return section in self.sections
84
85 def __iter__(self):
86 return iter(sorted(self.sections))
87
88 def addtitleditem(self, section, title, paragraphs):
89 """Add a titled release note entry."""
90 self.sections.setdefault(section, ([], []))
91 self.sections[section][0].append((title, paragraphs))
92
93 def addnontitleditem(self, section, paragraphs):
94 """Adds a non-titled release note entry.
95
96 Will be rendered as a bullet point.
97 """
98 self.sections.setdefault(section, ([], []))
99 self.sections[section][1].append(paragraphs)
100
101 def titledforsection(self, section):
102 """Returns titled entries in a section.
103
104 Returns a list of (title, paragraphs) tuples describing sub-sections.
105 """
106 return self.sections.get(section, ([], []))[0]
107
108 def nontitledforsection(self, section):
109 """Returns non-titled, bulleted paragraphs in a section."""
110 return self.sections.get(section, ([], []))[1]
111
112 def hastitledinsection(self, section, title):
113 return any(t[0] == title for t in self.titledforsection(section))
114
115 def merge(self, ui, other):
116 """Merge another instance into this one.
117
118 This is used to combine multiple sources of release notes together.
119 """
120 if not fuzz:
121 ui.warn(
122 _(
123 b"module 'fuzzywuzzy' not found, merging of similar "
124 b"releasenotes is disabled\n"
125 )
126 )
127
128 for section in other:
129 existingnotes = converttitled(
130 self.titledforsection(section)
131 ) + convertnontitled(self.nontitledforsection(section))
132 for title, paragraphs in other.titledforsection(section):
133 if self.hastitledinsection(section, title):
134 # TODO prompt for resolution if different and running in
135 # interactive mode.
136 ui.write(
137 _(b'%s already exists in %s section; ignoring\n')
138 % (title, section)
139 )
140 continue
141
142 incoming_str = converttitled([(title, paragraphs)])[0]
143 if section == b'fix':
144 issue = getissuenum(incoming_str)
145 if issue:
146 if findissue(ui, existingnotes, issue):
147 continue
148
149 if similar(ui, existingnotes, incoming_str):
150 continue
151
152 self.addtitleditem(section, title, paragraphs)
153
154 for paragraphs in other.nontitledforsection(section):
155 if paragraphs in self.nontitledforsection(section):
156 continue
157
158 incoming_str = convertnontitled([paragraphs])[0]
159 if section == b'fix':
160 issue = getissuenum(incoming_str)
161 if issue:
162 if findissue(ui, existingnotes, issue):
163 continue
164
165 if similar(ui, existingnotes, incoming_str):
166 continue
167
168 self.addnontitleditem(section, paragraphs)
169
170
171 class releasenotessections:
172 def __init__(self, ui, repo=None):
173 if repo:
174 sections = util.sortdict(DEFAULT_SECTIONS)
175 custom_sections = getcustomadmonitions(repo)
176 if custom_sections:
177 sections.update(custom_sections)
178 self._sections = list(sections.items())
179 else:
180 self._sections = list(DEFAULT_SECTIONS)
181
182 def __iter__(self):
183 return iter(self._sections)
184
185 def names(self):
186 return [t[0] for t in self._sections]
187
188 def sectionfromtitle(self, title):
189 for name, value in self._sections:
190 if value == title:
191 return name
192
193 return None
194
195
196 def converttitled(titledparagraphs):
197 """
198 Convert titled paragraphs to strings
199 """
200 string_list = []
201 for title, paragraphs in titledparagraphs:
202 lines = []
203 for para in paragraphs:
204 lines.extend(para)
205 string_list.append(b' '.join(lines))
206 return string_list
207
208
209 def convertnontitled(nontitledparagraphs):
210 """
211 Convert non-titled bullets to strings
212 """
213 string_list = []
214 for paragraphs in nontitledparagraphs:
215 lines = []
216 for para in paragraphs:
217 lines.extend(para)
218 string_list.append(b' '.join(lines))
219 return string_list
220
221
222 def getissuenum(incoming_str):
223 """
224 Returns issue number from the incoming string if it exists
225 """
226 issue = re.search(RE_ISSUE, incoming_str, re.IGNORECASE)
227 if issue:
228 issue = issue.group()
229 return issue
230
231
232 def findissue(ui, existing, issue):
233 """
234 Returns true if issue number already exists in notes.
235 """
236 if any(issue in s for s in existing):
237 ui.write(_(b'"%s" already exists in notes; ignoring\n') % issue)
238 return True
239 else:
240 return False
241
242
243 def similar(ui, existing, incoming_str):
244 """
245 Returns true if similar note found in existing notes.
246 """
247 if len(incoming_str.split()) > 10:
248 merge = similaritycheck(incoming_str, existing)
249 if not merge:
250 ui.write(
251 _(b'"%s" already exists in notes file; ignoring\n')
252 % incoming_str
253 )
254 return True
255 else:
256 return False
257 else:
258 return False
259
260
261 def similaritycheck(incoming_str, existingnotes):
262 """
263 Returns false when note fragment can be merged to existing notes.
264 """
265 # fuzzywuzzy not present
266 if not fuzz:
267 return True
268
269 merge = True
270 for bullet in existingnotes:
271 score = fuzz.token_set_ratio(incoming_str, bullet)
272 if score > 75:
273 merge = False
274 break
275 return merge
276
277
278 def getcustomadmonitions(repo):
279 ctx = repo[b'.']
280 p = config.config()
281
282 def read(f, sections=None, remap=None):
283 if f in ctx:
284 data = ctx[f].data()
285 p.parse(f, data, sections, remap, read)
286 else:
287 raise error.Abort(
288 _(b".hgreleasenotes file \'%s\' not found") % repo.pathto(f)
289 )
290
291 if b'.hgreleasenotes' in ctx:
292 read(b'.hgreleasenotes')
293 return p.items(b'sections')
294
295
296 def checkadmonitions(ui, repo, directives, revs):
297 """
298 Checks the commit messages for admonitions and their validity.
299
300 .. abcd::
301
302 First paragraph under this admonition
303
304 For this commit message, using `hg releasenotes -r . --check`
305 returns: Invalid admonition 'abcd' present in changeset 3ea92981e103
306
307 As admonition 'abcd' is neither present in default nor custom admonitions
308 """
309 for rev in revs:
310 ctx = repo[rev]
311 admonition = re.search(RE_DIRECTIVE, ctx.description())
312 if admonition:
313 if admonition.group(1) in directives:
314 continue
315 else:
316 ui.write(
317 _(b"Invalid admonition '%s' present in changeset %s\n")
318 % (admonition.group(1), ctx.hex()[:12])
319 )
320 sim = lambda x: difflib.SequenceMatcher(
321 None, admonition.group(1), x
322 ).ratio()
323
324 similar = [s for s in directives if sim(s) > 0.6]
325 if len(similar) == 1:
326 ui.write(_(b"(did you mean %s?)\n") % similar[0])
327 elif similar:
328 ss = b", ".join(sorted(similar))
329 ui.write(_(b"(did you mean one of %s?)\n") % ss)
330
331
332 def _getadmonitionlist(ui, sections):
333 for section in sections:
334 ui.write(b"%s: %s\n" % (section[0], section[1]))
335
336
337 def parsenotesfromrevisions(repo, directives, revs):
338 notes = parsedreleasenotes()
339
340 for rev in revs:
341 ctx = repo[rev]
342
343 blocks, pruned = minirst.parse(
344 ctx.description(), admonitions=directives
345 )
346
347 for i, block in enumerate(blocks):
348 if block[b'type'] != b'admonition':
349 continue
350
351 directive = block[b'admonitiontitle']
352 title = block[b'lines'][0].strip() if block[b'lines'] else None
353
354 if i + 1 == len(blocks):
355 raise error.Abort(
356 _(
357 b'changeset %s: release notes directive %s '
358 b'lacks content'
359 )
360 % (ctx, directive)
361 )
362
363 # Now search ahead and find all paragraphs attached to this
364 # admonition.
365 paragraphs = []
366 for j in range(i + 1, len(blocks)):
367 pblock = blocks[j]
368
369 # Margin blocks may appear between paragraphs. Ignore them.
370 if pblock[b'type'] == b'margin':
371 continue
372
373 if pblock[b'type'] == b'admonition':
374 break
375
376 if pblock[b'type'] != b'paragraph':
377 repo.ui.warn(
378 _(
379 b'changeset %s: unexpected block in release '
380 b'notes directive %s\n'
381 )
382 % (ctx, directive)
383 )
384
385 if pblock[b'indent'] > 0:
386 paragraphs.append(pblock[b'lines'])
387 else:
388 break
389
390 # TODO consider using title as paragraph for more concise notes.
391 if not paragraphs:
392 repo.ui.warn(
393 _(b"error parsing releasenotes for revision: '%s'\n")
394 % hex(ctx.node())
395 )
396 if title:
397 notes.addtitleditem(directive, title, paragraphs)
398 else:
399 notes.addnontitleditem(directive, paragraphs)
400
401 return notes
402
403
404 def parsereleasenotesfile(sections, text):
405 """Parse text content containing generated release notes."""
406 notes = parsedreleasenotes()
407
408 blocks = minirst.parse(text)[0]
409
410 def gatherparagraphsbullets(offset, title=False):
411 notefragment = []
412
413 for i in range(offset + 1, len(blocks)):
414 block = blocks[i]
415
416 if block[b'type'] == b'margin':
417 continue
418 elif block[b'type'] == b'section':
419 break
420 elif block[b'type'] == b'bullet':
421 if block[b'indent'] != 0:
422 raise error.Abort(_(b'indented bullet lists not supported'))
423 if title:
424 lines = [l[1:].strip() for l in block[b'lines']]
425 notefragment.append(lines)
426 continue
427 else:
428 lines = [[l[1:].strip() for l in block[b'lines']]]
429
430 for block in blocks[i + 1 :]:
431 if block[b'type'] in (b'bullet', b'section'):
432 break
433 if block[b'type'] == b'paragraph':
434 lines.append(block[b'lines'])
435 notefragment.append(lines)
436 continue
437 elif block[b'type'] != b'paragraph':
438 raise error.Abort(
439 _(b'unexpected block type in release notes: %s')
440 % block[b'type']
441 )
442 if title:
443 notefragment.append(block[b'lines'])
444
445 return notefragment
446
447 currentsection = None
448 for i, block in enumerate(blocks):
449 if block[b'type'] != b'section':
450 continue
451
452 title = block[b'lines'][0]
453
454 # TODO the parsing around paragraphs and bullet points needs some
455 # work.
456 if block[b'underline'] == b'=': # main section
457 name = sections.sectionfromtitle(title)
458 if not name:
459 raise error.Abort(
460 _(b'unknown release notes section: %s') % title
461 )
462
463 currentsection = name
464 bullet_points = gatherparagraphsbullets(i)
465 if bullet_points:
466 for para in bullet_points:
467 notes.addnontitleditem(currentsection, para)
468
469 elif block[b'underline'] == b'-': # sub-section
470 if title == BULLET_SECTION:
471 bullet_points = gatherparagraphsbullets(i)
472 for para in bullet_points:
473 notes.addnontitleditem(currentsection, para)
474 else:
475 paragraphs = gatherparagraphsbullets(i, True)
476 notes.addtitleditem(currentsection, title, paragraphs)
477 else:
478 raise error.Abort(_(b'unsupported section type for %s') % title)
479
480 return notes
481
482
483 def serializenotes(sections, notes):
484 """Serialize release notes from parsed fragments and notes.
485
486 This function essentially takes the output of ``parsenotesfromrevisions()``
487 and ``parserelnotesfile()`` and produces output combining the 2.
488 """
489 lines = []
490
491 for sectionname, sectiontitle in sections:
492 if sectionname not in notes:
493 continue
494
495 lines.append(sectiontitle)
496 lines.append(b'=' * len(sectiontitle))
497 lines.append(b'')
498
499 # First pass to emit sub-sections.
500 for title, paragraphs in notes.titledforsection(sectionname):
501 lines.append(title)
502 lines.append(b'-' * len(title))
503 lines.append(b'')
504
505 for i, para in enumerate(paragraphs):
506 if i:
507 lines.append(b'')
508 lines.extend(
509 stringutil.wrap(b' '.join(para), width=78).splitlines()
510 )
511
512 lines.append(b'')
513
514 # Second pass to emit bullet list items.
515
516 # If the section has titled and non-titled items, we can't
517 # simply emit the bullet list because it would appear to come
518 # from the last title/section. So, we emit a new sub-section
519 # for the non-titled items.
520 nontitled = notes.nontitledforsection(sectionname)
521 if notes.titledforsection(sectionname) and nontitled:
522 # TODO make configurable.
523 lines.append(BULLET_SECTION)
524 lines.append(b'-' * len(BULLET_SECTION))
525 lines.append(b'')
526
527 for paragraphs in nontitled:
528 lines.extend(
529 stringutil.wrap(
530 b' '.join(paragraphs[0]),
531 width=78,
532 initindent=b'* ',
533 hangindent=b' ',
534 ).splitlines()
535 )
536
537 for para in paragraphs[1:]:
538 lines.append(b'')
539 lines.extend(
540 stringutil.wrap(
541 b' '.join(para),
542 width=78,
543 initindent=b' ',
544 hangindent=b' ',
545 ).splitlines()
546 )
547
548 lines.append(b'')
549
550 if lines and lines[-1]:
551 lines.append(b'')
552
553 return b'\n'.join(lines)
554
555
556 @command(
557 b'releasenotes',
558 [
559 (
560 b'r',
561 b'rev',
562 b'',
563 _(b'revisions to process for release notes'),
564 _(b'REV'),
565 ),
566 (
567 b'c',
568 b'check',
569 False,
570 _(b'checks for validity of admonitions (if any)'),
571 _(b'REV'),
572 ),
573 (
574 b'l',
575 b'list',
576 False,
577 _(b'list the available admonitions with their title'),
578 None,
579 ),
580 ],
581 _(b'hg releasenotes [-r REV] [-c] FILE'),
582 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
583 )
584 def releasenotes(ui, repo, file_=None, **opts):
585 """parse release notes from commit messages into an output file
586
587 Given an output file and set of revisions, this command will parse commit
588 messages for release notes then add them to the output file.
589
590 Release notes are defined in commit messages as ReStructuredText
591 directives. These have the form::
592
593 .. directive:: title
594
595 content
596
597 Each ``directive`` maps to an output section in a generated release notes
598 file, which itself is ReStructuredText. For example, the ``.. feature::``
599 directive would map to a ``New Features`` section.
600
601 Release note directives can be either short-form or long-form. In short-
602 form, ``title`` is omitted and the release note is rendered as a bullet
603 list. In long form, a sub-section with the title ``title`` is added to the
604 section.
605
606 The ``FILE`` argument controls the output file to write gathered release
607 notes to. The format of the file is::
608
609 Section 1
610 =========
611
612 ...
613
614 Section 2
615 =========
616
617 ...
618
619 Only sections with defined release notes are emitted.
620
621 If a section only has short-form notes, it will consist of bullet list::
622
623 Section
624 =======
625
626 * Release note 1
627 * Release note 2
628
629 If a section has long-form notes, sub-sections will be emitted::
630
631 Section
632 =======
633
634 Note 1 Title
635 ------------
636
637 Description of the first long-form note.
638
639 Note 2 Title
640 ------------
641
642 Description of the second long-form note.
643
644 If the ``FILE`` argument points to an existing file, that file will be
645 parsed for release notes having the format that would be generated by this
646 command. The notes from the processed commit messages will be *merged*
647 into this parsed set.
648
649 During release notes merging:
650
651 * Duplicate items are automatically ignored
652 * Items that are different are automatically ignored if the similarity is
653 greater than a threshold.
654
655 This means that the release notes file can be updated independently from
656 this command and changes should not be lost when running this command on
657 that file. A particular use case for this is to tweak the wording of a
658 release note after it has been added to the release notes file.
659
660 The -c/--check option checks the commit message for invalid admonitions.
661
662 The -l/--list option, presents the user with a list of existing available
663 admonitions along with their title. This also includes the custom
664 admonitions (if any).
665 """
666
667 sections = releasenotessections(ui, repo)
668
669 cmdutil.check_incompatible_arguments(opts, 'list', ['rev', 'check'])
670
671 if opts.get('list'):
672 return _getadmonitionlist(ui, sections)
673
674 rev = opts.get('rev')
675 revs = logcmdutil.revrange(repo, [rev or b'not public()'])
676 if opts.get('check'):
677 return checkadmonitions(ui, repo, sections.names(), revs)
678
679 incoming = parsenotesfromrevisions(repo, sections.names(), revs)
680
681 if file_ is None:
682 ui.pager(b'releasenotes')
683 return ui.write(serializenotes(sections, incoming))
684
685 try:
686 notes = parsereleasenotesfile(sections, util.readfile(file_))
687 except FileNotFoundError:
688 notes = parsedreleasenotes()
689
690 notes.merge(ui, incoming)
691
692 util.writefile(file_, serializenotes(sections, notes))
693
694
695 @command(b'debugparsereleasenotes', norepo=True)
696 def debugparsereleasenotes(ui, path, repo=None):
697 """parse release notes and print resulting data structure"""
698 if path == b'-':
699 text = procutil.stdin.read()
700 else:
701 text = util.readfile(path)
702
703 sections = releasenotessections(ui, repo)
704
705 notes = parsereleasenotesfile(sections, text)
706
707 for section in notes:
708 ui.write(_(b'section: %s\n') % section)
709 for title, paragraphs in notes.titledforsection(section):
710 ui.write(_(b' subsection: %s\n') % title)
711 for para in paragraphs:
712 ui.write(_(b' paragraph: %s\n') % b' '.join(para))
713
714 for paragraphs in notes.nontitledforsection(section):
715 ui.write(_(b' bullet point:\n'))
716 for para in paragraphs:
717 ui.write(_(b' paragraph: %s\n') % b' '.join(para))