Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/pull_request_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ SPDX-License-Identifier: MIT

## Developer checklist (address before review)

- [ ] Changelog.md updated
- [ ] Changelog fragment added in `docs/changelog/unreleased/` (see the README there)
- [ ] Prepared update for depending repositories
- [ ] Documentation updated (public API changes only)
- [ ] API docstrings updated (public API changes only)
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,6 @@ CMakeUserPresets.json
#ignore temporary merge conflict backup files
*.orig

# generated from docs/changelog/unreleased/ by docs/changelog/assemble.py
/docs/changelog/versions/latest.md
/docs/changelog/versions-toctree.inc
45 changes: 10 additions & 35 deletions SilKit/ci/bump_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,21 @@
#
# SPDX-License-Identifier: MIT

# Bumps the SIL Kit version: patches SilKitVersionMacros.h, archives
# docs/changelog/versions/latest.md as <current-version>.md, lists it in
# docs/changelog/overview.rst and resets latest.md.
# Bumps the SIL Kit version in SilKitVersionMacros.h. The changelog of the
# current version must be finalized first (finalize_changelog.py writes
# docs/changelog/versions/<current-version>.md).
# See docs/development/release.md.

import argparse
import datetime
import pathlib
import re
import sys

ROOT = pathlib.Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "docs/changelog"))
import assemble # noqa: E402

HEADER = ROOT / "SilKit/include/silkit/capi/SilKitVersionMacros.h"
VERSIONS_DIR = ROOT / "docs/changelog/versions"
LATEST = VERSIONS_DIR / "latest.md"
OVERVIEW = ROOT / "docs/changelog/overview.rst"
COMPONENTS = ("MAJOR", "MINOR", "PATCH")


Expand Down Expand Up @@ -54,11 +53,8 @@ def write(path, text, eol, dry_run):


def main():
parser = argparse.ArgumentParser(description="Bump the SIL Kit version and rotate the changelog.")
parser = argparse.ArgumentParser(description="Bump the SIL Kit version.")
parser.add_argument("version", help="new version, e.g. 5.0.9")
parser.add_argument("--date", type=datetime.date.fromisoformat,
help="release date of the current version, YYYY-MM-DD (default: the date already in "
"latest.md, or today if it is UNRELEASED)")
parser.add_argument("-n", "--dry-run", action="store_true", help="only print the files that would be written")
args = parser.parse_args()

Expand All @@ -78,35 +74,14 @@ def main():
if new <= current:
die(f"{args.version} is not newer than {'.'.join(map(str, current))}")

current_name = ".".join(map(str, current))
new_name = ".".join(map(str, new))

archive = VERSIONS_DIR / (current_name + ".md")
if archive.exists():
die(f"{archive.relative_to(ROOT)} already exists")

latest, latest_eol = read(LATEST)
heading = re.search(r"^# \[[^\]]*\] - (UNRELEASED|\d{4}-\d{2}-\d{2})$", latest, re.M)
if not heading:
die(f"no '# [x.y.z] - UNRELEASED' or '# [x.y.z] - YYYY-MM-DD' heading in {LATEST.relative_to(ROOT)}")
date = args.date
if date is None:
date = datetime.date.today() if heading.group(1) == "UNRELEASED" else heading.group(1)
latest = f"{latest[:heading.start()]}# [{current_name}] - {date}{latest[heading.end():]}"

overview, overview_eol = read(OVERVIEW)
anchor = re.search(r"^( *)versions/latest\.md$", overview, re.M)
if not anchor:
die(f"no 'versions/latest.md' entry in {OVERVIEW.relative_to(ROOT)}")
overview = f"{overview[:anchor.end()]}\n{anchor.group(1)}versions/{current_name}.md{overview[anchor.end():]}"
page = assemble.version_page(".".join(map(str, current)))
if not page.exists():
die(f"{page.relative_to(ROOT)} does not exist; finalize the changelog first (finalize_changelog.py)")

for component, value in zip(COMPONENTS, new):
header = re.sub(rf"^(#define SILKIT_VERSION_{component} )\d+$", rf"\g<1>{value}", header, flags=re.M)

write(HEADER, header, header_eol, args.dry_run)
write(archive, latest, latest_eol, args.dry_run)
write(LATEST, f"# [{new_name}] - UNRELEASED\n\n> This changelog entry is still empty.\n", latest_eol, args.dry_run)
write(OVERVIEW, overview, overview_eol, args.dry_run)


if __name__ == "__main__":
Expand Down
2 changes: 1 addition & 1 deletion SilKit/ci/check_files_changed.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ def check_run_build(url: str):
file_path = fileObject["filename"]
file = file_path.split(sep="/")[-1]

if file not in exceptional_files:
if file not in exceptional_files and not file_path.startswith('docs/changelog/unreleased/'):
run_builds = "true"
break

Expand Down
59 changes: 59 additions & 0 deletions SilKit/ci/finalize_changelog.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#!/usr/bin/env python3

# SPDX-FileCopyrightText: 2026 Vector Informatik GmbH
#
# SPDX-License-Identifier: MIT

# Finalizes the changelog of the current version when preparing a delivery:
# writes the fragments in docs/changelog/unreleased/ to
# docs/changelog/versions/<current-version>.md with the release date and
# deletes them. The version bump (bump_version.py) comes later.
# See docs/development/release.md.

import argparse
import datetime
import pathlib
import sys

ROOT = pathlib.Path(__file__).resolve().parents[2]
sys.path.insert(0, str(ROOT / "docs/changelog"))
import assemble # noqa: E402


def die(message):
sys.exit("error: " + message)


def main():
parser = argparse.ArgumentParser(description="Write the changelog fragments to the page of the current version.")
parser.add_argument("--date", type=datetime.date.fromisoformat, default=datetime.date.today(),
help="release date, YYYY-MM-DD (default: today)")
parser.add_argument("-n", "--dry-run", action="store_true", help="only print what would be done")
args = parser.parse_args()
prefix = "[dry-run] " if args.dry_run else ""

try:
version = assemble.current_version()
found = assemble.fragments()
except assemble.FragmentError as e:
die(str(e))

page = assemble.version_page(version)
if page.exists():
die(f"{page.relative_to(ROOT)} already exists; bump the version first (bump_version.py)")
paths = assemble.fragment_paths(found)
if not paths:
die(f"no changelog fragments in {assemble.UNRELEASED_DIR.relative_to(ROOT)}")

print(f"{prefix}write {page.relative_to(ROOT)}")
if not args.dry_run:
with open(page, "w", encoding="utf-8", newline="\n") as f:
f.write(assemble.render(f"[{version}] - {args.date}", found))
for path in paths:
print(f"{prefix}delete {path.relative_to(ROOT)}")
if not args.dry_run:
path.unlink()


if __name__ == "__main__":
main()
11 changes: 10 additions & 1 deletion docs/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,9 @@ file(GLOB_RECURSE SPHINX_SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/*.rst)
# Markdown pages (the changelog entries, development/release.md) are part of the
# Sphinx sources too and must retrigger the build when edited.
file(GLOB_RECURSE SPHINX_MD_FILES ${CMAKE_CURRENT_SOURCE_DIR}/*.md)
# latest.md is generated by conf.py from the fragments in changelog/unreleased/,
# which the glob already lists; as a dependency it would retrigger every build.
list(FILTER SPHINX_MD_FILES EXCLUDE REGEX "/changelog/versions/latest\.md$")
list(APPEND SPHINX_SOURCE_FILES ${SPHINX_MD_FILES})
file(GLOB_RECURSE SVG_FILES ${CMAKE_CURRENT_SOURCE_DIR}/*.svg)
list(APPEND SPHINX_SOURCE_FILES ${CMAKE_CURRENT_SOURCE_DIR}/_static/custom.css)
Expand Down Expand Up @@ -97,9 +100,15 @@ install(DIRECTORY ${SPHINX_BUILD}/
REGEX "\.venv$" EXCLUDE
REGEX "\.buildinfo$" EXCLUDE
)
# The changelog of this version once it is finalized (SilKit/ci/finalize_changelog.py),
# otherwise the one conf.py generates from the fragments during the Sphinx build.
set(SILKIT_DOCS_CHANGELOG changelog/versions/${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}.${PROJECT_VERSION_PATCH}.md)
if (NOT EXISTS ${CMAKE_CURRENT_SOURCE_DIR}/${SILKIT_DOCS_CHANGELOG})
set(SILKIT_DOCS_CHANGELOG changelog/versions/latest.md)
endif()
install(
FILES
changelog/versions/latest.md
${SILKIT_DOCS_CHANGELOG}
DESTINATION .
COMPONENT docs
RENAME CHANGELOG.md
Expand Down
190 changes: 190 additions & 0 deletions docs/changelog/assemble.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,190 @@
#!/usr/bin/env python3

# SPDX-FileCopyrightText: 2026 Vector Informatik GmbH
#
# SPDX-License-Identifier: MIT

# Assembles the changelog from the fragments in
# docs/changelog/unreleased/<section>/*.md. Every pull request adds its own
# fragment instead of editing a shared file, so changelog entries never
# conflict. See docs/changelog/unreleased/README.md.
#
# Lifecycle of a version's changelog:
# 1. During development, the fragments are rendered as versions/latest.md,
# "# [<version>] - UNRELEASED", by the docs build (docs/conf.py).
# 2. When preparing the delivery, SilKit/ci/finalize_changelog.py writes them
# to versions/<version>.md with the release date and deletes them.
# Fragments merged after that belong to the next version and show up as
# "# [Unreleased]" until the version bump.
# 3. SilKit/ci/bump_version.py bumps the version; it needs step 2 done.
#
# The docs build also generates the version list of overview.rst, so neither
# script edits it.
#
# python3 docs/changelog/assemble.py # print the unreleased changelog
# python3 docs/changelog/assemble.py --check # only validate the fragments
# python3 docs/changelog/assemble.py -o FILE # write it to FILE

import argparse
import pathlib
import re
import sys

CHANGELOG_DIR = pathlib.Path(__file__).resolve().parent
UNRELEASED_DIR = CHANGELOG_DIR / "unreleased"
VERSIONS_DIR = CHANGELOG_DIR / "versions"
LATEST = VERSIONS_DIR / "latest.md"
TOCTREE = CHANGELOG_DIR / "versions-toctree.inc"
VERSION_HEADER = CHANGELOG_DIR.parents[1] / "SilKit/include/silkit/capi/SilKitVersionMacros.h"

# Directory name -> heading, in the order of Keep a Changelog. "notes" holds
# free-form text (with its own "##" heading) that goes before all sections.
SECTIONS = {
"notes": None,
"added": "Added",
"changed": "Changed",
"deprecated": "Deprecated",
"removed": "Removed",
"fixed": "Fixed",
}
IGNORED = {"README.md", ".gitkeep"}


class FragmentError(Exception):
pass


def fragments():
"""Returns {section: [(path, text)]}, sorted by file name; raises FragmentError on misplaced or empty files."""
found = {section: [] for section in SECTIONS}
errors = []
for path in sorted(UNRELEASED_DIR.rglob("*")):
if path.is_dir() or path.name in IGNORED:
continue
relative = path.relative_to(UNRELEASED_DIR)
if len(relative.parts) != 2 or relative.parts[0] not in SECTIONS or path.suffix != ".md":
errors.append(f"{relative.as_posix()}: expected <section>/<name>.md with <section> one of "
f"{', '.join(SECTIONS)}")
continue
text = path.read_text(encoding="utf-8").strip()
if not text:
errors.append(f"{relative.as_posix()}: empty")
continue
if relative.parts[0] != "notes" and not text.startswith("- "):
errors.append(f"{relative.as_posix()}: must be a list item starting with '- '")
continue
found[relative.parts[0]].append((path, text))
if errors:
raise FragmentError("invalid changelog fragments:\n " + "\n ".join(errors))
return found


def fragment_paths(found):
return [path for entries in found.values() for path, _ in entries]


def current_version():
header = VERSION_HEADER.read_text(encoding="utf-8")
parts = []
for component in ("MAJOR", "MINOR", "PATCH"):
match = re.search(rf"^#define SILKIT_VERSION_{component} (\d+)$", header, re.M)
if not match:
raise FragmentError(f"no SILKIT_VERSION_{component} in {VERSION_HEADER}")
parts.append(match.group(1))
return ".".join(parts)


def version_page(version):
return VERSIONS_DIR / f"{version}.md"


def render(heading, found):
"""A changelog page with the heading `heading` (without "# ") from the fragments in `found`."""
blocks = [f"# {heading}"]
for section, title in SECTIONS.items():
texts = [text for _, text in found[section]]
if not texts:
continue
if title is None:
blocks.extend(texts)
else:
blocks.append(f"## {title}\n\n" + "\n".join(texts))
if len(blocks) == 1:
blocks.append("> This changelog entry is still empty.")
return "\n\n".join(blocks) + "\n"


def render_latest(found=None):
"""The page of the fragments: "[<version>] - UNRELEASED", or "[Unreleased]" once <version>.md is finalized."""
if found is None:
found = fragments()
version = current_version()
if version_page(version).exists():
return render("[Unreleased]", found)
return render(f"[{version}] - UNRELEASED", found)


def latest_is_listed(found):
"""latest.md is left out of the docs between finalizing a version and the next fragment, when it is empty."""
return not version_page(current_version()).exists() or bool(fragment_paths(found))


def version_pages():
"""The pages in versions/, newest first: x.y.z.md by version, then the older <major>.rst pages."""
semver = []
older = []
for path in VERSIONS_DIR.iterdir():
match = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)\.md", path.name)
if match:
semver.append((tuple(int(x) for x in match.groups()), path.name))
elif path.suffix == ".rst":
match = re.match(r"\d+", path.name)
older.append((int(match.group()) if match else -1, path.name))
return [name for _, name in sorted(semver, reverse=True)] + [name for _, name in sorted(older, reverse=True)]


def render_toctree(include_latest):
entries = (["latest.md"] if include_latest else []) + version_pages()
lines = [".. toctree::", " :maxdepth: 1", ""] + [f" versions/{name}" for name in entries]
return "\n".join(lines) + "\n"


def write_if_changed(path, text):
"""Writes only on change, so that the docs build doesn't see a new file every time."""
try:
if path.read_text(encoding="utf-8") == text:
return
except FileNotFoundError:
pass
with open(path, "w", encoding="utf-8", newline="\n") as f:
f.write(text)


def write_docs_sources():
"""Called by docs/conf.py: writes latest.md and the version list. Returns whether latest.md is listed."""
found = fragments()
listed = latest_is_listed(found)
write_if_changed(LATEST, render_latest(found))
write_if_changed(TOCTREE, render_toctree(listed))
return listed


def main():
parser = argparse.ArgumentParser(description="Assemble the unreleased changelog from its fragments.")
parser.add_argument("--check", action="store_true", help="only validate the fragments")
parser.add_argument("-o", "--output", type=pathlib.Path, help="write to this file instead of stdout")
args = parser.parse_args()
try:
text = render_latest()
except FragmentError as e:
sys.exit(f"error: {e}")
if args.check:
return
if args.output:
write_if_changed(args.output, text)
else:
sys.stdout.write(text)


if __name__ == "__main__":
main()
Loading
Loading