releasebrief 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ahmed Saeed
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,3 @@
1
+ include README.md LICENSE THIRD_PARTY.md
2
+ recursive-include assets *.svg
3
+ recursive-include examples *.txt *.json
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: releasebrief
3
+ Version: 0.1.0
4
+ Summary: Draft release notes and stable semantic version suggestions from supplied commit subjects.
5
+ Author: Ahmed Saeed
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/ahmedsaeed1-eng/releasebrief
8
+ Project-URL: Issues, https://github.com/ahmedsaeed1-eng/releasebrief/issues
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ License-File: THIRD_PARTY.md
13
+ Dynamic: license-file
14
+
15
+ ![ReleaseBrief timeline](assets/logo.svg)
16
+
17
+ # ReleaseBrief
18
+
19
+ **A review-ready release draft, before you publish.**
20
+
21
+ [![Tests](https://github.com/ahmedsaeed1-eng/releasebrief/actions/workflows/ci.yml/badge.svg?branch=main&event=push)](https://github.com/ahmedsaeed1-eng/releasebrief/actions/workflows/ci.yml?query=branch%3Amain+event%3Apush) [![Repository stars](https://img.shields.io/github/stars/ahmedsaeed1-eng/releasebrief?style=flat-square&color=c084fc)](https://github.com/ahmedsaeed1-eng/releasebrief/stargazers) [![MIT license](https://img.shields.io/badge/license-MIT-6d28d9?style=flat-square)](LICENSE) [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-3776AB?style=flat-square&logo=python&logoColor=white)](pyproject.toml) [![No runtime dependencies](https://img.shields.io/badge/runtime-stdlib%20only-7c3aed?style=flat-square)](pyproject.toml)
22
+
23
+ > Collect commit subjects → draft release notes → refine sections → review SemVer.
24
+ >
25
+ > Your repository, tags and releases remain untouched.
26
+
27
+ | Jump to | Workflow |
28
+ | :--- | :--- |
29
+ | [01 · Collect](#01--collect) | Prepare text or exported JSON |
30
+ | [02 · Draft](#02--draft) | Generate the first changelog |
31
+ | [03 · Refine](#03--refine) | Select output and filter sections |
32
+ | [04 · Review](#04--review-the-version) | Check the version recommendation |
33
+ | [05 · Test](#05--test) | Run unit and CLI verification |
34
+
35
+ ## 01 · Collect
36
+
37
+ ReleaseBrief is a local Python CLI for drafting release notes from commit subjects you provide. It groups conventional commits, notices breaking changes, removes duplicate subjects, and recommends a stable SemVer increment without applying it. It does not run Git, call external services, mutate project files, create tags, or publish releases.
38
+
39
+ | Feature | Details |
40
+ |---|---|
41
+ | Input | UTF-8 text or JSON array via local file/stdin |
42
+ | Grouping | Features, fixes, performance, maintenance and more |
43
+ | Breaking changes | `!`, `BREAKING CHANGE:` and `BREAKING-CHANGE:` |
44
+ | Duplicate handling | Exact type/scope/description matches; preserves breaking qualifiers and distinct footer notes |
45
+ | Output | Markdown, machine-readable JSON, human-readable console |
46
+ | Filters | Include or exclude types without changing bump recommendation |
47
+ | Version | Suggest next `MAJOR.MINOR.PATCH` only; no tag or release mutation |
48
+
49
+ ## Package installation
50
+
51
+ Once the maintainer publishes this release to PyPI, install its pinned
52
+ Python CLI with:
53
+
54
+ ```sh
55
+ python -m pip install releasebrief==0.1.0
56
+ ```
57
+
58
+ Run the installed entry point against text you provide:
59
+
60
+ ```sh
61
+ printf 'feat: add preferences\nfix: correct exports\n' | releasebrief --current-version 1.2.3
62
+ ```
63
+
64
+ This is a standalone local CLI, not an MCP server. The source checkout
65
+ workflow below remains available with no runtime dependencies.
66
+
67
+ ## 02 · Draft
68
+
69
+ Requires Python 3.10 or later. No package installation is required. Clone or download the source repository, then run from its root:
70
+
71
+ ```sh
72
+ python -m releasebrief examples/commits.txt --current-version 1.2.3
73
+ ```
74
+
75
+ The bundled example includes a breaking change, so the result begins `# 2.0.0`. It is a draft, not a published release.
76
+
77
+ ## 03 · Refine
78
+
79
+ ```sh
80
+ python -m releasebrief examples/commits.json --input-format json --format json --current-version 1.2.3
81
+ python -m releasebrief examples/commits.txt --format console --exclude docs,chore
82
+ python -m releasebrief examples/commits.txt --date 2026-11-27 --strict > CHANGELOG-draft.md
83
+ ```
84
+
85
+ The final command redirects standard output to a new file through your shell; ReleaseBrief itself never writes to a project. Without an input path it reads standard input. Use `python -m releasebrief --help` for all options.
86
+
87
+ ### Input formats
88
+
89
+ Text expects one subject per line; an immediately following breaking-change footer belongs to the previous subject. Blank lines are ignored. For full commit bodies, use JSON rather than plaintext:
90
+
91
+ ```json
92
+ [
93
+ "feat(ui): add settings",
94
+ {"subject": "fix: correct exports"},
95
+ {"subject": "feat(api): rename option", "body": "BREAKING CHANGE: old option removed"}
96
+ ]
97
+ ```
98
+
99
+ The JSON input is an array of strings or objects with a string `subject` and optional string `body`. Unknown object fields are ignored. Non-conventional subjects are counted and omitted; `--strict` makes any such record an error. Invalid input exits with code 2 and writes diagnostics to standard error.
100
+
101
+ ## 04 · Review the version
102
+
103
+ | Commit content | Recommended bump |
104
+ |---|---|
105
+ | Breaking change | major |
106
+ | `feat` | minor |
107
+ | `fix`, `perf`, `revert` | patch |
108
+ | Other types or no commits | none |
109
+
110
+ Recommendations use all parsed commits, including types omitted by display filters. Breaking changes are never hidden by filters. Only stable numeric input versions (`1.2.3` style) are accepted; pre-release/build metadata, special policies for pre-1.0 software, and historical commit ancestry are not interpreted. Review every draft and recommendation manually before release. A duplicate subject can represent distinct changes; use suitably descriptive commit subjects or separate inputs when that distinction matters.
111
+
112
+ Default sections include conventional common types. Custom types are supported through `--include custom-type`. Text and JSON remain local, and Markdown escaping neutralizes common markup in supplied descriptions.
113
+
114
+ ## 05 · Test
115
+
116
+ ```sh
117
+ python -m unittest discover -s tests -v
118
+ ```
119
+
120
+ Tests include CLI execution, UTF-8 input, malformed records, strict mode, filtering, breaking changes, deduplication, and SemVer precedence. CI is configured for Python 3.10/3.12 on Linux, Windows and macOS; see the actual workflow status for the tested environments.
121
+
122
+ ## License and credits
123
+
124
+ MIT. See [LICENSE](LICENSE) and [THIRD_PARTY.md](THIRD_PARTY.md).
@@ -0,0 +1,110 @@
1
+ ![ReleaseBrief timeline](assets/logo.svg)
2
+
3
+ # ReleaseBrief
4
+
5
+ **A review-ready release draft, before you publish.**
6
+
7
+ [![Tests](https://github.com/ahmedsaeed1-eng/releasebrief/actions/workflows/ci.yml/badge.svg?branch=main&event=push)](https://github.com/ahmedsaeed1-eng/releasebrief/actions/workflows/ci.yml?query=branch%3Amain+event%3Apush) [![Repository stars](https://img.shields.io/github/stars/ahmedsaeed1-eng/releasebrief?style=flat-square&color=c084fc)](https://github.com/ahmedsaeed1-eng/releasebrief/stargazers) [![MIT license](https://img.shields.io/badge/license-MIT-6d28d9?style=flat-square)](LICENSE) [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-3776AB?style=flat-square&logo=python&logoColor=white)](pyproject.toml) [![No runtime dependencies](https://img.shields.io/badge/runtime-stdlib%20only-7c3aed?style=flat-square)](pyproject.toml)
8
+
9
+ > Collect commit subjects → draft release notes → refine sections → review SemVer.
10
+ >
11
+ > Your repository, tags and releases remain untouched.
12
+
13
+ | Jump to | Workflow |
14
+ | :--- | :--- |
15
+ | [01 · Collect](#01--collect) | Prepare text or exported JSON |
16
+ | [02 · Draft](#02--draft) | Generate the first changelog |
17
+ | [03 · Refine](#03--refine) | Select output and filter sections |
18
+ | [04 · Review](#04--review-the-version) | Check the version recommendation |
19
+ | [05 · Test](#05--test) | Run unit and CLI verification |
20
+
21
+ ## 01 · Collect
22
+
23
+ ReleaseBrief is a local Python CLI for drafting release notes from commit subjects you provide. It groups conventional commits, notices breaking changes, removes duplicate subjects, and recommends a stable SemVer increment without applying it. It does not run Git, call external services, mutate project files, create tags, or publish releases.
24
+
25
+ | Feature | Details |
26
+ |---|---|
27
+ | Input | UTF-8 text or JSON array via local file/stdin |
28
+ | Grouping | Features, fixes, performance, maintenance and more |
29
+ | Breaking changes | `!`, `BREAKING CHANGE:` and `BREAKING-CHANGE:` |
30
+ | Duplicate handling | Exact type/scope/description matches; preserves breaking qualifiers and distinct footer notes |
31
+ | Output | Markdown, machine-readable JSON, human-readable console |
32
+ | Filters | Include or exclude types without changing bump recommendation |
33
+ | Version | Suggest next `MAJOR.MINOR.PATCH` only; no tag or release mutation |
34
+
35
+ ## Package installation
36
+
37
+ Once the maintainer publishes this release to PyPI, install its pinned
38
+ Python CLI with:
39
+
40
+ ```sh
41
+ python -m pip install releasebrief==0.1.0
42
+ ```
43
+
44
+ Run the installed entry point against text you provide:
45
+
46
+ ```sh
47
+ printf 'feat: add preferences\nfix: correct exports\n' | releasebrief --current-version 1.2.3
48
+ ```
49
+
50
+ This is a standalone local CLI, not an MCP server. The source checkout
51
+ workflow below remains available with no runtime dependencies.
52
+
53
+ ## 02 · Draft
54
+
55
+ Requires Python 3.10 or later. No package installation is required. Clone or download the source repository, then run from its root:
56
+
57
+ ```sh
58
+ python -m releasebrief examples/commits.txt --current-version 1.2.3
59
+ ```
60
+
61
+ The bundled example includes a breaking change, so the result begins `# 2.0.0`. It is a draft, not a published release.
62
+
63
+ ## 03 · Refine
64
+
65
+ ```sh
66
+ python -m releasebrief examples/commits.json --input-format json --format json --current-version 1.2.3
67
+ python -m releasebrief examples/commits.txt --format console --exclude docs,chore
68
+ python -m releasebrief examples/commits.txt --date 2026-11-27 --strict > CHANGELOG-draft.md
69
+ ```
70
+
71
+ The final command redirects standard output to a new file through your shell; ReleaseBrief itself never writes to a project. Without an input path it reads standard input. Use `python -m releasebrief --help` for all options.
72
+
73
+ ### Input formats
74
+
75
+ Text expects one subject per line; an immediately following breaking-change footer belongs to the previous subject. Blank lines are ignored. For full commit bodies, use JSON rather than plaintext:
76
+
77
+ ```json
78
+ [
79
+ "feat(ui): add settings",
80
+ {"subject": "fix: correct exports"},
81
+ {"subject": "feat(api): rename option", "body": "BREAKING CHANGE: old option removed"}
82
+ ]
83
+ ```
84
+
85
+ The JSON input is an array of strings or objects with a string `subject` and optional string `body`. Unknown object fields are ignored. Non-conventional subjects are counted and omitted; `--strict` makes any such record an error. Invalid input exits with code 2 and writes diagnostics to standard error.
86
+
87
+ ## 04 · Review the version
88
+
89
+ | Commit content | Recommended bump |
90
+ |---|---|
91
+ | Breaking change | major |
92
+ | `feat` | minor |
93
+ | `fix`, `perf`, `revert` | patch |
94
+ | Other types or no commits | none |
95
+
96
+ Recommendations use all parsed commits, including types omitted by display filters. Breaking changes are never hidden by filters. Only stable numeric input versions (`1.2.3` style) are accepted; pre-release/build metadata, special policies for pre-1.0 software, and historical commit ancestry are not interpreted. Review every draft and recommendation manually before release. A duplicate subject can represent distinct changes; use suitably descriptive commit subjects or separate inputs when that distinction matters.
97
+
98
+ Default sections include conventional common types. Custom types are supported through `--include custom-type`. Text and JSON remain local, and Markdown escaping neutralizes common markup in supplied descriptions.
99
+
100
+ ## 05 · Test
101
+
102
+ ```sh
103
+ python -m unittest discover -s tests -v
104
+ ```
105
+
106
+ Tests include CLI execution, UTF-8 input, malformed records, strict mode, filtering, breaking changes, deduplication, and SemVer precedence. CI is configured for Python 3.10/3.12 on Linux, Windows and macOS; see the actual workflow status for the tested environments.
107
+
108
+ ## License and credits
109
+
110
+ MIT. See [LICENSE](LICENSE) and [THIRD_PARTY.md](THIRD_PARTY.md).
@@ -0,0 +1,3 @@
1
+ # Third-party references
2
+
3
+ ReleaseBrief uses Python's standard library and has no third-party runtime dependencies or copied implementation. It follows the [Conventional Commits 1.0.0 specification](https://www.conventionalcommits.org/en/v1.0.0/) and the stable numeric version format of [Semantic Versioning 2.0.0](https://semver.org/); the local recommendation rules are documented in the README and are not an official certification. Python and these specifications are independent projects.
@@ -0,0 +1,15 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 860 220" role="img" aria-labelledby="title">
2
+ <title id="title">ReleaseBrief: collect, draft, review</title>
3
+ <rect width="860" height="220" rx="20" fill="#111827"/>
4
+ <path d="M86 143H774" stroke="#52627d" stroke-width="3" stroke-dasharray="7 6"/>
5
+ <circle cx="155" cy="143" r="18" fill="#111827" stroke="#60a5fa" stroke-width="5"/>
6
+ <circle cx="430" cy="143" r="18" fill="#111827" stroke="#c084fc" stroke-width="5"/>
7
+ <circle cx="705" cy="143" r="20" fill="#064e3b" stroke="#34d399" stroke-width="4"/>
8
+ <path d="m697 143 6 6 12-13" fill="none" stroke="#a7f3d0" stroke-width="3.5" stroke-linecap="round" stroke-linejoin="round"/>
9
+ <g font-family="monospace" font-size="17" fill="#dbeafe" text-anchor="middle">
10
+ <text x="155" y="109">COMMITS</text><text x="430" y="109">DRAFT</text><text x="705" y="109">REVIEW</text>
11
+ </g>
12
+ <text x="34" y="53" font-family="sans-serif" font-size="29" font-weight="bold" fill="#f8fafc">ReleaseBrief</text>
13
+ <text x="825" y="49" font-family="monospace" font-size="13" text-anchor="end" fill="#93c5fd">LOCAL RELEASE WORKFLOW</text>
14
+ <text x="430" y="191" font-family="sans-serif" font-size="14" text-anchor="middle" fill="#bac8dd">Every release deserves a deliberate review.</text>
15
+ </svg>
@@ -0,0 +1,5 @@
1
+ [
2
+ "feat(ui): add a compact dashboard",
3
+ {"subject": "fix(export): preserve Arabic text"},
4
+ {"subject": "feat(api): rename configuration fields", "body": "BREAKING CHANGE: update old field names before upgrading"}
5
+ ]
@@ -0,0 +1,7 @@
1
+ feat(ui): add a compact dashboard
2
+ fix(export): preserve Arabic text
3
+ perf: reduce report rendering time
4
+ docs: add migration notes
5
+ feat(api)!: rename configuration fields
6
+ BREAKING CHANGE: update old field names before upgrading
7
+ fix(export): preserve Arabic text
@@ -0,0 +1,24 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "releasebrief"
7
+ version = "0.1.0"
8
+ description = "Draft release notes and stable semantic version suggestions from supplied commit subjects."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE", "THIRD_PARTY.md"]
13
+ authors = [{name = "Ahmed Saeed"}]
14
+ dependencies = []
15
+
16
+ [project.scripts]
17
+ releasebrief = "releasebrief.__main__:main"
18
+
19
+ [project.urls]
20
+ Repository = "https://github.com/ahmedsaeed1-eng/releasebrief"
21
+ Issues = "https://github.com/ahmedsaeed1-eng/releasebrief/issues"
22
+
23
+ [tool.setuptools.packages.find]
24
+ include = ["releasebrief*"]
@@ -0,0 +1,2 @@
1
+ """ReleaseBrief: local changelog and semantic version suggestions."""
2
+ __version__ = "0.1.0"
@@ -0,0 +1,46 @@
1
+ """Command-line entry point."""
2
+ from __future__ import annotations
3
+ import argparse
4
+ import json
5
+ import sys
6
+ from pathlib import Path
7
+
8
+ from . import __version__
9
+ from .core import build_preview, parse_records, read_records, render_console, render_markdown
10
+
11
+
12
+ def main(argv: list[str] | None = None) -> int:
13
+ parser = argparse.ArgumentParser(prog="releasebrief", description="Draft a changelog from supplied Conventional Commit subjects, without modifying a repository.")
14
+ parser.add_argument("input", nargs="?", default="-", help="UTF-8 source file or '-' for stdin (default)")
15
+ parser.add_argument("--input-format", choices=("text", "json"), default="text")
16
+ parser.add_argument("--format", choices=("markdown", "json", "console"), default="markdown", help="output format (default: markdown)")
17
+ parser.add_argument("--current-version", metavar="X.Y.Z", help="stable version to suggest a next version from")
18
+ parser.add_argument("--date", metavar="YYYY-MM-DD", help="optional release date, Markdown only")
19
+ parser.add_argument("--include", metavar="TYPE,TYPE", help="include only these types, except breaking changes")
20
+ parser.add_argument("--exclude", metavar="TYPE,TYPE", default="", help="hide listed types, except breaking changes; does not change bump")
21
+ parser.add_argument("--strict", action="store_true", help="fail with exit 2 if any record is not conventional")
22
+ parser.add_argument("--version", action="version", version=__version__)
23
+ # Consistent UTF-8 on redirected Windows streams and Unix terminals.
24
+ for stream in (sys.stdin, sys.stdout, sys.stderr):
25
+ if hasattr(stream, "reconfigure"):
26
+ stream.reconfigure(encoding="utf-8-sig" if stream is sys.stdin else "utf-8")
27
+ args = parser.parse_args(argv)
28
+ try:
29
+ content = sys.stdin.read() if args.input == "-" else Path(args.input).read_text(encoding="utf-8-sig")
30
+ parsed = parse_records(read_records(content, args.input_format))
31
+ if args.strict and parsed.ignored:
32
+ raise ValueError(f"{parsed.ignored} non-conventional record(s)")
33
+ def types(raw):
34
+ return [part.strip().lower() for part in raw.split(",") if part.strip()]
35
+ result = build_preview(parsed, args.current_version, types(args.include) if args.include is not None else None, types(args.exclude))
36
+ if args.date and args.format != "markdown":
37
+ raise ValueError("--date is only supported with Markdown output")
38
+ output = json.dumps(result, ensure_ascii=False, indent=2) + "\n" if args.format == "json" else render_console(result) if args.format == "console" else render_markdown(result, release_date=args.date)
39
+ print(output, end="")
40
+ except (OSError, UnicodeError, ValueError) as exc:
41
+ print(f"releasebrief: {exc}", file=sys.stderr)
42
+ return 2
43
+ return 0
44
+
45
+ if __name__ == "__main__":
46
+ raise SystemExit(main())
@@ -0,0 +1,195 @@
1
+ """Pure parsing and rendering routines for ReleaseBrief."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import re
6
+ from dataclasses import asdict, dataclass
7
+ from datetime import date
8
+ from typing import Any, Iterable
9
+
10
+ _HEADER = re.compile(r"^(?P<type>[a-zA-Z][a-zA-Z0-9-]*)(?:\((?P<scope>[^()\r\n]+)\))?(?P<bang>!)?:[ \t]+(?P<description>\S.*)$")
11
+ _BREAKING = re.compile(r"^BREAKING(?: |-)CHANGE:[ \t]*(.*)$")
12
+ _VERSION = re.compile(r"^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$")
13
+ _SECTIONS = {"feat": "Features", "fix": "Fixes", "perf": "Performance", "docs": "Documentation", "refactor": "Refactoring", "test": "Tests", "build": "Build", "ci": "CI", "chore": "Maintenance", "style": "Style", "revert": "Reverts"}
14
+ _DEFAULT_TYPES = tuple(_SECTIONS)
15
+
16
+ @dataclass(frozen=True)
17
+ class Commit:
18
+ type: str
19
+ scope: str | None
20
+ description: str
21
+ breaking: bool
22
+ breaking_note: str | None = None
23
+
24
+ @dataclass(frozen=True)
25
+ class Parsed:
26
+ commits: tuple[Commit, ...]
27
+ ignored: int
28
+ duplicates: int
29
+
30
+
31
+ def parse_commit(subject: str, body: str = "") -> Commit | None:
32
+ lines = subject.strip().splitlines()
33
+ if not lines:
34
+ return None
35
+ match = _HEADER.fullmatch(lines[0].strip())
36
+ if not match:
37
+ return None
38
+ note = None
39
+ is_breaking = bool(match["bang"])
40
+ for line in [*lines[1:], *body.splitlines()]:
41
+ breaking = _BREAKING.fullmatch(line.strip())
42
+ if breaking:
43
+ is_breaking = True
44
+ incoming = breaking[1].strip()
45
+ if incoming and incoming not in (note or "").split("\n"):
46
+ note = "\n".join(filter(None, (note, incoming)))
47
+ return Commit(match["type"].lower(), match["scope"], match["description"].strip(), is_breaking, note)
48
+
49
+
50
+ def read_records(text: str, kind: str) -> list[tuple[str, str]]:
51
+ """Read one subject per text line; footer lines belong to prior subject.
52
+
53
+ JSON supports a top-level array of strings or objects (subject + optional body).
54
+ A blank text line may separate subjects; arbitrary text is counted as ignored.
55
+ """
56
+ if kind == "json":
57
+ try:
58
+ data = json.loads(text)
59
+ except json.JSONDecodeError as exc:
60
+ raise ValueError(f"invalid JSON at line {exc.lineno}, column {exc.colno}: {exc.msg}") from exc
61
+ if not isinstance(data, list):
62
+ raise ValueError("JSON input must be an array")
63
+ result = []
64
+ for i, item in enumerate(data, 1):
65
+ if isinstance(item, str):
66
+ result.append((item, ""))
67
+ elif isinstance(item, dict) and isinstance(item.get("subject"), str) and isinstance(item.get("body", ""), str):
68
+ result.append((item["subject"], item.get("body", "")))
69
+ else:
70
+ raise ValueError(f"JSON record {i} must be a string or an object with string subject/body fields")
71
+ return result
72
+ result = []
73
+ for line in text.splitlines():
74
+ line = line.strip()
75
+ if not line:
76
+ continue
77
+ if _BREAKING.fullmatch(line) and result and _HEADER.fullmatch(result[-1][0]):
78
+ subject, body = result[-1]
79
+ result[-1] = (subject, f"{body}\n{line}")
80
+ else:
81
+ result.append((line, ""))
82
+ return result
83
+
84
+
85
+ def parse_records(records: Iterable[tuple[str, str]]) -> Parsed:
86
+ result: list[Commit] = []
87
+ seen: dict[tuple[str, str | None, str], int] = {}
88
+ ignored = duplicates = 0
89
+ for subject, body in records:
90
+ commit = parse_commit(subject, body)
91
+ if commit is None:
92
+ ignored += 1
93
+ continue
94
+ key = (commit.type, commit.scope, commit.description)
95
+ if key in seen:
96
+ duplicates += 1
97
+ # Preserve a breaking qualifier discovered on a duplicate.
98
+ idx = seen[key]
99
+ previous = result[idx]
100
+ notes = list(dict.fromkeys(
101
+ note for value in (previous.breaking_note, commit.breaking_note)
102
+ if value for note in value.split("\n")
103
+ ))
104
+ result[idx] = Commit(previous.type, previous.scope, previous.description,
105
+ previous.breaking or commit.breaking,
106
+ "\n".join(notes) or None)
107
+ continue
108
+ seen[key] = len(result)
109
+ result.append(commit)
110
+ return Parsed(tuple(result), ignored, duplicates)
111
+
112
+
113
+ def suggest(commits: Iterable[Commit]) -> str:
114
+ items = tuple(commits)
115
+ if any(c.breaking for c in items):
116
+ return "major"
117
+ if any(c.type == "feat" for c in items):
118
+ return "minor"
119
+ if any(c.type in {"fix", "perf", "revert"} for c in items):
120
+ return "patch"
121
+ return "none"
122
+
123
+
124
+ def next_version(current: str, bump: str) -> str:
125
+ match = _VERSION.fullmatch(current)
126
+ if not match:
127
+ raise ValueError("version must be a stable SemVer in MAJOR.MINOR.PATCH form (no leading zeroes)")
128
+ major, minor, patch = map(int, match.groups())
129
+ if bump == "major":
130
+ return f"{major + 1}.0.0"
131
+ if bump == "minor":
132
+ return f"{major}.{minor + 1}.0"
133
+ if bump == "patch":
134
+ return f"{major}.{minor}.{patch + 1}"
135
+ return current
136
+
137
+
138
+ def build_preview(parsed: Parsed, current: str | None = None, include: Iterable[str] | None = None, exclude: Iterable[str] = ()) -> dict[str, Any]:
139
+ included = set(include) if include is not None else set(_DEFAULT_TYPES)
140
+ excluded = set(exclude)
141
+ selected = [c for c in parsed.commits if c.breaking or (c.type in included and c.type not in excluded)]
142
+ bump = suggest(parsed.commits) # presentation filters never hide release impact
143
+ groups: dict[str, list[dict[str, Any]]] = {}
144
+ for commit in selected:
145
+ section = "Breaking changes" if commit.breaking else _SECTIONS.get(commit.type, commit.type.title())
146
+ groups.setdefault(section, []).append(asdict(commit))
147
+ order = ["Breaking changes", *_SECTIONS.values()]
148
+ ordered = {key: groups[key] for key in [*order, *sorted(groups.keys() - set(order))] if key in groups}
149
+ return {"bump": bump, "current_version": current, "suggested_version": next_version(current, bump) if current is not None else None, "counts": {"parsed": len(parsed.commits), "included": len(selected), "filtered": len(parsed.commits)-len(selected), "ignored": parsed.ignored, "duplicates": parsed.duplicates}, "sections": ordered}
150
+
151
+
152
+ def _display_text(value: str) -> str:
153
+ """Keep untrusted content from injecting terminal control sequences."""
154
+ return "".join(f"\\u{ord(char):04x}" if ord(char) < 32 or 127 <= ord(char) <= 159 else char for char in value)
155
+
156
+
157
+ def _md_text(value: str) -> str:
158
+ # Neutralize arbitrary Markdown/HTML while retaining visible text.
159
+ value = _display_text(value).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
160
+ return re.sub(r"([\\`*_{}\[\]#|!~])", r"\\\1", value.replace("\n", " ").replace("\r", " "))
161
+
162
+
163
+ def render_markdown(preview: dict[str, Any], *, release_date: str | None = None) -> str:
164
+ if release_date:
165
+ # Accept only an unambiguous calendar date.
166
+ if date.fromisoformat(release_date).isoformat() != release_date:
167
+ raise ValueError("date must use YYYY-MM-DD")
168
+ title = preview["suggested_version"] or "Unreleased"
169
+ lines = [f"# {title}" + (f" ({release_date})" if release_date else ""), "", f"Draft · suggested bump: **{preview['bump']}**", ""]
170
+ for name, commits in preview["sections"].items():
171
+ lines.extend([f"## {_md_text(name)}", ""])
172
+ for item in commits:
173
+ scope = f"**{_md_text(item['scope'])}:** " if item["scope"] else ""
174
+ lines.append(f"- {scope}{_md_text(item['description'])}")
175
+ if item["breaking_note"]:
176
+ lines.extend(f" - Breaking: {_md_text(note)}" for note in item["breaking_note"].split("\n"))
177
+ lines.append("")
178
+ if not preview["sections"]:
179
+ lines.extend(["No matching conventional commits.", ""])
180
+ return "\n".join(lines).rstrip() + "\n"
181
+
182
+
183
+ def render_console(preview: dict[str, Any]) -> str:
184
+ c = preview["counts"]
185
+ target = f" → {preview['suggested_version']}" if preview["suggested_version"] is not None else ""
186
+ lines = [f"ReleaseBrief draft | {preview['bump']} bump{target}", f"{c['included']} included · {c['filtered']} filtered · {c['duplicates']} duplicates · {c['ignored']} ignored", ""]
187
+ for heading, items in preview["sections"].items():
188
+ lines.append(heading)
189
+ for item in items:
190
+ prefix = f"[{_display_text(item['scope'])}] " if item["scope"] else ""
191
+ lines.append(f" • {prefix}{_display_text(item['description'])}")
192
+ if item["breaking_note"]:
193
+ lines.extend(f" Breaking: {_display_text(note)}" for note in item["breaking_note"].split("\n"))
194
+ lines.append("")
195
+ return "\n".join(lines).rstrip() + "\n"
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: releasebrief
3
+ Version: 0.1.0
4
+ Summary: Draft release notes and stable semantic version suggestions from supplied commit subjects.
5
+ Author: Ahmed Saeed
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/ahmedsaeed1-eng/releasebrief
8
+ Project-URL: Issues, https://github.com/ahmedsaeed1-eng/releasebrief/issues
9
+ Requires-Python: >=3.10
10
+ Description-Content-Type: text/markdown
11
+ License-File: LICENSE
12
+ License-File: THIRD_PARTY.md
13
+ Dynamic: license-file
14
+
15
+ ![ReleaseBrief timeline](assets/logo.svg)
16
+
17
+ # ReleaseBrief
18
+
19
+ **A review-ready release draft, before you publish.**
20
+
21
+ [![Tests](https://github.com/ahmedsaeed1-eng/releasebrief/actions/workflows/ci.yml/badge.svg?branch=main&event=push)](https://github.com/ahmedsaeed1-eng/releasebrief/actions/workflows/ci.yml?query=branch%3Amain+event%3Apush) [![Repository stars](https://img.shields.io/github/stars/ahmedsaeed1-eng/releasebrief?style=flat-square&color=c084fc)](https://github.com/ahmedsaeed1-eng/releasebrief/stargazers) [![MIT license](https://img.shields.io/badge/license-MIT-6d28d9?style=flat-square)](LICENSE) [![Python 3.10+](https://img.shields.io/badge/Python-3.10%2B-3776AB?style=flat-square&logo=python&logoColor=white)](pyproject.toml) [![No runtime dependencies](https://img.shields.io/badge/runtime-stdlib%20only-7c3aed?style=flat-square)](pyproject.toml)
22
+
23
+ > Collect commit subjects → draft release notes → refine sections → review SemVer.
24
+ >
25
+ > Your repository, tags and releases remain untouched.
26
+
27
+ | Jump to | Workflow |
28
+ | :--- | :--- |
29
+ | [01 · Collect](#01--collect) | Prepare text or exported JSON |
30
+ | [02 · Draft](#02--draft) | Generate the first changelog |
31
+ | [03 · Refine](#03--refine) | Select output and filter sections |
32
+ | [04 · Review](#04--review-the-version) | Check the version recommendation |
33
+ | [05 · Test](#05--test) | Run unit and CLI verification |
34
+
35
+ ## 01 · Collect
36
+
37
+ ReleaseBrief is a local Python CLI for drafting release notes from commit subjects you provide. It groups conventional commits, notices breaking changes, removes duplicate subjects, and recommends a stable SemVer increment without applying it. It does not run Git, call external services, mutate project files, create tags, or publish releases.
38
+
39
+ | Feature | Details |
40
+ |---|---|
41
+ | Input | UTF-8 text or JSON array via local file/stdin |
42
+ | Grouping | Features, fixes, performance, maintenance and more |
43
+ | Breaking changes | `!`, `BREAKING CHANGE:` and `BREAKING-CHANGE:` |
44
+ | Duplicate handling | Exact type/scope/description matches; preserves breaking qualifiers and distinct footer notes |
45
+ | Output | Markdown, machine-readable JSON, human-readable console |
46
+ | Filters | Include or exclude types without changing bump recommendation |
47
+ | Version | Suggest next `MAJOR.MINOR.PATCH` only; no tag or release mutation |
48
+
49
+ ## Package installation
50
+
51
+ Once the maintainer publishes this release to PyPI, install its pinned
52
+ Python CLI with:
53
+
54
+ ```sh
55
+ python -m pip install releasebrief==0.1.0
56
+ ```
57
+
58
+ Run the installed entry point against text you provide:
59
+
60
+ ```sh
61
+ printf 'feat: add preferences\nfix: correct exports\n' | releasebrief --current-version 1.2.3
62
+ ```
63
+
64
+ This is a standalone local CLI, not an MCP server. The source checkout
65
+ workflow below remains available with no runtime dependencies.
66
+
67
+ ## 02 · Draft
68
+
69
+ Requires Python 3.10 or later. No package installation is required. Clone or download the source repository, then run from its root:
70
+
71
+ ```sh
72
+ python -m releasebrief examples/commits.txt --current-version 1.2.3
73
+ ```
74
+
75
+ The bundled example includes a breaking change, so the result begins `# 2.0.0`. It is a draft, not a published release.
76
+
77
+ ## 03 · Refine
78
+
79
+ ```sh
80
+ python -m releasebrief examples/commits.json --input-format json --format json --current-version 1.2.3
81
+ python -m releasebrief examples/commits.txt --format console --exclude docs,chore
82
+ python -m releasebrief examples/commits.txt --date 2026-11-27 --strict > CHANGELOG-draft.md
83
+ ```
84
+
85
+ The final command redirects standard output to a new file through your shell; ReleaseBrief itself never writes to a project. Without an input path it reads standard input. Use `python -m releasebrief --help` for all options.
86
+
87
+ ### Input formats
88
+
89
+ Text expects one subject per line; an immediately following breaking-change footer belongs to the previous subject. Blank lines are ignored. For full commit bodies, use JSON rather than plaintext:
90
+
91
+ ```json
92
+ [
93
+ "feat(ui): add settings",
94
+ {"subject": "fix: correct exports"},
95
+ {"subject": "feat(api): rename option", "body": "BREAKING CHANGE: old option removed"}
96
+ ]
97
+ ```
98
+
99
+ The JSON input is an array of strings or objects with a string `subject` and optional string `body`. Unknown object fields are ignored. Non-conventional subjects are counted and omitted; `--strict` makes any such record an error. Invalid input exits with code 2 and writes diagnostics to standard error.
100
+
101
+ ## 04 · Review the version
102
+
103
+ | Commit content | Recommended bump |
104
+ |---|---|
105
+ | Breaking change | major |
106
+ | `feat` | minor |
107
+ | `fix`, `perf`, `revert` | patch |
108
+ | Other types or no commits | none |
109
+
110
+ Recommendations use all parsed commits, including types omitted by display filters. Breaking changes are never hidden by filters. Only stable numeric input versions (`1.2.3` style) are accepted; pre-release/build metadata, special policies for pre-1.0 software, and historical commit ancestry are not interpreted. Review every draft and recommendation manually before release. A duplicate subject can represent distinct changes; use suitably descriptive commit subjects or separate inputs when that distinction matters.
111
+
112
+ Default sections include conventional common types. Custom types are supported through `--include custom-type`. Text and JSON remain local, and Markdown escaping neutralizes common markup in supplied descriptions.
113
+
114
+ ## 05 · Test
115
+
116
+ ```sh
117
+ python -m unittest discover -s tests -v
118
+ ```
119
+
120
+ Tests include CLI execution, UTF-8 input, malformed records, strict mode, filtering, breaking changes, deduplication, and SemVer precedence. CI is configured for Python 3.10/3.12 on Linux, Windows and macOS; see the actual workflow status for the tested environments.
121
+
122
+ ## License and credits
123
+
124
+ MIT. See [LICENSE](LICENSE) and [THIRD_PARTY.md](THIRD_PARTY.md).
@@ -0,0 +1,17 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ THIRD_PARTY.md
5
+ pyproject.toml
6
+ assets/logo.svg
7
+ examples/commits.json
8
+ examples/commits.txt
9
+ releasebrief/__init__.py
10
+ releasebrief/__main__.py
11
+ releasebrief/core.py
12
+ releasebrief.egg-info/PKG-INFO
13
+ releasebrief.egg-info/SOURCES.txt
14
+ releasebrief.egg-info/dependency_links.txt
15
+ releasebrief.egg-info/entry_points.txt
16
+ releasebrief.egg-info/top_level.txt
17
+ tests/test_releasebrief.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ releasebrief = releasebrief.__main__:main
@@ -0,0 +1 @@
1
+ releasebrief
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,85 @@
1
+ import json
2
+ import subprocess
3
+ import sys
4
+ import unittest
5
+ from pathlib import Path
6
+ from tempfile import TemporaryDirectory
7
+
8
+ from releasebrief.core import build_preview, next_version, parse_records, read_records, render_markdown
9
+
10
+ ROOT = Path(__file__).resolve().parents[1]
11
+
12
+ class ReleaseBriefTests(unittest.TestCase):
13
+ def cli(self, *args, text=""):
14
+ return subprocess.run([sys.executable, "-m", "releasebrief", *args], input=text, text=True, encoding="utf-8", capture_output=True, cwd=ROOT)
15
+
16
+ def test_text_grouping_and_disjoint_sections(self):
17
+ out = self.cli("--current-version", "1.2.3", text="fix(ui): improve spacing\nfeat: add Arabic labels\ndocs: setup instructions\nfix(ui): improve spacing\nnot conventional\n")
18
+ self.assertEqual(out.returncode, 0, out.stderr)
19
+ self.assertIn("# 1.3.0", out.stdout)
20
+ self.assertLess(out.stdout.index("## Features"), out.stdout.index("## Fixes"))
21
+ self.assertEqual(out.stdout.count("improve spacing"), 1)
22
+
23
+ def test_breaking_duplicate_and_filters(self):
24
+ data = [{"subject":"fix(core): rename option"}, {"subject":"fix(core): rename option", "body":"BREAKING CHANGE: old option removed"}, "docs!: new format", "feat: new screen"]
25
+ result = self.cli("--input-format", "json", "--format", "json", "--exclude", "fix,docs,feat", "--current-version", "0.9.4", text=json.dumps(data))
26
+ self.assertEqual(result.returncode, 0, result.stderr)
27
+ view = json.loads(result.stdout)
28
+ self.assertEqual(view["bump"], "major")
29
+ self.assertEqual(view["suggested_version"], "1.0.0")
30
+ self.assertEqual(view["counts"], {"parsed":3,"included":2,"filtered":1,"ignored":0,"duplicates":1})
31
+ self.assertEqual(len(view["sections"]["Breaking changes"]), 2)
32
+ self.assertEqual(view["sections"]["Breaking changes"][0]["breaking_note"], "old option removed")
33
+
34
+ def test_distinct_breaking_notes_preserved(self):
35
+ parsed = parse_records(read_records("feat!: rename export\nBREAKING CHANGE: old header\nBREAKING CHANGE: old footer\nfeat!: rename export\nBREAKING CHANGE: old header\nBREAKING CHANGE: old option", "text"))
36
+ preview = build_preview(parsed)
37
+ self.assertEqual(preview["counts"]["duplicates"], 1)
38
+ self.assertEqual(preview["sections"]["Breaking changes"][0]["breaking_note"], "old header\nold footer\nold option")
39
+ markdown = render_markdown(preview)
40
+ for note in ("old header", "old footer", "old option"):
41
+ self.assertEqual(markdown.count("Breaking: " + note), 1)
42
+
43
+ def test_semver_priority_and_filters(self):
44
+ self.assertEqual(next_version("2.0.1", "patch"), "2.0.2")
45
+ parsed = parse_records(read_records("feat: add option\nchore: format files", "text"))
46
+ self.assertEqual(build_preview(parsed, "2.0.1", include=["chore"])["bump"], "minor")
47
+ self.assertEqual(build_preview(parse_records(read_records("docs: add guide", "text")), "2.0.1")["suggested_version"], "2.0.1")
48
+ with self.assertRaises(ValueError):
49
+ next_version("01.0.1", "patch")
50
+
51
+ def test_cli_file_json_and_unicode(self):
52
+ with TemporaryDirectory() as temp:
53
+ p = Path(temp) / "commits.json"
54
+ p.write_text(json.dumps(["feat: واجهة عربية"], ensure_ascii=False), encoding="utf-8")
55
+ result = self.cli(str(p), "--input-format", "json", "--format", "console")
56
+ self.assertEqual(result.returncode, 0, result.stderr)
57
+ self.assertIn("واجهة عربية", result.stdout)
58
+ self.assertIn("minor bump", result.stdout)
59
+
60
+ def test_footers_and_markdown_escape(self):
61
+ parsed = parse_records(read_records("feat: <img> and *text*\nBREAKING-CHANGE: old [link]\n", "text"))
62
+ out = render_markdown(build_preview(parsed), release_date="2026-01-31")
63
+ self.assertIn("# Unreleased (2026-01-31)", out)
64
+ self.assertIn("&lt;img&gt; and \\*text\\*", out)
65
+ self.assertIn("Breaking: old \\[link\\]", out)
66
+
67
+ def test_invalid_inputs_and_strict(self):
68
+ for flags, text in [(("--strict",),"not a conventional commit"), (("--input-format", "json"),"{"), (("--input-format", "json"),'{"subject":"feat: x"}'), (("--input-format", "json"),"[1]"), (("--current-version", "1.2-beta"),"feat: x"), (("--date", "2026-02-30"),"feat: x"), (("--date", "2026-01-01", "--format", "json"),"feat: x")]:
69
+ with self.subTest(flags=flags):
70
+ out = self.cli(*flags, text=text)
71
+ self.assertEqual(out.returncode, 2)
72
+ self.assertEqual(out.stdout, "")
73
+ self.assertIn("releasebrief:", out.stderr)
74
+
75
+ def test_console_escapes_control_characters(self):
76
+ result = self.cli("--format", "console", text="feat: terminal \x1b[31m sequence")
77
+ self.assertNotIn("\x1b", result.stdout)
78
+ self.assertIn(r"\u001b", result.stdout)
79
+
80
+ def test_empty_and_custom_type(self):
81
+ self.assertIn("No matching conventional commits", self.cli(text="\n").stdout)
82
+ self.assertIn("## Translate", self.cli("--include", "translate", text="translate: add French").stdout)
83
+
84
+ if __name__ == "__main__":
85
+ unittest.main()