Debian Codegraph @

tasks/release.py

raw
1 """Handles creating a release."""
2
3 from __future__ import annotations
4
5 from pathlib import Path
6 from subprocess import call, check_call
7
8 from git import Commit, Remote, Repo, TagReference
9 from packaging.version import Version
10
11
12 ROOT_SRC_DIR = Path(__file__).resolve().parents[1]
13 VERSION_FILE = ROOT_SRC_DIR / 'src' / 'build' / '__init__.py'
14 CHANGELOG_FILE = ROOT_SRC_DIR / 'CHANGELOG.rst'
15
16
17 def main(version_str: str, *, push: bool) -> None:
18 repo = Repo(str(ROOT_SRC_DIR))
19 if repo.is_dirty():
20 msg = 'Current repository is dirty. Please commit any changes and try again.'
21 raise RuntimeError(msg)
22 remote = get_remote(repo)
23 remote.fetch()
24 version = resolve_version(version_str, repo)
25 print(f'releasing {version}')
26 release_commit = create_release_commit(repo, version)
27 tag = tag_release_commit(release_commit, repo, version)
28 if push:
29 print('push release commit')
30 repo.git.push(remote.name, 'HEAD:main')
31 print('push release tag')
32 repo.git.push(remote.name, tag)
33 print('All done! ✨ 🍰 ✨')
34
35
36 def resolve_version(version_str: str, repo: Repo) -> Version:
37 if version_str not in {'auto', 'major', 'minor', 'patch'}:
38 return Version(version_str)
39 latest_tag = repo.git.describe('--tags', '--abbrev=0')
40 latest_tag = latest_tag.lstrip('v')
41 parts = [int(x) for x in latest_tag.split('.')]
42 match version_str:
43 case 'major':
44 parts = [parts[0] + 1, 0, 0]
45 case 'minor':
46 parts = [parts[0], parts[1] + 1, 0]
47 case 'patch' | 'auto':
48 parts[2] += 1
49 return Version('.'.join(str(p) for p in parts))
50
51
52 def get_remote(repo: Repo) -> Remote:
53 upstream_remote = 'pypa/build'
54 urls = set()
55 for remote in repo.remotes:
56 for url in remote.urls:
57 if url.rstrip('.git').endswith(upstream_remote):
58 return remote
59 urls.add(url)
60 msg = f'could not find {upstream_remote} remote, has {urls}'
61 raise RuntimeError(msg)
62
63
64 def create_release_commit(repo: Repo, version: Version) -> Commit:
65 print('update version in __init__.py')
66 update_version_file(version)
67 print('build changelog from fragments with towncrier')
68 check_call(['towncrier', 'build', '--yes', '--version', version.public], cwd=str(ROOT_SRC_DIR)) # noqa: S603
69 call(['pre-commit', 'run', '--all-files'], cwd=str(ROOT_SRC_DIR))
70 call(['pre-commit', 'run', '--all-files'], cwd=str(ROOT_SRC_DIR))
71 repo.git.add('src/build/__init__.py', 'CHANGELOG.rst', 'docs/changelog/*')
72 check_call(['pre-commit', 'run', '--all-files', '--show-diff-on-failure'], cwd=str(ROOT_SRC_DIR))
73 if repo.is_dirty(index=False, working_tree=True, untracked_files=False):
74 msg = 'Pre-commit hooks modified files after final run. This indicates an environment inconsistency.'
75 raise RuntimeError(msg)
76 return repo.index.commit(f'chore: prepare for {version}')
77
78
79 def update_version_file(version: Version) -> None:
80 content = VERSION_FILE.read_text(encoding='utf-8')
81 lines = content.splitlines(keepends=True)
82 for i, line in enumerate(lines):
83 if line.startswith('__version__ = '):
84 lines[i] = f"__version__ = '{version}'\n"
85 break
86 VERSION_FILE.write_text(''.join(lines), encoding='utf-8')
87
88
89 def tag_release_commit(release_commit: Commit, repo: Repo, version: Version) -> TagReference:
90 print('create annotated tag')
91 tag_name = str(version)
92 existing_tags = [x.name for x in repo.tags]
93 if tag_name in existing_tags:
94 print(f'delete existing tag {tag_name}')
95 repo.delete_tag(tag_name)
96 changelog_content = extract_changelog_for_version(version)
97 tag_message = f'build {version}\n\n{changelog_content}'
98 print(f'creating tag {tag_name}')
99 repo.git.tag('-a', tag_name, '-m', tag_message, str(release_commit))
100 print('✓ Created annotated tag')
101 return repo.tags[tag_name]
102
103
104 def extract_changelog_for_version(version: Version) -> str:
105 content = CHANGELOG_FILE.read_text(encoding='utf-8')
106 lines = content.splitlines()
107 in_version_section = False
108 version_header = str(version)
109 changelog_lines = []
110 for line in lines:
111 if version_header in line and '*' in line:
112 in_version_section = True
113 continue
114 if in_version_section:
115 if line.startswith('**') and '*' * 10 in line:
116 break
117 if line.strip():
118 cleaned = line.replace(':pr:', 'PR #').replace(':issue:', 'issue #')
119 cleaned = cleaned.replace('``', '`')
120 changelog_lines.append(cleaned)
121 return '\n'.join(changelog_lines).strip()
122
123
124 if __name__ == '__main__':
125 from argparse import ArgumentParser
126
127 parser = ArgumentParser(prog='release')
128 parser.add_argument('--version', default='auto')
129 parser.add_argument('--no-push', action='store_true')
130 options = parser.parse_args()
131 main(options.version, push=not options.no_push)