diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 0e94d0c..2a3b3bb 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -30,6 +30,22 @@ jobs: - name: "Tests: app workflow (~1 min)" run: python -m pytest -m app -v --tb=short --durations=10 + release-check: + name: Version bumped & changelog released + runs-on: ubuntu-latest + if: github.event_name == 'pull_request' + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Check version and CHANGELOG.md against main + run: python -m scripts.check_release --base-ref origin/${{ github.base_ref }} + deploy: name: Build & deploy to Cloud Run needs: test @@ -60,3 +76,31 @@ jobs: --memory=4Gi \ --concurrency=8 \ --max-instances=1 + + tag-release: + name: Tag & publish GitHub Release + needs: deploy + runs-on: ubuntu-latest + if: github.event_name == 'push' && github.ref == 'refs/heads/main' + permissions: + contents: write + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: actions/setup-python@v5 + with: + python-version: "3.13" + + - name: Create tag and release if this version is new + env: + GH_TOKEN: ${{ github.token }} + run: | + VERSION=$(python -c "from utils.version import get_version; print(get_version())") + if git rev-parse -q --verify "refs/tags/v$VERSION" >/dev/null; then + echo "Tag v$VERSION already exists; nothing to release" + exit 0 + fi + python -m scripts.check_release --notes > release-notes.md + gh release create "v$VERSION" --target "$GITHUB_SHA" --title "v$VERSION" --notes-file release-notes.md diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 4696398..b3718b4 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -1,6 +1,6 @@ name: Tests -# Full suite on PRs into development. +# Full suite + changelog check on PRs into development. # PRs and pushes to main run the same suite in deploy.yml, which gates deployment. on: pull_request: @@ -25,3 +25,22 @@ jobs: - name: "Tests: app workflow (~1 min)" run: python -m pytest -m app -v --tb=short --durations=10 + + changelog: + name: CHANGELOG.md updated + runs-on: ubuntu-latest + # Add the "skip-changelog" label to a PR for changes that don't need an entry (CI, typos) + if: ${{ !contains(github.event.pull_request.labels.*.name, 'skip-changelog') }} + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + + - name: Check that the PR adds a changelog entry + run: | + if git diff --name-only origin/${{ github.base_ref }}...HEAD | grep -qx CHANGELOG.md; then + echo "CHANGELOG.md updated" + else + echo "::error::Add an entry under '## [Unreleased]' in CHANGELOG.md, or label the PR 'skip-changelog'." + exit 1 + fi diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..ed70ffa --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,46 @@ +# Changelog + +All notable changes to the Berkeley Decarb Tool are documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project +uses [Semantic Versioning](https://semver.org/). While the version is below 1.0.0: + +- **minor** (0.x.0): new features, or changes that alter calculation results or the format of + saved/uploaded data +- **patch** (0.0.x): bug fixes and UI tweaks + +Add entries under `[Unreleased]` with every pull request, grouped as Added / Changed / Fixed / +Removed. `scripts/bump_version.py` turns them into a release section. + +## [Unreleased] + +## [0.1.0] - 2026-10-13 + +First versioned release of the tool. Earlier deployments were not versioned consistently; +this changelog starts here. + +### Added + +- Four-step workflow: loads, equipment, emissions, results +- Building load profiles from the library (DOE prototypes and measured data), filterable by + location, building type and vintage, or uploaded as a custom CSV +- Load scaling and base-load adjustment for selected load profiles +- Location search to set the building location independently of the load profile +- Equipment scenarios combining heat recovery water-to-water heat pumps, air-to-water heat pumps, + air-cooled chillers, and gas or electric boilers, with an editable equipment library +- Grid emission scenarios based on NREL Cambium data (long-run and short-run marginal rates), + including refrigerant and natural gas leakage assumptions +- Results page comparing energy use and emissions across equipment and emission scenarios, with + data download +- SI/IP unit toggle +- Tiered automated test suite (unit, verification, regression, integration, app) +- Versioning and changelog workflow; the footer version is read from `pyproject.toml` + +### Fixed + +- Summary cards on the loads page are shown empty before a load is selected, instead of + "No metadata yet" +- Add/Reset buttons on the equipment and emissions pages stay on the right on narrow windows; + the subtitle wraps instead +- Location set via the location search is stored correctly (#200, #201) +- Faster results download (#110) diff --git a/README.md b/README.md index 5dbedb9..d01554a 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,8 @@ The tool is designed to bring consistency, transparency, and scientific robustne ## Documentation While the tool is still under development, we have set up a short documentation outlining underlying calculations [here](https://cbe-berkeley.gitbook.io/decarb).
+Release notes for each version are in [CHANGELOG.md](CHANGELOG.md).
+

(back to top)

diff --git a/layout/footer.py b/layout/footer.py index 78bc547..5692b32 100644 --- a/layout/footer.py +++ b/layout/footer.py @@ -1,5 +1,7 @@ import dash_mantine_components as dmc +from utils.version import get_version + def shell_footer(): # --- Top band: logos, nav links, socials, citation --- @@ -130,7 +132,7 @@ def shell_footer(): version_and_license = dmc.Group( [ - dmc.Text("Version 1.2.0", fz="xs", c="dimmed"), + dmc.Text(f"Version {get_version()}", fz="xs", c="dimmed"), dmc.Anchor( dmc.Image( src="https://img.shields.io/badge/License-MIT-yellow.svg", diff --git a/pyproject.toml b/pyproject.toml index 02e9b61..214e3c2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "decarb-tool" -version = "1.2.0" +version = "0.1.0" description = "Building decarbonization planning tool" requires-python = ">=3.12" diff --git a/scripts/__init__.py b/scripts/__init__.py new file mode 100644 index 0000000..4db8d04 --- /dev/null +++ b/scripts/__init__.py @@ -0,0 +1 @@ +# Release tooling (run as modules, e.g. python -m scripts.bump_version) diff --git a/scripts/bump_version.py b/scripts/bump_version.py new file mode 100644 index 0000000..e661903 --- /dev/null +++ b/scripts/bump_version.py @@ -0,0 +1,115 @@ +"""Cut a release: bump the version in pyproject.toml and date the [Unreleased] changelog entries. + +Usage (from the repo root): + python -m scripts.bump_version patch|minor|major [--dry-run] + python -m scripts.bump_version 0.4.0 [--dry-run] +""" + +import argparse +import re +import sys +from datetime import date +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +PYPROJECT = ROOT / "pyproject.toml" +CHANGELOG = ROOT / "CHANGELOG.md" + +VERSION_LINE = re.compile(r'^version = "([^"]+)"', re.MULTILINE) +SECTION_HEADING = re.compile(r"^## \[([^\]]+)\].*$", re.MULTILINE) +UNRELEASED = "Unreleased" + + +def parse_version(version: str) -> tuple[int, int, int]: + match = re.fullmatch(r"(\d+)\.(\d+)\.(\d+)", version) + if not match: + raise ValueError(f"Not a MAJOR.MINOR.PATCH version: {version!r}") + return tuple(int(part) for part in match.groups()) + + +def bump(current: str, part: str) -> str: + """Return the next version: `part` is major/minor/patch or an explicit X.Y.Z.""" + major, minor, patch = parse_version(current) + if part == "major": + return f"{major + 1}.0.0" + if part == "minor": + return f"{major}.{minor + 1}.0" + if part == "patch": + return f"{major}.{minor}.{patch + 1}" + if parse_version(part) <= (major, minor, patch): + raise ValueError(f"New version {part} must be higher than the current {current}") + return part + + +def read_pyproject_version(pyproject_text: str) -> str: + match = VERSION_LINE.search(pyproject_text) + if not match: + raise ValueError('No `version = "..."` line found in pyproject.toml') + return match.group(1) + + +def set_pyproject_version(pyproject_text: str, version: str) -> str: + return VERSION_LINE.sub(f'version = "{version}"', pyproject_text, count=1) + + +def extract_section(changelog_text: str, name: str) -> str | None: + """Return the body of the `## [name]` section (without its heading), or None if missing.""" + headings = list(SECTION_HEADING.finditer(changelog_text)) + for i, heading in enumerate(headings): + if heading.group(1) == name: + end = headings[i + 1].start() if i + 1 < len(headings) else len(changelog_text) + return changelog_text[heading.end() : end].strip() + return None + + +def release_changelog(changelog_text: str, version: str, release_date: str) -> str: + """Move the [Unreleased] entries into a new `## [version] - date` section.""" + unreleased = extract_section(changelog_text, UNRELEASED) + if unreleased is None: + raise ValueError("CHANGELOG.md has no '## [Unreleased]' section") + if not unreleased: + raise ValueError("The [Unreleased] section of CHANGELOG.md is empty; nothing to release") + if extract_section(changelog_text, version) is not None: + raise ValueError(f"CHANGELOG.md already has a section for {version}") + + heading = next(h for h in SECTION_HEADING.finditer(changelog_text) if h.group(1) == UNRELEASED) + next_heading = next( + (h for h in SECTION_HEADING.finditer(changelog_text) if h.start() > heading.start()), None + ) + end = next_heading.start() if next_heading else len(changelog_text) + released = f"## [{UNRELEASED}]\n\n## [{version}] - {release_date}\n\n{unreleased}\n" + ( + "\n" if next_heading else "" + ) + return changelog_text[: heading.start()] + released + changelog_text[end:] + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("part", help="major, minor, patch, or an explicit X.Y.Z") + parser.add_argument("--dry-run", action="store_true", help="print the result, write nothing") + args = parser.parse_args(argv) + + pyproject_text = PYPROJECT.read_text() + changelog_text = CHANGELOG.read_text() + current = read_pyproject_version(pyproject_text) + + try: + new = bump(current, args.part) + new_changelog = release_changelog(changelog_text, new, date.today().isoformat()) + except ValueError as e: + print(f"error: {e}", file=sys.stderr) + return 1 + + if args.dry_run: + print(f"{current} -> {new} (dry run, nothing written)\n") + print(f"## [{new}]\n\n{extract_section(new_changelog, new)}") + return 0 + + PYPROJECT.write_text(set_pyproject_version(pyproject_text, new)) + CHANGELOG.write_text(new_changelog) + print(f"{current} -> {new}: updated pyproject.toml and CHANGELOG.md") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/check_release.py b/scripts/check_release.py new file mode 100644 index 0000000..7d208c2 --- /dev/null +++ b/scripts/check_release.py @@ -0,0 +1,83 @@ +"""CI checks for releases, and release notes for the GitHub Release. + +Usage (from the repo root): + python -m scripts.check_release --base-ref origin/main # PR into main: is this a valid release? + python -m scripts.check_release --notes # print the current version's changelog section +""" + +import argparse +import subprocess +import sys + +from scripts.bump_version import ( + CHANGELOG, + PYPROJECT, + UNRELEASED, + extract_section, + parse_version, + read_pyproject_version, +) + + +def _git_show(ref: str, path: str) -> str | None: + result = subprocess.run(["git", "show", f"{ref}:{path}"], capture_output=True, text=True) + return result.stdout if result.returncode == 0 else None + + +def check_release( + version: str, changelog_text: str, base_version: str, base_has_changelog: bool +) -> list[str]: + """Return a list of problems; empty means the release is valid.""" + problems = [] + # The first versioned release (no CHANGELOG.md on the base yet) restarted the numbering at + # 0.1.0, so the version-increase check only applies from then on. + if base_has_changelog and parse_version(version) <= parse_version(base_version): + problems.append( + f"Version {version} is not higher than {base_version} on the base branch. " + "Run `python -m scripts.bump_version patch|minor|major`." + ) + if extract_section(changelog_text, version) is None: + problems.append(f"CHANGELOG.md has no '## [{version}]' section.") + if extract_section(changelog_text, UNRELEASED): + problems.append( + "CHANGELOG.md still has entries under [Unreleased]; " + "run the bump script to move them into the release." + ) + return problems + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + group = parser.add_mutually_exclusive_group(required=True) + group.add_argument("--base-ref", help="git ref of the branch being merged into") + group.add_argument("--notes", action="store_true", help="print the release notes") + args = parser.parse_args(argv) + + version = read_pyproject_version(PYPROJECT.read_text()) + changelog_text = CHANGELOG.read_text() + + if args.notes: + notes = extract_section(changelog_text, version) + if notes is None: + print(f"error: CHANGELOG.md has no section for {version}", file=sys.stderr) + return 1 + print(notes) + return 0 + + base_pyproject = _git_show(args.base_ref, "pyproject.toml") + if base_pyproject is None: + print(f"error: could not read pyproject.toml at {args.base_ref}", file=sys.stderr) + return 1 + base_version = read_pyproject_version(base_pyproject) + base_has_changelog = _git_show(args.base_ref, "CHANGELOG.md") is not None + + problems = check_release(version, changelog_text, base_version, base_has_changelog) + for problem in problems: + print(f"error: {problem}", file=sys.stderr) + if not problems: + print(f"OK: releasing {version} (base: {base_version})") + return 1 if problems else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_versioning.py b/tests/test_versioning.py new file mode 100644 index 0000000..fe66ad0 --- /dev/null +++ b/tests/test_versioning.py @@ -0,0 +1,105 @@ +"""Tests for the release tooling (scripts/) and the single-sourced app version.""" + +import tomllib + +import pytest +from scripts.bump_version import CHANGELOG as CHANGELOG_PATH +from scripts.bump_version import ( + PYPROJECT, + bump, + extract_section, + read_pyproject_version, + release_changelog, + set_pyproject_version, +) +from scripts.check_release import check_release + +from layout.footer import shell_footer +from utils.version import get_version + +CHANGELOG = """# Changelog + +Intro text. + +## [Unreleased] + +### Fixed + +- A bug + +## [0.1.0] - 2026-01-01 + +### Added + +- First release +""" + + +@pytest.mark.unit +class TestBump: + @pytest.mark.parametrize( + ("part", "expected"), + [("patch", "0.1.1"), ("minor", "0.2.0"), ("major", "1.0.0"), ("0.3.0", "0.3.0")], + ) + def test_bump(self, part, expected): + assert bump("0.1.0", part) == expected + + @pytest.mark.parametrize("part", ["0.1.0", "0.0.9", "1.0", "v0.2.0"]) + def test_rejects_invalid_or_lower_version(self, part): + with pytest.raises(ValueError): + bump("0.1.0", part) + + def test_pyproject_version_roundtrip(self): + text = '[project]\nname = "x"\nversion = "0.1.0"\n\n[tool.ruff]\ntarget-version = "py312"\n' + new = set_pyproject_version(text, "0.2.0") + assert read_pyproject_version(new) == "0.2.0" + assert 'target-version = "py312"' in new + + +@pytest.mark.unit +class TestChangelog: + def test_extract_section(self): + assert extract_section(CHANGELOG, "Unreleased") == "### Fixed\n\n- A bug" + assert extract_section(CHANGELOG, "0.1.0") == "### Added\n\n- First release" + assert extract_section(CHANGELOG, "9.9.9") is None + + def test_release_moves_unreleased_entries(self): + new = release_changelog(CHANGELOG, "0.1.1", "2026-02-01") + assert extract_section(new, "Unreleased") == "" + assert extract_section(new, "0.1.1") == "### Fixed\n\n- A bug" + assert extract_section(new, "0.1.0") == "### Added\n\n- First release" + assert "## [0.1.1] - 2026-02-01" in new + assert new.index("## [Unreleased]") < new.index("## [0.1.1]") < new.index("## [0.1.0]") + assert new.startswith("# Changelog\n\nIntro text.\n\n") + + def test_release_refuses_empty_unreleased(self): + released = release_changelog(CHANGELOG, "0.1.1", "2026-02-01") + with pytest.raises(ValueError, match="empty"): + release_changelog(released, "0.1.2", "2026-03-01") + + +@pytest.mark.unit +class TestCheckRelease: + def test_valid_release(self): + released = release_changelog(CHANGELOG, "0.1.1", "2026-02-01") + assert check_release("0.1.1", released, "0.1.0", base_has_changelog=True) == [] + + def test_flags_missing_bump_section_and_unreleased_entries(self): + problems = check_release("0.1.0", CHANGELOG.replace("0.1.0", "0.0.1"), "0.1.0", True) + assert len(problems) == 3 + + def test_first_release_may_restart_numbering(self): + released = release_changelog(CHANGELOG, "0.1.1", "2026-02-01") + assert check_release("0.1.1", released, "1.2.0", base_has_changelog=False) == [] + + +@pytest.mark.unit +def test_app_version_comes_from_pyproject(): + with PYPROJECT.open("rb") as f: + assert get_version() == tomllib.load(f)["project"]["version"] + assert f"Version {get_version()}" in str(shell_footer()) + + +@pytest.mark.unit +def test_repo_changelog_has_current_version(): + assert extract_section(CHANGELOG_PATH.read_text(), get_version()) is not None diff --git a/utils/version.py b/utils/version.py new file mode 100644 index 0000000..dc380d5 --- /dev/null +++ b/utils/version.py @@ -0,0 +1,13 @@ +"""Single source of truth for the app version: `[project].version` in pyproject.toml.""" + +import tomllib +from functools import cache +from pathlib import Path + +PYPROJECT = Path(__file__).resolve().parent.parent / "pyproject.toml" + + +@cache +def get_version() -> str: + with PYPROJECT.open("rb") as f: + return tomllib.load(f)["project"]["version"]