diff --git a/local_hooks/release_notes.py b/local_hooks/release_notes.py index b15c8459..ec085e25 100755 --- a/local_hooks/release_notes.py +++ b/local_hooks/release_notes.py @@ -2,14 +2,8 @@ import re UNRELEASED_MD_HEADER = "**Unreleased**" -RELEASE_NOTE_PATTERN = re.compile(r"^\s*\* (?P.+)$") -# The minimum number of white spaces a nested list entry needs to be -# indented from its parent for it be rendered correctly on GitHub -MD_NESTED_LIST_MIN_INDENT = 2 - -# The maximum number of white spaces a nested list entry can be -# indented from its parent for it to be rendered correctly on GitHub -MD_NESTED_LIST_MAX_INDENT = 5 +RELEASE_NOTE_PATTERN = re.compile(r"^\* (?P\S.*)$") +NESTED_LIST_MARKER_PATTERN = re.compile(r"^(?:[*+-]|\d+[.)])(?:\s|$)") def check_release_notes(app_directory: str): @@ -21,72 +15,34 @@ def check_release_notes(app_directory: str): release_notes_path.write_text(UNRELEASED_MD_HEADER + "\n") raise ValueError("Release notes file is empty. Please populate it with release notes.") - release_notes = release_notes_path.read_text().rstrip().splitlines() + release_notes = release_notes_path.read_text().splitlines() if not release_notes: release_notes_path.write_text(UNRELEASED_MD_HEADER + "\n") raise ValueError("Release notes file is empty. Please populate it with release notes.") - incorrect_format = False - if release_notes[0] != UNRELEASED_MD_HEADER: - # assuming that the first line is a note - release_notes.insert(0, UNRELEASED_MD_HEADER) + raise ValueError(f"Release notes must start with '{UNRELEASED_MD_HEADER}'.") - if len(release_notes) == 1: - raise ValueError("Release notes file is empty. Please populate it with release notes.") + note_lines = list(enumerate(release_notes[1:], start=2)) + if note_lines and note_lines[0][1] == "": + note_lines = note_lines[1:] - parent_depths = [] - for i in range(1, len(release_notes)): - note = release_notes[i] - if not note or not note.strip(): - continue + if not note_lines: + raise ValueError("Release notes file is empty. Please populate it with release notes.") + for line_number, note in note_lines: match = RELEASE_NOTE_PATTERN.match(note) if not match: - leading_whitespace = re.match(r"^\s*", note).group() - new_note = f"{leading_whitespace}* {note.strip()}" - if not ( - match := RELEASE_NOTE_PATTERN.match(new_note) - ): # check if the note is still incorrect - # fix any successfully caught errors found before - if incorrect_format: - release_notes_path.write_text("\n".join(release_notes) + "\n") - raise ValueError( - f"Detected incorrectly formatted release note: '{note}'. Tried fixing but failed." - ) - else: - incorrect_format = True - release_notes[i] = new_note - print(f"Fixed release note formatting for {note}.") - - note = match.group() - cur_depth, parent_depth = note.index("*"), parent_depths[-1] if parent_depths else 0 - depth_diff = cur_depth - parent_depth - # Previous nested list ended and we're moving back up one or more levels - if depth_diff < 0: - while True: - parent_depths.pop() - depth_diff = cur_depth - parent_depths[-1] if parent_depths else 0 - if depth_diff >= 0: - break - # Current note is too far indented from its parent - elif depth_diff > MD_NESTED_LIST_MAX_INDENT: - incorrect_format = True - new_depth = parent_depth + MD_NESTED_LIST_MAX_INDENT - 1 - note = " " * new_depth + note.lstrip() - release_notes[i] = note - print(f"Fixed indentation for {note}.") - # Current note starts a new nested list - record the depth of the new list - elif MD_NESTED_LIST_MIN_INDENT <= depth_diff: - parent_depths.append(cur_depth) - # Current note is on the same level as the previous - else: - pass - - # fix errors if any were found - if incorrect_format: - release_notes_path.write_text("\n".join(release_notes) + "\n") - print("Release notes file has been updated with corrected formatting.") + raise ValueError( + f"Incorrectly formatted release note on line {line_number}: {note!r}. " + "Expected a non-empty top-level '* ' list entry." + ) + + if NESTED_LIST_MARKER_PATTERN.match(match.group("note")): + raise ValueError( + f"Incorrectly formatted release note on line {line_number}: {note!r}. " + "Nested or repeated list markers are not allowed." + ) def main(): diff --git a/local_hooks/tests/data/release_notes/release_notes_failing/actual/release_notes/unreleased.md b/local_hooks/tests/data/release_notes/release_notes_failing/actual/release_notes/unreleased.md deleted file mode 100644 index 1f48df1e..00000000 --- a/local_hooks/tests/data/release_notes/release_notes_failing/actual/release_notes/unreleased.md +++ /dev/null @@ -1,3 +0,0 @@ -* test failing. - bad tab and format - bad format diff --git a/local_hooks/tests/data/release_notes/release_notes_failing/expected/release_notes/unreleased.md b/local_hooks/tests/data/release_notes/release_notes_failing/expected/release_notes/unreleased.md deleted file mode 100644 index 6b269e2b..00000000 --- a/local_hooks/tests/data/release_notes/release_notes_failing/expected/release_notes/unreleased.md +++ /dev/null @@ -1,4 +0,0 @@ -**Unreleased** -* test failing. - * bad tab and format - * bad format diff --git a/local_hooks/tests/data/release_notes/release_notes_passing/release_notes/unreleased.md b/local_hooks/tests/data/release_notes/release_notes_passing/release_notes/unreleased.md deleted file mode 100644 index 16f5e8c3..00000000 --- a/local_hooks/tests/data/release_notes/release_notes_passing/release_notes/unreleased.md +++ /dev/null @@ -1,4 +0,0 @@ -**Unreleased** - -* [test] test release note. - * test diff --git a/local_hooks/tests/test_release_notes.py b/local_hooks/tests/test_release_notes.py index 221628c8..a58c3af4 100644 --- a/local_hooks/tests/test_release_notes.py +++ b/local_hooks/tests/test_release_notes.py @@ -1,67 +1,64 @@ -import logging -import os -import shutil +from pathlib import Path import subprocess import pytest -from pathlib import Path -PRE_COMMIT_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) +from local_hooks.release_notes import UNRELEASED_MD_HEADER, check_release_notes -logging.getLogger().setLevel(logging.INFO) +def write_release_notes(app_dir: Path, content: str) -> None: + release_notes_dir = app_dir / "release_notes" + release_notes_dir.mkdir() + (release_notes_dir / "unreleased.md").write_text(content) -@pytest.fixture(scope="function") -def app_dir(request: pytest.FixtureRequest) -> Path: - app_dir = Path(request.param) # type: ignore - app_dir_copy = Path(f"{app_dir}_copy") - shutil.copytree(app_dir, app_dir_copy) +@pytest.mark.parametrize( + "content", + [ + "**Unreleased**\n* Updated dependencies.\n", + "**Unreleased**\n\n* Updated dependencies.\n", + "**Unreleased**\n\n* Updated `urllib3`.\n* Fixed request handling.\n", + ], +) +def test_release_notes_accepts_top_level_bullets(tmp_path: Path, content: str): + write_release_notes(tmp_path, content) - def remove_test_dir_copy(): - shutil.rmtree(app_dir_copy, ignore_errors=True) + check_release_notes(str(tmp_path)) - request.addfinalizer(remove_test_dir_copy) - return app_dir_copy +def test_release_notes_command_accepts_canonical_content(tmp_path: Path): + write_release_notes(tmp_path, "**Unreleased**\n\n* Updated dependencies.\n") + result = subprocess.run(["release-notes", "."], cwd=tmp_path, capture_output=True) -@pytest.mark.parametrize( - "app_dir", - ["tests/data/release_notes/release_notes_passing"], - indirect=["app_dir"], -) -def test_release_notes_passing(app_dir: Path): - result = subprocess.run( - ["release-notes", "."], - cwd=app_dir, - capture_output=True, - ) - print(result.stderr.decode()) assert result.returncode == 0 @pytest.mark.parametrize( - "app_dir", - ["tests/data/release_notes/release_notes_failing/actual"], - indirect=["app_dir"], + ("content", "error"), + [ + ("**Unreleased**\n\n* Parent note.\n * Nested note.\n", "top-level"), + ("**Unreleased**\n\n* - Updated dependency.\n", "repeated list markers"), + ( + "**Unreleased**\n\n* Updated first dependency.\n\n* Updated second dependency.\n", + "top-level", + ), + ("**Unreleased**\n\nUpdated dependencies.\n", "top-level"), + ("**Unreleased**\n\n* \n", "top-level"), + ], ) -def test_release_notes_failing(app_dir: Path): - expected_dir = Path("tests/data/release_notes/release_notes_failing/expected") - expected_file = "release_notes/unreleased.md" - - result = subprocess.run( - ["release-notes", "."], - cwd=app_dir, - capture_output=True, - ) - assert result.returncode == 0 +def test_release_notes_rejects_noncanonical_content(tmp_path: Path, content: str, error: str): + write_release_notes(tmp_path, content) + + with pytest.raises(ValueError, match=error): + check_release_notes(str(tmp_path)) + + +def test_missing_release_notes_file_is_created_and_rejected(tmp_path: Path): + release_notes_dir = tmp_path / "release_notes" + release_notes_dir.mkdir() - actual_path = app_dir / expected_file - expected_path = expected_dir / expected_file + with pytest.raises(ValueError, match="empty"): + check_release_notes(str(tmp_path)) - assert actual_path.exists(), f"Missing expected file {expected_file}" - print(actual_path.read_text()) - assert actual_path.read_text() == expected_path.read_text(), ( - f"Release note file {expected_file} did not match expectations!" - ) + assert (release_notes_dir / "unreleased.md").read_text() == f"{UNRELEASED_MD_HEADER}\n"