|
| 1 | +""" |
| 2 | +Sort whatsnew note blocks by issue number. |
| 3 | +
|
| 4 | +NOTE: this assumes that each entry is on its own line, and ends with an issue number. |
| 5 | +If that's not the case, then an entry might not get sorted. However, virtually all |
| 6 | +recent-enough whatsnew entries follow this pattern. So, although not perfect, this |
| 7 | +script should be good enough to significantly reduce merge conflicts. |
| 8 | +
|
| 9 | +For example: |
| 10 | +
|
| 11 | +- Fixed bug in resample (:issue:`321`) |
| 12 | +- Fixed bug in groupby (:issue:`123`) |
| 13 | +
|
| 14 | +would become |
| 15 | +
|
| 16 | +- Fixed bug in groupby (:issue:`123`) |
| 17 | +- Fixed bug in resample (:issue:`321`) |
| 18 | +
|
| 19 | +The motivation is to reduce merge conflicts by reducing the chances that multiple |
| 20 | +contributors will edit the same line of code. |
| 21 | +
|
| 22 | +You can run this manually with |
| 23 | +
|
| 24 | + pre-commit run sort-whatsnew-items --all-files |
| 25 | +""" |
| 26 | +from __future__ import annotations |
| 27 | + |
| 28 | +import argparse |
| 29 | +import re |
| 30 | +import sys |
| 31 | +from typing import Sequence |
| 32 | + |
| 33 | +pattern = re.compile(r"\(:issue:`(\d+)`\)\n$") |
| 34 | + |
| 35 | + |
| 36 | +def sort_whatsnew_note(content: str) -> int: |
| 37 | + new_lines = [] |
| 38 | + block: list[str] = [] |
| 39 | + lines = content.splitlines(keepends=True) |
| 40 | + for line in lines: |
| 41 | + if line.startswith("- ") and pattern.search(line) is not None: |
| 42 | + block.append(line) |
| 43 | + else: |
| 44 | + key = lambda x: int(pattern.search(x).group(1)) |
| 45 | + block = sorted(block, key=key) |
| 46 | + new_lines.extend(block) |
| 47 | + new_lines.append(line) |
| 48 | + block = [] |
| 49 | + if sorted(new_lines) != sorted(lines): # pragma: no cover |
| 50 | + # Defensive check - this script should only reorder lines, not modify any |
| 51 | + # content. |
| 52 | + raise AssertionError( |
| 53 | + "Script modified content of file. Something is wrong, please don't " |
| 54 | + "trust it." |
| 55 | + ) |
| 56 | + return "".join(new_lines) |
| 57 | + |
| 58 | + |
| 59 | +def main(argv: Sequence[str] | None = None) -> int: |
| 60 | + parser = argparse.ArgumentParser() |
| 61 | + parser.add_argument("paths", nargs="*") |
| 62 | + args = parser.parse_args(argv) |
| 63 | + ret = 0 |
| 64 | + for path in args.paths: |
| 65 | + with open(path) as fd: |
| 66 | + content = fd.read() |
| 67 | + new_content = sort_whatsnew_note(content) |
| 68 | + if content != new_content: |
| 69 | + ret |= 1 |
| 70 | + with open(path, "w") as fd: |
| 71 | + fd.write(new_content) |
| 72 | + return ret |
| 73 | + |
| 74 | + |
| 75 | +if __name__ == "__main__": |
| 76 | + sys.exit(main()) |
0 commit comments