diff --git a/.github/release-notes.sh b/.github/release-notes.sh index dfda612e0..24014babd 100755 --- a/.github/release-notes.sh +++ b/.github/release-notes.sh @@ -1,52 +1,6 @@ #!/usr/bin/env bash -# Generate a FEATURE-oriented changelog for a release, not a contributor ledger. -# -# Buckets conventional-commit subjects (feat/fix/perf/docs/...) since the -# previous release tag into readable sections. Author names and PR-merge noise -# are intentionally dropped β€” the "Full changelog" compare link at the bottom is -# the exhaustive, per-commit view for anyone who wants it. -# -# Usage: release-notes.sh -# Writes the notes (Markdown) to stdout. Requires full git history + tags -# (checkout with fetch-depth: 0). +# Compatible interface: release-notes.sh X.Y.Z [source-sha] [--allow-direct-merge] +# Optional source pin also accepted as RELEASE_SOURCE_SHA. Requires full history, +# tags, and gh read access for historical release provenance (never moving dev). set -euo pipefail - -VERSION="${1:?usage: release-notes.sh X.Y.Z }" -SHA="${2:?usage: release-notes.sh X.Y.Z }" -REPO="${GITHUB_REPOSITORY:-RayforceDB/rayforce}" - -# Previous-release boundary: the highest semver tag strictly below this release. -# Falls back to the pre-v2 rollup marker, then to the repo root (no boundary). -prev="$(git tag -l 'v[0-9]*.[0-9]*.[0-9]*' --sort=-v:refname | grep -vxF "v$VERSION" | head -1 || true)" -if [ -z "$prev" ] && git rev-parse -q --verify "pre-v2-rollup^{commit}" >/dev/null 2>&1; then - prev="pre-v2-rollup" -fi -range="${prev:+$prev..}$SHA" - -feats=""; fixes=""; perfs=""; docs=""; other="" -while IFS= read -r s; do - [ -n "$s" ] || continue - type="$(printf '%s' "$s" | sed -nE 's/^([a-zA-Z]+)(\([^)]*\))?!?:.*/\1/p')" - desc="$(printf '%s' "$s" | sed -E 's/^[a-zA-Z]+(\([^)]*\))?!?:[[:space:]]*//')" - case "$type" in - feat) feats+="- ${desc}"$'\n';; - fix) fixes+="- ${desc}"$'\n';; - perf) perfs+="- ${desc}"$'\n';; - docs) docs+="- ${desc}"$'\n';; - *) other+="- ${s}"$'\n';; # non-conventional / internal: keep full subject - esac -done < <(git log --no-merges --reverse --pretty=tformat:'%s' "$range") - -emit() { [ -n "$2" ] && printf '### %s\n\n%s\n' "$1" "$2"; return 0; } - -emit "✨ Features" "$feats" -emit "πŸ› Bug fixes" "$fixes" -emit "⚑ Performance" "$perfs" -emit "πŸ“š Documentation" "$docs" -if [ -n "$other" ]; then - printf '
\nπŸ”§ Maintenance & internal\n\n%s\n
\n' "$other" -fi - -if [ -n "$prev" ]; then - printf '\n**Full changelog**: https://github.com/%s/compare/%s...v%s\n' "$REPO" "$prev" "$VERSION" -fi +exec python3 "$(dirname "${BASH_SOURCE[0]}")/release_notes.py" "$@" diff --git a/.github/release_notes.py b/.github/release_notes.py new file mode 100644 index 000000000..56817770a --- /dev/null +++ b/.github/release_notes.py @@ -0,0 +1,237 @@ +#!/usr/bin/env python3 +"""Release subjects from verified source history, independently of artifact history. + +Requires local full history/tags and gh read access. Never fetches a moving branch. +Missing source objects must be fetched explicitly by the caller before retrying. +""" +import argparse +import json +import os +import re +import subprocess +import sys + + +class NotesError(Exception): + pass + + +def run(args): + proc = subprocess.run(args, text=True, capture_output=True) + if proc.returncode: + raise NotesError(f"{' '.join(args)} failed ({proc.returncode}): {proc.stderr.strip()}") + return proc.stdout.strip() + + +def git(*args): + return run(['git', *args]) + + +def version(value): + if not re.fullmatch(r'[0-9]+\.[0-9]+\.[0-9]+', value): + raise NotesError(f'Invalid release version: {value!r}; expected X.Y.Z') + return tuple(map(int, value.split('.'))) + + +def commit(ref): + return git('rev-parse', '--verify', ref + '^{commit}') + + +def immutable(sha): + if not isinstance(sha, str) or not re.fullmatch(r'[0-9a-f]{40}', sha): + raise NotesError(f'Expected immutable full commit SHA, got {sha!r}') + if commit(sha) != sha: + raise NotesError(f'Expected commit SHA, not tag object: {sha}') + return sha + + +def ancestor(old, new): + proc = subprocess.run(['git', 'merge-base', '--is-ancestor', old, new], + text=True, capture_output=True) + if proc.returncode not in (0, 1): + raise NotesError(f'git ancestry check failed: {proc.stderr.strip()}') + return proc.returncode == 0 + + +def same_tree(artifact, source): + if git('rev-parse', artifact + '^{tree}') != git('rev-parse', source + '^{tree}'): + raise NotesError(f'Source tree does not match artifact: {source} vs {artifact}') + + +class GitHub: + def __init__(self, repo): + self.repo = repo + + def api(self, path, optional=False, pages=False): + args = ['gh', 'api', f'repos/{self.repo}/{path}'] + if pages: + args += ['--paginate', '--slurp'] + proc = subprocess.run(args, text=True, capture_output=True) + if optional and proc.returncode and '(HTTP 404)' in proc.stderr: + return None + if proc.returncode: + raise NotesError(f'GitHub lookup {path} failed: {proc.stderr.strip()}') + try: + return json.loads(proc.stdout) + except ValueError as exc: + raise NotesError(f'Invalid GitHub JSON for {path}') from exc + + def body(self, tag): + data = self.api(f'releases/tags/{tag}', optional=True) + if data is None: + return '' + if not isinstance(data, dict) or not isinstance(data.get('body'), (str, type(None))): + raise NotesError(f'Invalid release response for {tag}') + return data.get('body') or '' + + def pulls(self, artifact): + pages = self.api(f'commits/{artifact}/pulls?per_page=100', pages=True) + if not isinstance(pages, list) or any(not isinstance(p, list) for p in pages): + raise NotesError('Invalid paginated PR response') + return [pr for page in pages for pr in page] + + +MARKER = 'release-notes-source-v1' + + +def metadata(body): + # Generated provenance occupies its own HTML-comment line. A commit title + # or documentation mentioning the marker is ordinary release-note prose. + records = [line.strip() for line in body.splitlines() + if line.lstrip().startswith('', records[0]) + if len(records) != 1 or not match: + raise NotesError('Malformed, duplicate or unsupported release source metadata') + try: + data = json.loads(match[1]) + except ValueError as exc: + raise NotesError('Malformed release source metadata JSON') from exc + if not isinstance(data, dict): + raise NotesError('Invalid release source metadata') + return data + +def resolve(api, tag, artifact, pinned=None, body=None, allow_direct_merge=False): + """Metadata is authoritative if present; otherwise bootstrap exact PR evidence.""" + data = metadata(api.body(tag) if body is None else body) + if data is not None: + if data.get('tag') != tag or data.get('artifact') != artifact: + raise NotesError(f'Metadata tag/artifact mismatch for {tag}') + source = immutable(data.get('source')) + if data.get('tree') != git('rev-parse', artifact + '^{tree}'): + raise NotesError(f'Metadata tree mismatch for {tag}') + else: + pulls = api.pulls(artifact) + if any(not isinstance(pr, dict) or not isinstance(pr.get('base'), dict) + or not isinstance(pr.get('head'), dict) for pr in pulls): + raise NotesError('Invalid PR record') + matches = [pr for pr in pulls if pr.get('merged_at') + and pr.get('merge_commit_sha') == artifact + and pr.get('base', {}).get('ref') == 'master' + and pr.get('title') == tag] + if len(matches) > 1: + raise NotesError(f'Ambiguous merged release PRs for {tag}') + if matches: + source = immutable(matches[0].get('head', {}).get('sha')) + else: + # A normal, non-merge source commit is self-provenancing. A release + # wrapper needs exact provenance. An explicit manual selection can + # identify a non-wrapper merge as its own complete source history. + subject = git('show', '-s', '--format=%s', artifact) + parents = git('show', '-s', '--format=%P', artifact).split() + if re.match(r'^v?[0-9]+\.[0-9]+\.[0-9]+(?:\s|$)', subject) or (len(parents) > 1 and not allow_direct_merge): + raise NotesError(f'Missing release source provenance for {tag} ({artifact})') + source = artifact + same_tree(artifact, source) + if pinned and immutable(pinned) != source: + raise NotesError(f'Pinned PR source disagrees with provenance for {tag}') + return source + + +def previous(api, requested, artifact, source): + tags = git('tag', '--list').splitlines() + candidates = [t for t in tags if re.fullmatch(r'v[0-9]+\.[0-9]+\.[0-9]+', t) + and version(t[1:]) < version(requested)] + for tag in sorted(candidates, key=lambda t: version(t[1:]), reverse=True): + old = commit('refs/tags/' + tag) + old_source = resolve(api, tag, old) + related = ancestor(old, artifact) or ancestor(old, source) + if ancestor(old_source, source): + return tag, old, old_source + if related: + raise NotesError(f'Previous source {tag} is not an ancestor of current source') + # Root/rollup is only a first-release boundary, not a provenance fallback. + if candidates: + raise NotesError('No compatible previous release source among older version tags') + if 'pre-v2-rollup' in tags: + old = commit('refs/tags/pre-v2-rollup') + if not ancestor(old, source): + raise NotesError('pre-v2-rollup is not a source ancestor') + return 'pre-v2-rollup', old, old + return None, None, None + + +def render(subjects, repo, requested, prev): + buckets = {key: [] for key in ('feat', 'fix', 'perf', 'docs', 'other')} + for subject in subjects: + match = re.match(r'^([a-zA-Z]+)(?:\([^)]*\))?!?:\s*(.*)$', subject) + key = match[1] if match and match[1] in buckets and match[1] != 'other' else 'other' + buckets[key].append('- ' + (match[2] if key != 'other' else subject)) + parts = [] + for key, title in [('feat', '✨ Features'), ('fix', 'πŸ› Bug fixes'), + ('perf', '⚑ Performance'), ('docs', 'πŸ“š Documentation')]: + if buckets[key]: + parts.append(f'### {title}\n\n' + '\n'.join(buckets[key]) + '\n') + if buckets['other']: + parts.append('
\nπŸ”§ Maintenance & internal\n\n' + + '\n'.join(buckets['other']) + '\n\n
') + if prev: + parts.append(f'**Full changelog**: https://github.com/{repo}/compare/{prev}...v{requested}') + return '\n\n'.join(parts) + + +def generate(requested, target, pinned=None, repo='RayforceDB/rayforce', api=None, + allow_direct_merge=False): + version(requested) + artifact = immutable(target) + api = api or GitHub(repo) + tag = 'v' + requested + tags = git('tag', '--list').splitlines() + if tag in tags and commit('refs/tags/' + tag) != artifact: + raise NotesError(f'Artifact target disagrees with existing tag {tag}') + source = resolve(api, tag, artifact, pinned, body='', + allow_direct_merge=allow_direct_merge) + prev, old, old_source = previous(api, requested, artifact, source) + args = ['log', '--no-merges', '--reverse', '--format=%s', source] + if old: + args += ['--not', old_source, old] + subjects = git(*args).splitlines() + if not subjects or all(re.match(r'^v?[0-9]+\.[0-9]+\.[0-9]+(?:\s|$)', s) for s in subjects): + raise NotesError('Empty or wrapper-only release source delta; explicit release decision required') + data = dict(tag=tag, artifact=artifact, source=source, + tree=git('rev-parse', artifact + '^{tree}')) + return (render(subjects, repo, requested, prev) + '\n\n\n') + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('version') + parser.add_argument('artifact_sha') + parser.add_argument('source_sha', nargs='?', default=os.getenv('RELEASE_SOURCE_SHA') or None) + parser.add_argument('--allow-direct-merge', action='store_true', + help='manual dispatch: the selected non-wrapper merge is the source') + args = parser.parse_args() + try: + print(generate(args.version, args.artifact_sha, args.source_sha, + os.getenv('GITHUB_REPOSITORY', 'RayforceDB/rayforce'), + allow_direct_merge=args.allow_direct_merge), end='') + except (NotesError, OSError) as exc: + print(f'release notes: {exc}', file=sys.stderr) + return 1 + return 0 + + +if __name__ == '__main__': + sys.exit(main()) diff --git a/.github/test_release_notes.py b/.github/test_release_notes.py new file mode 100644 index 000000000..57145dc2b --- /dev/null +++ b/.github/test_release_notes.py @@ -0,0 +1,366 @@ +"""Offline regressions: real disposable Git graphs, fixture-only GitHub access.""" +import importlib.util +import json +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +SPEC = importlib.util.spec_from_file_location('release_notes', Path(__file__).with_name('release_notes.py')) +notes = importlib.util.module_from_spec(SPEC) +SPEC.loader.exec_module(notes) + + +class API: + def __init__(self): + self.prs = {} + self.bodies = {} + + def body(self, tag): + return self.bodies.get(tag, '') + + def pulls(self, sha): + return self.prs.get(sha, []) + + def release(self, tag, artifact, source, **changes): + pr = dict(merged_at='2026-01-01', title=tag, merge_commit_sha=artifact, + base={'ref': 'master'}, head={'sha': source}) + pr.update(changes) + self.prs.setdefault(artifact, []).append(pr) + + +class GraphTests(unittest.TestCase): + def setUp(self): + self.tmp = tempfile.TemporaryDirectory(prefix='release-notes-test-') + self.cwd = os.getcwd() + os.chdir(self.tmp.name) + self.api = API() + self.git('init', '-q', '-b', 'master') + self.git('config', 'user.email', 'offline@example.invalid') + self.git('config', 'user.name', 'Offline Test') + self.root = self.add('chore: root') + + def tearDown(self): + os.chdir(self.cwd) + self.tmp.cleanup() + + def git(self, *args): + return subprocess.check_output(['git', *args], text=True, stderr=subprocess.PIPE).strip() + + def add(self, subject, content=None): + path = Path('data') + path.write_text((path.read_text() if path.exists() else '') + (content or subject) + '\n') + self.git('add', 'data') + self.git('commit', '-q', '-m', subject) + return self.git('rev-parse', 'HEAD') + + def generate(self, version, sha, pin=None): + return notes.generate(version, sha, pin, api=self.api) + + def squash_pair(self): + self.git('checkout', '-q', '-b', 'dev') + old_source = self.add('feat: already released') + self.git('checkout', '-q', 'master') + self.git('merge', '--squash', 'dev') + self.git('commit', '-q', '-m', 'v2.11.5 (#791)') + old = self.git('rev-parse', 'HEAD') + self.git('tag', '-a', 'v2.11.5', '-m', 'annotated') + self.api.release('v2.11.5', old, old_source) + self.git('checkout', '-q', 'dev') + self.git('merge', '-q', 'master', '-m', 'reconcile released master') + self.add('feat(query): new query') + self.add('fix!: reclaim remap') + self.add('perf: faster') + source = self.add('docs: guide') + self.git('checkout', '-q', 'master') + self.git('merge', '--squash', 'dev') + self.git('commit', '-q', '-m', 'v3.0.1 (#984)') + artifact = self.git('rev-parse', 'HEAD') + self.api.release('v3.0.1', artifact, source) + return old, old_source, artifact, source + + def test_linear_numeric_future_and_unrelated(self): + self.git('tag', 'v2.9.0') + self.add('fix: prior') + self.git('tag', 'v2.10.0') + target = self.add('feat: desired') + self.add('fix: future') + self.git('tag', 'v9.0.0') + self.git('checkout', '-q', '--orphan', 'unrelated') + unrelated = self.add('feat: unrelated') + self.git('tag', 'v2.10.9', unrelated) + body = self.generate('2.11.0', target) + self.assertIn('v2.10.0...v2.11.0', body) + self.assertIn('- desired', body) + self.assertNotIn('- prior', body) + self.assertNotIn('- future', body) + self.assertNotIn('- unrelated', body) + + def test_future_version_on_ancestor_is_not_previous(self): + self.git('tag', 'v9.0.0', self.root) + self.add('fix: previous change') + self.git('tag', 'v2.10.0') + target = self.add('feat: desired only') + body = self.generate('2.11.0', target) + self.assertIn('v2.10.0...v2.11.0', body) + self.assertNotIn('v9.0.0', body) + self.assertNotIn('previous change', body) + + def test_squash_reconciliation_pin_metadata_roundtrip(self): + old, old_source, artifact, source = self.squash_pair() + body = self.generate('3.0.1', artifact, source) + for title in ['✨ Features', 'πŸ› Bug fixes', '⚑ Performance', 'πŸ“š Documentation']: + self.assertIn(title, body) + for absent in ['already released', '(#791)', '(#984)', 'reconcile released master']: + self.assertNotIn(absent, body) + self.assertEqual(body.count('- new query'), 1) + self.assertEqual(body.count(notes.MARKER), 1) + self.assertEqual(body, self.generate('3.0.1', artifact, source)) + data = notes.metadata(body) + self.assertEqual(data['source'], source) + self.assertEqual(data['artifact'], artifact) + self.git('tag', 'v3.0.1', artifact) + self.api.bodies['v3.0.1'] = body + del self.api.prs[artifact] + self.git('checkout', '-q', 'dev') + target = self.add('fix: next only') + next_body = self.generate('3.0.2', target) + self.assertIn('- next only', next_body) + self.assertNotIn('- new query', next_body) + self.assertFalse(notes.ancestor(artifact, target)) + self.assertTrue(notes.ancestor(source, target)) + + def test_merge_release_and_moving_dev(self): + self.git('tag', 'v1.0.0') + self.git('checkout', '-q', '-b', 'dev') + source = self.add('feat: merged change') + self.git('checkout', '-q', 'master') + self.git('merge', '--no-ff', '-q', 'dev', '-m', 'v1.1.0') + artifact = self.git('rev-parse', 'HEAD') + self.api.release('v1.1.0', artifact, source) + self.git('checkout', '-q', 'dev') + self.add('fix: not released') + body = self.generate('1.1.0', artifact, source) + self.assertIn('- merged change', body) + self.assertNotIn('not released', body) + self.assertNotIn('chore: root', body) + + def test_explicit_manual_nonwrapper_merge_source(self): + self.git('tag', 'v1.0.0') + self.git('checkout', '-q', '-b', 'dev') + self.add('feat: manual merged source') + self.git('checkout', '-q', 'master') + self.git('merge', '--no-ff', '-q', 'dev', '-m', 'Merge dev changes') + artifact = self.git('rev-parse', 'HEAD') + with self.assertRaisesRegex(notes.NotesError, 'Missing release source'): + self.generate('1.1.0', artifact) + body = notes.generate('1.1.0', artifact, api=self.api, allow_direct_merge=True) + self.assertIn('- manual merged source', body) + self.assertEqual(notes.metadata(body)['source'], artifact) + self.assertNotIn('chore: root', body) + + def test_manual_mode_cannot_relabel_release_wrapper(self): + _, _, artifact, _ = self.squash_pair() + self.api.prs[artifact] = [] + with self.assertRaisesRegex(notes.NotesError, 'Missing release source'): + notes.generate('3.0.1', artifact, api=self.api, allow_direct_merge=True) + + def test_missing_and_ambiguous_provenance(self): + _, _, artifact, source = self.squash_pair() + pr = self.api.prs[artifact][0] + self.api.prs[artifact] = [] + with self.assertRaisesRegex(notes.NotesError, 'Missing release source'): + self.generate('3.0.1', artifact) + self.api.prs[artifact] = [pr, pr] + with self.assertRaisesRegex(notes.NotesError, 'Ambiguous'): + self.generate('3.0.1', artifact) + self.api.prs[artifact] = [dict(pr, title='v3.0.2')] + with self.assertRaisesRegex(notes.NotesError, 'Missing release source'): + self.generate('3.0.1', artifact, source) + + def test_missing_previous_provenance_never_falls_back_to_root(self): + old, _, artifact, _ = self.squash_pair() + self.api.prs[old] = [] + with self.assertRaisesRegex(notes.NotesError, 'Missing release source'): + self.generate('3.0.1', artifact) + + def test_tree_missing_object_and_pin_mismatch(self): + _, old_source, artifact, source = self.squash_pair() + self.api.prs[artifact][0]['head']['sha'] = old_source + with self.assertRaisesRegex(notes.NotesError, 'tree does not match'): + self.generate('3.0.1', artifact) + self.api.prs[artifact][0]['head']['sha'] = 'f' * 40 + with self.assertRaisesRegex(notes.NotesError, 'failed'): + self.generate('3.0.1', artifact) + self.api.prs[artifact][0]['head']['sha'] = source + with self.assertRaisesRegex(notes.NotesError, 'Pinned PR source'): + self.generate('3.0.1', artifact, old_source) + + def test_wrong_base_unmerged_or_merge_sha(self): + _, _, artifact, _ = self.squash_pair() + pr = self.api.prs[artifact][0] + for changes in [dict(base={'ref': 'dev'}), dict(merged_at=None), + dict(merge_commit_sha=self.root)]: + self.api.prs[artifact] = [dict(pr, **changes)] + with self.assertRaisesRegex(notes.NotesError, 'Missing release source'): + self.generate('3.0.1', artifact) + + def test_metadata_rejects_corruption(self): + _, _, artifact, source = self.squash_pair() + body = self.generate('3.0.1', artifact) + valid = notes.metadata(body) + for field, value in [('artifact', self.root), ('source', self.root), + ('tree', 'f' * 40), ('tag', 'v9.0.0')]: + corrupt = dict(valid, **{field: value}) + self.api.bodies['v3.0.1'] = '' + with self.assertRaises(notes.NotesError): + notes.resolve(self.api, 'v3.0.1', artifact) + for malformed in [body + body, '', + '']: + with self.assertRaises(notes.NotesError): + notes.metadata(malformed) + self.api.bodies['v3.0.1'] = body + self.assertEqual(notes.resolve(self.api, 'v3.0.1', artifact), source) + + def test_invalid_pr_response_fails_clearly(self): + self.api.prs[self.root] = [{'base': None, 'head': {}}] + with self.assertRaisesRegex(notes.NotesError, 'Invalid PR record'): + self.generate('1.0.0', self.root) + + def test_wrapper_only_source_delta_fails(self): + self.git('tag', 'v1.0.0') + source = self.add('v1.1.0 (#2)') + self.api.release('v1.1.0', source, source) + with self.assertRaisesRegex(notes.NotesError, 'wrapper-only'): + self.generate('1.1.0', source) + + def test_divergent_previous_source_fails(self): + old, _, artifact, _ = self.squash_pair() + # Same tree but fabricated independent source history is not ancestry. + tree = self.git('rev-parse', old + '^{tree}') + divergent = self.git('commit-tree', tree, '-m', 'feat: independent') + self.api.prs[old][0]['head']['sha'] = divergent + with self.assertRaisesRegex(notes.NotesError, 'not an ancestor'): + self.generate('3.0.1', artifact) + + def test_first_root_and_rollup(self): + target = self.add('feat: first') + body = self.generate('1.0.0', target) + self.assertIn('chore: root', body) + self.assertIn('Maintenance & internal', body) + self.git('tag', 'pre-v2-rollup', self.root) + body = self.generate('2.0.0', target) + self.assertNotIn('chore: root', body) + self.assertIn('pre-v2-rollup...v2.0.0', body) + + def test_invalid_version_target_tag_and_empty(self): + for value in ['v1.0.0', '1.2', '1.0.0-rc1', '1.0.0\n', '-1.0.0']: + with self.assertRaises(notes.NotesError): + self.generate(value, self.root) + with self.assertRaisesRegex(notes.NotesError, 'immutable'): + self.generate('1.0.0', 'master') + self.git('tag', 'v1.0.0') + target = self.add('feat: next') + with self.assertRaisesRegex(notes.NotesError, 'existing tag'): + self.generate('1.0.0', target) + with self.assertRaisesRegex(notes.NotesError, 'Empty'): + self.generate('1.0.1', self.root) + + def test_git_log_failure_is_not_hidden(self): + actual = notes.git + + def fail(*args): + if args[0] == 'log': + raise notes.NotesError('git log failed (128)') + return actual(*args) + + with patch.object(notes, 'git', side_effect=fail): + with self.assertRaisesRegex(notes.NotesError, 'git log failed'): + self.generate('1.0.0', self.root) + + def test_cli_wrapper_only_uses_stub_gh(self): + script = Path(__file__).with_name('release-notes.sh').resolve() + bin_dir = Path('bin') + bin_dir.mkdir() + stub = bin_dir / 'gh' + stub.write_text('#!/usr/bin/python3\nimport json,sys\n' + 'assert "commits/" in sys.argv[2], sys.argv\n' + 'print(json.dumps([[]]))\n') + stub.chmod(0o755) + env = dict(os.environ, PATH=str(bin_dir.resolve()) + ':' + os.environ['PATH']) + proc = subprocess.run(['bash', str(script), '1.0.0', self.root], + env=env, text=True, capture_output=True) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn('chore: root', proc.stdout) + proc = subprocess.run(['bash', str(script), 'bad', self.root], + env=env, text=True, capture_output=True) + self.assertEqual(proc.returncode, 1) + self.assertIn('Invalid release version', proc.stderr) + self.git('checkout', '-q', '-b', 'dev') + self.add('feat: manual CLI merge') + self.git('checkout', '-q', 'master') + self.git('merge', '--no-ff', '-q', 'dev', '-m', 'Merge dev changes') + artifact = self.git('rev-parse', 'HEAD') + proc = subprocess.run(['bash', str(script), '1.0.0', artifact, '--allow-direct-merge'], + env=env, text=True, capture_output=True) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertIn('- manual CLI merge', proc.stdout) + self.assertEqual(notes.metadata(proc.stdout)['source'], artifact) + # Exercise a real nonzero git-log subprocess through the Bash entrypoint. + git_stub = bin_dir / 'git' + git_stub.write_text('#!/bin/sh\nif [ "$1" = log ]; then echo forced-log-failure >&2; exit 128; fi\n' + 'exec /usr/bin/git "$@"\n') + git_stub.chmod(0o755) + proc = subprocess.run(['bash', str(script), '1.0.0', self.root], + env=env, text=True, capture_output=True) + self.assertEqual(proc.returncode, 1) + self.assertEqual(proc.stdout, '') + self.assertIn('forced-log-failure', proc.stderr) + + +class AdapterTests(unittest.TestCase): + def test_announcement_hides_internal_and_provenance(self): + body = notes.render(['feat: visible', 'chore: internal'], 'offline/repo', '1.0.0', None) + body += '\n\n' + args = ['sed', '-e', '/
/,/<\\/details>/d', + '-e', '/^\n' + self.assertEqual(notes.metadata(body), data) + self.assertIsNone(notes.metadata(prose)) + with self.assertRaises(notes.NotesError): + notes.metadata('