rn-forge-devops 0.3.1__py3-none-any.whl

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,31 @@
1
+ """CI and release automation: the platform- and stack-neutral core."""
2
+
3
+ from rn_forge.devops.ci import (
4
+ UNSCOPED,
5
+ Package,
6
+ Smoke,
7
+ Workspace,
8
+ changed_files,
9
+ normalize,
10
+ plan,
11
+ releasable,
12
+ release_order,
13
+ released,
14
+ requirement_name,
15
+ select,
16
+ )
17
+
18
+ __all__ = [
19
+ "UNSCOPED",
20
+ "Package",
21
+ "Smoke",
22
+ "Workspace",
23
+ "changed_files",
24
+ "normalize",
25
+ "plan",
26
+ "releasable",
27
+ "release_order",
28
+ "released",
29
+ "requirement_name",
30
+ "select",
31
+ ]
rn_forge/devops/ci.py ADDED
@@ -0,0 +1,291 @@
1
+ """The CI core: the member graph, change selection, check matrices and release gating.
2
+
3
+ The core knows neither a CI platform nor a package manager. An adapter fills a
4
+ `Workspace` from the repository's own manifests and formats the `plan` outputs
5
+ for its platform.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import re
11
+ import shlex
12
+ import subprocess
13
+ import sys
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+
17
+ # Changes under these paths select no package.
18
+ UNSCOPED = ("docs/",)
19
+
20
+ # A revision name never starts with `-`, so it cannot be read as a git option.
21
+ REVISION = r"[A-Za-z0-9_][A-Za-z0-9_./@-]*"
22
+
23
+
24
+ def normalize(name: str) -> str:
25
+ """Return `name` in its canonical form: lowercase, runs of `-_.` as one `-`."""
26
+ return re.sub(r"[-_.]+", "-", name).lower()
27
+
28
+
29
+ def requirement_name(requirement: str) -> str:
30
+ """Return the normalized package name of a requirement string."""
31
+ return normalize(re.split(r"[\s\[<>=!~;@]", requirement.strip(), maxsplit=1)[0])
32
+
33
+
34
+ @dataclass
35
+ class Smoke:
36
+ """A package's smoke-test declaration.
37
+
38
+ Attributes:
39
+ modules: Modules imported in every smoke run.
40
+ extras: Modules imported for each extra, keyed by extra name.
41
+ setup: A script, relative to the package directory, run before the imports.
42
+ """
43
+
44
+ modules: list[str] = field(default_factory=list[str])
45
+ extras: dict[str, list[str]] = field(default_factory=dict[str, list[str]])
46
+ setup: str = ""
47
+
48
+
49
+ @dataclass
50
+ class Package:
51
+ """A workspace member.
52
+
53
+ Attributes:
54
+ name: Normalized project name.
55
+ dir: Directory relative to the repository root, with `/` separators.
56
+ module: Import name of the package.
57
+ requires: Names of the workspace members this package requires, through
58
+ dependencies, optional dependencies or dependency groups.
59
+ release_requires: Names of the workspace members this package requires
60
+ through dependencies or optional dependencies only. Release order and
61
+ release gating follow these.
62
+ postgres_env: Variable that receives a PostgreSQL DSN, or `None` when the
63
+ package needs no database run.
64
+ redis_env: Variable that receives a Redis URL, or `None` when the package
65
+ needs no Redis run.
66
+ smoke: The smoke-test declaration, or `None` when the package declares none.
67
+ adapters: Names of the package's adapters, or `None` when it declares none.
68
+ """
69
+
70
+ name: str
71
+ dir: str
72
+ module: str
73
+ requires: set[str] = field(default_factory=lambda: set[str]())
74
+ release_requires: set[str] = field(default_factory=lambda: set[str]())
75
+ postgres_env: str | None = None
76
+ redis_env: str | None = None
77
+ smoke: Smoke | None = None
78
+ adapters: list[str] | None = None
79
+
80
+ def checks(self) -> list[dict[str, str]]:
81
+ """Every check that must pass before this package may be released.
82
+
83
+ The empty-extra smoke check is listed whether or not `smoke` is set.
84
+ """
85
+ checks = [{"kind": "verify", "marker": f"{self.name}.verify"}]
86
+ if self.postgres_env is not None:
87
+ checks.append({"kind": "postgres", "marker": f"{self.name}.postgres"})
88
+ if self.redis_env is not None:
89
+ checks.append({"kind": "redis", "marker": f"{self.name}.redis"})
90
+ checks.append({"kind": "smoke", "extra": "", "marker": f"{self.name}.smoke"})
91
+ if self.smoke is not None:
92
+ checks += [
93
+ {
94
+ "kind": "smoke",
95
+ "extra": extra,
96
+ "marker": f"{self.name}.smoke-{extra}",
97
+ }
98
+ for extra in self.smoke.extras
99
+ ]
100
+ return checks
101
+
102
+
103
+ @dataclass
104
+ class Workspace:
105
+ """A repository root, its members and its workspace-wide CI settings.
106
+
107
+ Attributes:
108
+ root: The repository root.
109
+ packages: The members, keyed by normalized name.
110
+ pytest_args: Arguments added to every package's pytest run.
111
+ suites: Workspace-wide pytest runs, keyed by suite name.
112
+ """
113
+
114
+ root: Path
115
+ packages: dict[str, Package]
116
+ pytest_args: list[str] = field(default_factory=list[str])
117
+ suites: dict[str, list[str]] = field(default_factory=dict[str, list[str]])
118
+
119
+
120
+ def release_order(packages: dict[str, Package], names: set[str]) -> list[str]:
121
+ """Return `names` with every package after its release requirements.
122
+
123
+ Raises:
124
+ ValueError: When the release requirements of `names` form a cycle.
125
+ """
126
+ order: list[str] = []
127
+ pending = sorted(names)
128
+ while pending:
129
+ ready = [
130
+ n
131
+ for n in pending
132
+ if not (packages[n].release_requires & names) - set(order)
133
+ ]
134
+ if not ready:
135
+ raise ValueError(f"release requirements form a cycle among {pending}")
136
+ order += ready
137
+ pending = [n for n in pending if n not in ready]
138
+ return order
139
+
140
+
141
+ def changed_files(root: Path, base: str) -> list[str]:
142
+ """Return the paths changed between `base` and `HEAD`.
143
+
144
+ Raises:
145
+ ValueError: When `base` is not a plain revision name.
146
+ """
147
+ if not re.fullmatch(REVISION, base):
148
+ raise ValueError(f"invalid base {base!r}")
149
+ out = subprocess.run( # noqa: S603 # fixed argv, no shell
150
+ ["git", "diff", "--name-only", "--end-of-options", f"{base}...HEAD"], # noqa: S607 # tool resolved from PATH
151
+ cwd=root,
152
+ check=True,
153
+ capture_output=True,
154
+ text=True,
155
+ ).stdout
156
+ return out.splitlines()
157
+
158
+
159
+ def select(workspace: Workspace, base: str) -> set[str]:
160
+ """Return the packages with changed files, plus every package that depends on one.
161
+
162
+ An empty, invalid or non-ancestor base, or a change outside every package and
163
+ `UNSCOPED`, selects all. A base is invalid unless it matches `REVISION`.
164
+ """
165
+ packages, root = workspace.packages, workspace.root
166
+ if not base:
167
+ return set(packages)
168
+ if not re.fullmatch(REVISION, base) or (
169
+ subprocess.run( # noqa: S603 # fixed argv, no shell
170
+ ["git", "cat-file", "-e", "--end-of-options", f"{base}^{{commit}}"], # noqa: S607 # tool resolved from PATH
171
+ check=False,
172
+ cwd=root,
173
+ stdout=subprocess.DEVNULL,
174
+ stderr=subprocess.DEVNULL,
175
+ ).returncode
176
+ or subprocess.run( # noqa: S603 # fixed argv, no shell
177
+ ["git", "merge-base", "--is-ancestor", "--end-of-options", base, "HEAD"], # noqa: S607 # tool resolved from PATH
178
+ check=False,
179
+ cwd=root,
180
+ stdout=subprocess.DEVNULL,
181
+ stderr=subprocess.DEVNULL,
182
+ ).returncode
183
+ ):
184
+ print(
185
+ f"base {base} is not a commit or an ancestor of HEAD; selecting all packages",
186
+ file=sys.stderr,
187
+ )
188
+ return set(packages)
189
+ selected: set[str] = set()
190
+ for file in changed_files(root, base):
191
+ owner = next(
192
+ (p.name for p in packages.values() if file.startswith(f"{p.dir}/")), None
193
+ )
194
+ if owner:
195
+ selected.add(owner)
196
+ elif not file.startswith(UNSCOPED):
197
+ return set(packages)
198
+ grew = True
199
+ while grew:
200
+ grew = False
201
+ for package in packages.values():
202
+ if package.name not in selected and package.requires & selected:
203
+ selected.add(package.name)
204
+ grew = True
205
+ return selected
206
+
207
+
208
+ def plan(workspace: Workspace, base: str) -> dict[str, object]:
209
+ """Return every job's matrix and package list for a run against `base`.
210
+
211
+ Command-line values are shell-quoted strings. The keys are `release-order`,
212
+ `packages`, `postgres`, `redis`, `smoke`, `suites`, `pytest-args`, `cov-args`,
213
+ `test-paths`, `sonar-sources`, `sonar-tests`, `sonar` and `docs`.
214
+ """
215
+ packages, root = workspace.packages, workspace.root
216
+ order = release_order(packages, select(workspace, base))
217
+ chosen = [packages[n] for n in order]
218
+ everything = [packages[n] for n in release_order(packages, set(packages))]
219
+ return {
220
+ "release-order": order,
221
+ "packages": [{"name": p.name, "dir": p.dir} for p in chosen],
222
+ "postgres": [
223
+ {"name": p.name, "dir": p.dir, "env": p.postgres_env}
224
+ for p in chosen
225
+ if p.postgres_env is not None
226
+ ],
227
+ "redis": [
228
+ {"name": p.name, "dir": p.dir, "env": p.redis_env}
229
+ for p in chosen
230
+ if p.redis_env is not None
231
+ ],
232
+ "smoke": [
233
+ {"name": p.name, "extra": c["extra"], "marker": c["marker"]}
234
+ for p in chosen
235
+ for c in p.checks()
236
+ if c["kind"] == "smoke"
237
+ ],
238
+ "suites": [
239
+ {"name": name, "args": shlex.join(args)}
240
+ for name, args in workspace.suites.items()
241
+ ],
242
+ "pytest-args": shlex.join(workspace.pytest_args),
243
+ "cov-args": shlex.join(f"--cov={p.module}" for p in everything),
244
+ "test-paths": shlex.join(p.dir for p in everything),
245
+ "sonar-sources": ",".join(f"{p.dir}/src" for p in everything),
246
+ "sonar-tests": ",".join(
247
+ f"{p.dir}/tests" for p in everything if (root / p.dir / "tests").is_dir()
248
+ ),
249
+ "sonar": (root / "sonar-project.properties").is_file(),
250
+ "docs": (root / "mkdocs.yml").is_file(),
251
+ }
252
+
253
+
254
+ def releasable(
255
+ packages: dict[str, Package], ok_dir: Path, names: list[str]
256
+ ) -> tuple[list[str], list[str]]:
257
+ """Return the packages of `names` that may be released, then those that may not.
258
+
259
+ A package may be released when every check of it left a marker file in
260
+ `ok_dir` and its release requirements among `names` may be released too. Both lists
261
+ are in release order.
262
+ """
263
+ selected = {normalize(n) for n in names}
264
+ passed: set[str] = set()
265
+ blocked: list[str] = []
266
+ for name in release_order(packages, selected):
267
+ package = packages[name]
268
+ checks_ok = all((ok_dir / c["marker"]).exists() for c in package.checks())
269
+ if checks_ok and (package.release_requires & selected) <= passed:
270
+ passed.add(name)
271
+ else:
272
+ blocked.append(name)
273
+ return [n for n in release_order(packages, selected) if n in passed], blocked
274
+
275
+
276
+ def released(workspace: Workspace) -> list[tuple[str, str, str, str]]:
277
+ """Return `(name, dir, module, version)` for each `<name>-v<version>` tag at `HEAD`."""
278
+ tags = subprocess.run(
279
+ ["git", "tag", "--points-at", "HEAD"], # noqa: S607 # tool resolved from PATH
280
+ cwd=workspace.root,
281
+ check=True,
282
+ capture_output=True,
283
+ text=True,
284
+ ).stdout.split()
285
+ found: list[tuple[str, str, str, str]] = []
286
+ for tag in tags:
287
+ name, _, version = tag.rpartition("-v")
288
+ if name in workspace.packages:
289
+ package = workspace.packages[name]
290
+ found.append((name, package.dir, package.module, version))
291
+ return found
rn_forge/devops/cli.py ADDED
@@ -0,0 +1,190 @@
1
+ """The `rn-forge-devops` console script."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from rn_forge.devops import ci, github, index, notes, releases, requirements, uv
10
+
11
+
12
+ def _parser() -> argparse.ArgumentParser:
13
+ parser = argparse.ArgumentParser(
14
+ prog="rn-forge-devops",
15
+ description="Plan and run a workspace's CI pipeline from its own manifests.",
16
+ )
17
+ commands = parser.add_subparsers(dest="command", required=True)
18
+ plan = commands.add_parser("plan", help="print `$GITHUB_OUTPUT` lines for the run")
19
+ plan.add_argument("base", nargs="?", default="", metavar="BASE")
20
+ releasable = commands.add_parser(
21
+ "releasable", help="print the NAMEs whose checks all passed"
22
+ )
23
+ releasable.add_argument("ok_dir", metavar="OK_DIR")
24
+ releasable.add_argument("names", nargs="*", metavar="NAME")
25
+ commands.add_parser(
26
+ "released", help="print `name dir module version` per tag at HEAD"
27
+ )
28
+ smoke = commands.add_parser(
29
+ "smoke", help="install one extra from built wheels and import it"
30
+ )
31
+ smoke.add_argument("package", metavar="PACKAGE")
32
+ smoke.add_argument("extra", nargs="?", default="", metavar="EXTRA")
33
+ commands.add_parser(
34
+ "adapters", help="check each declared adapter has a module and an extra"
35
+ )
36
+ commands.add_parser(
37
+ "requirements", help="check internal requirements are version ranges"
38
+ )
39
+ commands.add_parser(
40
+ "sonar-target",
41
+ help="print the `$GITHUB_OUTPUT` line with the Sonar branch argument",
42
+ )
43
+ index_command = commands.add_parser(
44
+ "index", help="write a PEP 503 simple index of a repository's release files"
45
+ )
46
+ index_command.add_argument("--repo", required=True, metavar="OWNER/NAME")
47
+ index_command.add_argument("--out", required=True, metavar="DIR")
48
+ notes_command = commands.add_parser(
49
+ "notes", help="print a changelog version's section"
50
+ )
51
+ notes_command.add_argument("changelog", metavar="CHANGELOG")
52
+ notes_command.add_argument("version", metavar="VERSION")
53
+ umbrella = commands.add_parser(
54
+ "umbrella",
55
+ help="write the pending umbrella release's notes; tags are read from stdin",
56
+ )
57
+ umbrella.add_argument("releases_dir", metavar="RELEASES_DIR")
58
+ umbrella.add_argument("body_file", metavar="BODY_FILE")
59
+ umbrella.add_argument("--site-url", required=True, metavar="URL")
60
+ return parser
61
+
62
+
63
+ def _within_cwd(raw: str) -> Path | None:
64
+ path = Path(raw).resolve()
65
+ return path if path.is_relative_to(Path.cwd().resolve()) else None
66
+
67
+
68
+ def _notes(args: argparse.Namespace) -> int:
69
+ changelog = _within_cwd(args.changelog)
70
+ if changelog is None:
71
+ print(f"{args.changelog} is outside the working directory", file=sys.stderr)
72
+ return 1
73
+ text = changelog.read_text(encoding="utf-8")
74
+ try:
75
+ print(notes.changelog_section(text, args.version))
76
+ except ValueError as error:
77
+ print(error, file=sys.stderr)
78
+ return 1
79
+ return 0
80
+
81
+
82
+ def _umbrella(args: argparse.Namespace) -> int:
83
+ releases_dir = _within_cwd(args.releases_dir)
84
+ if releases_dir is None:
85
+ print(f"{args.releases_dir} is outside the working directory", file=sys.stderr)
86
+ return 1
87
+ body_file = _within_cwd(args.body_file)
88
+ if body_file is None:
89
+ print(f"{args.body_file} is outside the working directory", file=sys.stderr)
90
+ return 1
91
+ # `git ls-remote --tags --refs` lines: `<sha>\trefs/tags/<name>`.
92
+ tags = {
93
+ line.split("refs/tags/", 1)[1].strip()
94
+ for line in sys.stdin.read().splitlines()
95
+ if "refs/tags/" in line
96
+ }
97
+ found = notes.pending_umbrella(releases_dir, tags, args.site_url)
98
+ if found is not None:
99
+ body_file.write_text(found.body, encoding="utf-8")
100
+ print(f"tag={found.tag}")
101
+ print(f"title={found.title}")
102
+ return 0
103
+
104
+
105
+ def _index(args: argparse.Namespace) -> int:
106
+ files = releases.release_files(args.repo)
107
+ pages = index.render_index(files)
108
+ out = Path(args.out).resolve()
109
+ for relative, content in pages.items():
110
+ path = (out / relative).resolve()
111
+ if not path.is_relative_to(out):
112
+ print(f"page {relative!r} escapes {args.out}", file=sys.stderr)
113
+ return 1
114
+ path.parent.mkdir(parents=True, exist_ok=True)
115
+ path.write_text(content, encoding="utf-8")
116
+ projects = len(pages) - 1
117
+ print(f"wrote {projects} projects and {len(files)} files to {args.out}")
118
+ return 0
119
+
120
+
121
+ def _releasable(workspace: ci.Workspace, args: argparse.Namespace) -> int:
122
+ ok, blocked = ci.releasable(workspace.packages, Path(args.ok_dir), args.names)
123
+ for name in blocked:
124
+ print(
125
+ f"not releasing {name}: a check or a prerequisite failed", file=sys.stderr
126
+ )
127
+ for name in ok:
128
+ print(name)
129
+ return 0
130
+
131
+
132
+ def _adapters(workspace: ci.Workspace) -> int:
133
+ problems = uv.check_adapters(workspace)
134
+ for problem in problems:
135
+ print(problem, file=sys.stderr)
136
+ return 1 if problems else 0
137
+
138
+
139
+ def _requirements(root: Path) -> int:
140
+ problems = requirements.check_requirements(root)
141
+ for problem in problems:
142
+ print(problem, file=sys.stderr)
143
+ return 1 if problems else 0
144
+
145
+
146
+ def _run(workspace: ci.Workspace, args: argparse.Namespace) -> int:
147
+ command: str = args.command
148
+ if command == "plan":
149
+ for line in github.output_lines(ci.plan(workspace, args.base)):
150
+ print(line)
151
+ elif command == "releasable":
152
+ return _releasable(workspace, args)
153
+ elif command == "adapters":
154
+ return _adapters(workspace)
155
+ elif command == "released":
156
+ for found in ci.released(workspace):
157
+ print(*found)
158
+ else:
159
+ return uv.smoke(workspace, args.package, args.extra)
160
+ return 0
161
+
162
+
163
+ def main(argv: list[str] | None = None) -> int:
164
+ """Run a subcommand and return its exit status.
165
+
166
+ Args:
167
+ argv: The arguments after the program name; `sys.argv[1:]` when omitted.
168
+ """
169
+ args = _parser().parse_args(argv)
170
+ if args.command == "sonar-target":
171
+ try:
172
+ print(github.sonar_target())
173
+ except ValueError as error:
174
+ sys.exit(str(error))
175
+ return 0
176
+ if args.command == "index":
177
+ return _index(args)
178
+ if args.command == "notes":
179
+ return _notes(args)
180
+ if args.command == "umbrella":
181
+ return _umbrella(args)
182
+
183
+ try:
184
+ root = uv.find_root(Path.cwd())
185
+ if args.command == "requirements":
186
+ return _requirements(root)
187
+ workspace = uv.load_workspace(root)
188
+ except FileNotFoundError as error:
189
+ sys.exit(str(error))
190
+ return _run(workspace, args)
@@ -0,0 +1,44 @@
1
+ """The GitHub Actions adapter: `$GITHUB_OUTPUT` lines and the event context."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+
8
+
9
+ def output_lines(outputs: dict[str, object]) -> list[str]:
10
+ """Return `key=value` lines for `$GITHUB_OUTPUT`, with non-strings as JSON."""
11
+ return [
12
+ f"{key}={value if isinstance(value, str) else json.dumps(value)}"
13
+ for key, value in outputs.items()
14
+ ]
15
+
16
+
17
+ def sonar_branch(event: str, ref_type: str, ref_name: str) -> str:
18
+ """Return the Sonar branch name to analyze, or "" to leave a pull request to the scanner.
19
+
20
+ Raises:
21
+ ValueError: For a tag ref, or any event other than push,
22
+ workflow_dispatch and pull_request.
23
+ """
24
+ if event == "pull_request":
25
+ return ""
26
+ if event not in ("push", "workflow_dispatch"):
27
+ raise ValueError(f"unsupported event for Sonar analysis: {event}")
28
+ if ref_type != "branch":
29
+ raise ValueError(
30
+ f"unsupported ref for Sonar analysis: {ref_type} {ref_name}; run it on a branch"
31
+ )
32
+ return ref_name
33
+
34
+
35
+ def sonar_target() -> str:
36
+ """Return the `branch-arg=` output line for the run in `EVENT_NAME`, `REF_TYPE` and `REF_NAME`.
37
+
38
+ Raises:
39
+ ValueError: As `sonar_branch`.
40
+ """
41
+ branch = sonar_branch(
42
+ os.environ["EVENT_NAME"], os.environ["REF_TYPE"], os.environ["REF_NAME"]
43
+ )
44
+ return f"branch-arg=-Dsonar.branch.name={branch}" if branch else "branch-arg="
@@ -0,0 +1,74 @@
1
+ """A PEP 503 simple index rendered from a list of release files."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import html
6
+ import re
7
+ from collections.abc import Sequence
8
+ from dataclasses import dataclass
9
+
10
+ _PAGE = """<!DOCTYPE html>
11
+ <html>
12
+ <head>
13
+ <meta name="pypi:repository-version" content="1.0">
14
+ <title>{title}</title>
15
+ </head>
16
+ <body>
17
+ {links}
18
+ </body>
19
+ </html>
20
+ """
21
+
22
+
23
+ @dataclass(frozen=True, slots=True)
24
+ class ReleaseFile:
25
+ """One distribution file attached to a release."""
26
+
27
+ project: str
28
+ """The distribution name; normalized when the index is rendered."""
29
+ filename: str
30
+ """The file name, for example `rn_forge_commons-0.7.0-py3-none-any.whl`."""
31
+ url: str
32
+ """The release asset's download URL."""
33
+ sha256: str
34
+ """The file's hex SHA-256 digest."""
35
+
36
+
37
+ def _normalize(name: str) -> str:
38
+ return re.sub(r"[-_.]+", "-", name).lower()
39
+
40
+
41
+ def _page(title: str, links: list[str]) -> str:
42
+ return _PAGE.format(title=html.escape(title), links="\n".join(links))
43
+
44
+
45
+ def render_index(files: Sequence[ReleaseFile]) -> dict[str, str]:
46
+ """Return the index's pages, keyed by relative path.
47
+
48
+ `index.html` links each project, sorted. `<project>/index.html` links each
49
+ of the project's files, sorted by filename, with a `#sha256=` fragment.
50
+ Project names are normalized per PEP 503 and all text is HTML-escaped.
51
+ """
52
+ by_project: dict[str, list[ReleaseFile]] = {}
53
+ for file in files:
54
+ by_project.setdefault(_normalize(file.project), []).append(file)
55
+
56
+ pages = {
57
+ "index.html": _page(
58
+ "Simple index",
59
+ [
60
+ f'<a href="{html.escape(project)}/">{html.escape(project)}</a><br>'
61
+ for project in sorted(by_project)
62
+ ],
63
+ )
64
+ }
65
+ for project, project_files in by_project.items():
66
+ pages[f"{project}/index.html"] = _page(
67
+ f"Links for {project}",
68
+ [
69
+ f'<a href="{html.escape(f.url)}#sha256={html.escape(f.sha256)}">'
70
+ f"{html.escape(f.filename)}</a><br>"
71
+ for f in sorted(project_files, key=lambda f: f.filename)
72
+ ],
73
+ )
74
+ return pages
@@ -0,0 +1,109 @@
1
+ """Release notes: a changelog section and the umbrella release for a shipped page."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ from collections.abc import Collection
7
+ from dataclasses import dataclass
8
+ from pathlib import Path
9
+
10
+ _PAGE_DIR = re.compile(r"release-(\d+)")
11
+ _STATUS = re.compile(r"^\|[ \t]*\*\*Status\*\*[ \t]*\|([^\n]*)\|[ \t]*$", re.MULTILINE)
12
+ _TITLE = re.compile(r"^#[ \t]+(\S[^\n]*)$", re.MULTILINE)
13
+ _SHIPPED_HEADING = re.compile(r"## Shipped[ \t]*")
14
+
15
+
16
+ def _shipped_section(text: str) -> str | None:
17
+ """Return the lines under `## Shipped` up to the next `## ` heading."""
18
+ body: list[str] = []
19
+ inside = False
20
+ for line in text.splitlines(keepends=True):
21
+ if inside:
22
+ if line.startswith("## "):
23
+ break
24
+ body.append(line)
25
+ elif _SHIPPED_HEADING.fullmatch(line.rstrip("\r\n")):
26
+ inside = True
27
+ return "".join(body) if inside else None
28
+
29
+
30
+ @dataclass(frozen=True, slots=True)
31
+ class Umbrella:
32
+ """The GitHub release that announces a shipped release page."""
33
+
34
+ tag: str
35
+ """The release tag, for example `release-6`."""
36
+ title: str
37
+ """The page's H1 text."""
38
+ body: str
39
+ """The release notes: the page's `## Shipped` section and a link to the page."""
40
+
41
+
42
+ def changelog_section(changelog: str, version: str) -> str:
43
+ """Return the body under `## [<version>]` up to the next `## [` heading.
44
+
45
+ The heading is `## [<version>]` followed by the end of the line or
46
+ ` - <date>`; the version must match exactly.
47
+
48
+ Args:
49
+ changelog: The text of a Keep a Changelog file.
50
+ version: The version whose section to return.
51
+
52
+ Returns:
53
+ The section body with surrounding whitespace removed.
54
+
55
+ Raises:
56
+ ValueError: The version has no heading, or its body is empty.
57
+ """
58
+ heading = re.compile(
59
+ rf"^## \[{re.escape(version)}\](?: - .*)?[ \t]*$", re.MULTILINE
60
+ )
61
+ match = heading.search(changelog)
62
+ if match is None:
63
+ raise ValueError(f"no `## [{version}]` heading in the changelog")
64
+ rest = changelog[match.end() :]
65
+ following = re.search(r"^## \[", rest, re.MULTILINE)
66
+ body = (rest[: following.start()] if following else rest).strip()
67
+ if not body:
68
+ raise ValueError(f"the `## [{version}]` section is empty")
69
+ return body
70
+
71
+
72
+ def pending_umbrella(
73
+ releases_dir: Path, existing_tags: Collection[str], site_url: str
74
+ ) -> Umbrella | None:
75
+ """Return the umbrella release for the newest shipped release page.
76
+
77
+ Only the newest page whose `| **Status** |` row starts with `shipped` is
78
+ considered, so older pages are never backfilled.
79
+
80
+ Args:
81
+ releases_dir: A directory of `release-<n>/index.md` pages.
82
+ existing_tags: The repository's existing tag names.
83
+ site_url: The documentation site's URL, ending in `/`.
84
+
85
+ Returns:
86
+ The umbrella release, or `None` when no page is shipped or its tag
87
+ already exists.
88
+ """
89
+ shipped: list[tuple[int, Path]] = []
90
+ for page in releases_dir.glob("release-*/index.md"):
91
+ number = _PAGE_DIR.fullmatch(page.parent.name)
92
+ if number is None:
93
+ continue
94
+ status = _STATUS.search(page.read_text(encoding="utf-8"))
95
+ if status and status.group(1).strip().startswith("shipped"):
96
+ shipped.append((int(number.group(1)), page))
97
+ if not shipped:
98
+ return None
99
+ number, page = max(shipped)
100
+ tag = f"release-{number}"
101
+ if tag in existing_tags:
102
+ return None
103
+ text = page.read_text(encoding="utf-8")
104
+ title = _TITLE.search(text)
105
+ section = _shipped_section(text)
106
+ if title is None or section is None:
107
+ raise ValueError(f"{page} needs an H1 title and a `## Shipped` section")
108
+ link = f"Release page: {site_url}releases/{tag}/"
109
+ return Umbrella(tag, title.group(1).strip(), f"{section.strip()}\n\n{link}\n")
File without changes
@@ -0,0 +1,67 @@
1
+ """The GitHub Releases adapter: the distribution files a repository has published."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import re
8
+ import subprocess
9
+ import urllib.request
10
+ from typing import Any
11
+
12
+ from rn_forge.devops.index import ReleaseFile
13
+
14
+ _TAG = re.compile(r"^(rn-forge-[a-z0-9-]+)-v\d+\.\d+\.\d+$")
15
+ _REPO = re.compile(r"[A-Za-z0-9_.][A-Za-z0-9_.-]*/[A-Za-z0-9_.][A-Za-z0-9_.-]*")
16
+ _SUFFIXES = (".whl", ".tar.gz")
17
+
18
+
19
+ def _releases(repo: str) -> list[dict[str, Any]]:
20
+ # `--slurp` wraps each page in one outer array.
21
+ result = subprocess.run( # noqa: S603 # fixed argv, no shell
22
+ ["gh", "api", f"repos/{repo}/releases", "--paginate", "--slurp"], # noqa: S607 # tool resolved from PATH
23
+ check=True,
24
+ capture_output=True,
25
+ text=True,
26
+ )
27
+ pages: list[list[dict[str, Any]]] = json.loads(result.stdout)
28
+ return [release for page in pages for release in page]
29
+
30
+
31
+ def _sha256(asset: dict[str, Any]) -> str:
32
+ digest: str | None = asset.get("digest")
33
+ if digest and digest.startswith("sha256:"):
34
+ return digest.removeprefix("sha256:")
35
+ with urllib.request.urlopen(asset["browser_download_url"]) as response: # noqa: S310 # asset URL comes from the GitHub API
36
+ return hashlib.sha256(response.read()).hexdigest()
37
+
38
+
39
+ def release_files(repo: str) -> list[ReleaseFile]:
40
+ """Return the wheels and sdists of `repo`'s published `rn-forge-*` releases.
41
+
42
+ Drafts, prereleases and tags not named `rn-forge-<name>-vX.Y.Z` are skipped.
43
+ A file's digest is the asset's `sha256:` digest, or the hash of its download
44
+ when the asset has none.
45
+
46
+ Raises:
47
+ ValueError: If `repo` is not `owner/name`.
48
+ subprocess.CalledProcessError: If `gh api` fails.
49
+ """
50
+ if not _REPO.fullmatch(repo) or {".", ".."} & set(repo.split("/")):
51
+ raise ValueError(f"invalid repo {repo!r}")
52
+ files: list[ReleaseFile] = []
53
+ for release in _releases(repo):
54
+ match = _TAG.match(release["tag_name"])
55
+ if release["draft"] or release["prerelease"] or not match:
56
+ continue
57
+ files.extend(
58
+ ReleaseFile(
59
+ project=match.group(1),
60
+ filename=asset["name"],
61
+ url=asset["browser_download_url"],
62
+ sha256=_sha256(asset),
63
+ )
64
+ for asset in release["assets"]
65
+ if asset["name"].endswith(_SUFFIXES)
66
+ )
67
+ return files
@@ -0,0 +1,91 @@
1
+ """Check that requirements between workspace members are version ranges."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import tomllib
6
+ from pathlib import Path
7
+ from typing import Any
8
+
9
+ from packaging.requirements import Requirement
10
+ from packaging.utils import canonicalize_name
11
+ from packaging.version import Version
12
+
13
+ MANIFEST = "pyproject.toml"
14
+
15
+
16
+ def _members(root: Path) -> dict[str, tuple[str, str, dict[str, Any]]]:
17
+ """Map each member's canonical name to its name, version and manifest."""
18
+ workspace: dict[str, Any] = tomllib.loads((root / MANIFEST).read_text())["tool"][
19
+ "uv"
20
+ ]["workspace"]
21
+ excluded = {
22
+ path
23
+ for pattern in workspace.get("exclude", [])
24
+ for path in root.glob(f"{pattern}/{MANIFEST}")
25
+ }
26
+ members: dict[str, tuple[str, str, dict[str, Any]]] = {}
27
+ for pattern in workspace["members"]:
28
+ for path in sorted(root.glob(f"{pattern}/{MANIFEST}")):
29
+ if path in excluded:
30
+ continue
31
+ manifest: dict[str, Any] = tomllib.loads(path.read_text())
32
+ project: dict[str, Any] = manifest["project"]
33
+ name: str = project["name"]
34
+ members[canonicalize_name(name)] = (
35
+ name,
36
+ project.get("version", ""),
37
+ manifest,
38
+ )
39
+ return members
40
+
41
+
42
+ def _requirements(project: dict[str, Any], groups: dict[str, Any]) -> list[str]:
43
+ """Return every requirement string of one member's manifest."""
44
+ found: list[str] = list(project.get("dependencies", []))
45
+ for extra in project.get("optional-dependencies", {}).values():
46
+ found.extend(extra)
47
+ for group in groups.values():
48
+ found.extend(item for item in group if isinstance(item, str))
49
+ return found
50
+
51
+
52
+ def check_requirements(root: Path) -> list[str]:
53
+ """Return the problems with requirements on other workspace members.
54
+
55
+ Reads the members listed under `[tool.uv.workspace]` in `root/pyproject.toml`.
56
+ A requirement on a member, in `dependencies`, `optional-dependencies` or
57
+ `[dependency-groups]`, is reported when it is a URL, when its specifier
58
+ excludes the member's `[project]` version, or when its specifier has no
59
+ `<` or `<=` clause. Requirements on anything else are ignored.
60
+
61
+ Args:
62
+ root: The workspace root directory.
63
+
64
+ Returns:
65
+ One message per problem, empty when the requirements are all ranges.
66
+ """
67
+ members = _members(root)
68
+ problems: list[str] = []
69
+ for key, (name, _, manifest) in members.items():
70
+ for text in _requirements(
71
+ manifest["project"], manifest.get("dependency-groups", {})
72
+ ):
73
+ req = Requirement(text)
74
+ target_key = canonicalize_name(req.name)
75
+ target = members.get(target_key)
76
+ # A package naming itself (an extra that includes other extras) is no dependency.
77
+ if target is not None and target_key != key:
78
+ problems.extend(_problems(name, req, target[1]))
79
+ return problems
80
+
81
+
82
+ def _problems(package: str, req: Requirement, version: str) -> list[str]:
83
+ if req.url is not None:
84
+ return [f"{package}: {req.name} is a URL; use a range (ADR-0004)"]
85
+ spec = req.specifier
86
+ shown = f"{req.name}{spec}"
87
+ if version and not spec.contains(Version(version), prereleases=True):
88
+ return [f"{package}: {shown} excludes the workspace's {version}"]
89
+ if not any(clause.operator in ("<", "<=") for clause in spec):
90
+ return [f"{package}: {shown} has no ceiling"]
91
+ return []
rn_forge/devops/uv.py ADDED
@@ -0,0 +1,280 @@
1
+ """The uv workspace adapter: manifest reading and the `smoke` and `adapters` checks.
2
+
3
+ Members are those of the root `[tool.uv.workspace]`. A member's internal
4
+ requirements are the members named in its dependencies, optional dependencies and
5
+ dependency groups. CI settings live in `[tool.workspace-ci]` tables: the root one
6
+ holds workspace-wide settings, a member's own holds that member's extra checks.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import fnmatch
12
+ import subprocess
13
+ import tempfile
14
+ import tomllib
15
+ import zipfile
16
+ from email.parser import Parser
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from packaging.requirements import Requirement
21
+ from rn_forge.devops.ci import (
22
+ Package,
23
+ Smoke,
24
+ Workspace,
25
+ normalize,
26
+ requirement_name,
27
+ )
28
+
29
+ TOOL = "workspace-ci"
30
+ MANIFEST = "pyproject.toml"
31
+
32
+ IMPORT_SNIPPET = """
33
+ import importlib, runpy, sys
34
+ setup, *modules = sys.argv[1:]
35
+ if setup:
36
+ runpy.run_path(setup)
37
+ for name in modules:
38
+ importlib.import_module(name)
39
+ print("imported", name)
40
+ """
41
+
42
+
43
+ def find_root(start: Path) -> Path:
44
+ """Return the nearest directory at or above `start` whose `pyproject.toml`
45
+ declares `[tool.uv.workspace]`.
46
+
47
+ Raises:
48
+ FileNotFoundError: When there is none.
49
+ """
50
+ for directory in (start, *start.parents):
51
+ manifest = directory / MANIFEST
52
+ if manifest.is_file() and "workspace" in tomllib.loads(
53
+ manifest.read_text()
54
+ ).get("tool", {}).get("uv", {}):
55
+ return directory
56
+ raise FileNotFoundError(f"no uv workspace at or above {start}")
57
+
58
+
59
+ def load_workspace(root: Path) -> Workspace:
60
+ """Read the uv workspace at `root` into the core's graph."""
61
+ manifest: dict[str, Any] = tomllib.loads((root / MANIFEST).read_text())
62
+ workspace = manifest["tool"]["uv"]["workspace"]
63
+ excluded = workspace.get("exclude", [])
64
+ dirs = sorted(
65
+ {
66
+ path.parent
67
+ for pattern in workspace["members"]
68
+ for path in root.glob(f"{pattern}/{MANIFEST}")
69
+ if not any(
70
+ fnmatch.fnmatch(path.parent.relative_to(root).as_posix(), x)
71
+ for x in excluded
72
+ )
73
+ }
74
+ )
75
+ manifests = {path: tomllib.loads((path / MANIFEST).read_text()) for path in dirs}
76
+ names = {normalize(m["project"]["name"]) for m in manifests.values()}
77
+ packages: dict[str, Package] = {}
78
+ for path, member in manifests.items():
79
+ project = member["project"]
80
+ tool = member.get("tool", {})
81
+ requirements: list[str] = list(project.get("dependencies", []))
82
+ for extra in project.get("optional-dependencies", {}).values():
83
+ requirements += extra
84
+ release_requirements = list(requirements)
85
+ for group in member.get("dependency-groups", {}).values():
86
+ requirements += [item for item in group if isinstance(item, str)]
87
+ name = normalize(project["name"])
88
+ ci = tool.get(TOOL, {})
89
+ smoke = ci.get("smoke")
90
+ packages[name] = Package(
91
+ name=name,
92
+ dir=path.relative_to(root).as_posix(),
93
+ module=tool.get("uv", {}).get("build-backend", {}).get("module-name")
94
+ or name.replace("-", "_"),
95
+ requires={r for r in map(requirement_name, requirements) if r in names}
96
+ - {name},
97
+ release_requires={
98
+ r for r in map(requirement_name, release_requirements) if r in names
99
+ }
100
+ - {name},
101
+ postgres_env=ci["postgres"]["env"] if "postgres" in ci else None,
102
+ redis_env=ci["redis"]["env"] if "redis" in ci else None,
103
+ smoke=(
104
+ Smoke(
105
+ modules=smoke.get("modules", []),
106
+ extras=smoke.get("extras", {}),
107
+ setup=smoke.get("setup", ""),
108
+ )
109
+ if smoke is not None
110
+ else None
111
+ ),
112
+ adapters=ci.get("adapters"),
113
+ )
114
+ settings = manifest.get("tool", {}).get(TOOL, {})
115
+ return Workspace(
116
+ root=root,
117
+ packages=packages,
118
+ pytest_args=settings.get("pytest-args", []),
119
+ suites=settings.get("suites", {}),
120
+ )
121
+
122
+
123
+ def adapter_problems(
124
+ package: Package, extras: set[str], modules: set[str]
125
+ ) -> list[str]:
126
+ """Return one message per problem with the adapters `package` declares.
127
+
128
+ A declared adapter is a problem when it is repeated, when it is not in
129
+ `modules`, or when it is not in `extras`.
130
+
131
+ Args:
132
+ package: The member; one that declares no adapters has no problems.
133
+ extras: The names in the member's `[project.optional-dependencies]`.
134
+ modules: The module and subpackage names found in the member's source
135
+ directory.
136
+ """
137
+ problems: list[str] = []
138
+ seen: set[str] = set()
139
+ for name in package.adapters or []:
140
+ if name in seen:
141
+ problems.append(f"{package.name}: adapter {name} is declared twice")
142
+ continue
143
+ seen.add(name)
144
+ if name not in modules:
145
+ problems.append(f"{package.name}: adapter {name} has no module {name}")
146
+ if name not in extras:
147
+ problems.append(f"{package.name}: adapter {name} has no extra {name}")
148
+ return problems
149
+
150
+
151
+ def check_adapters(workspace: Workspace) -> list[str]:
152
+ """Return the problems `adapter_problems` finds across the workspace members
153
+ that declare `adapters`."""
154
+ problems: list[str] = []
155
+ for package in workspace.packages.values():
156
+ if package.adapters is None:
157
+ continue
158
+ member = workspace.root / package.dir
159
+ manifest: dict[str, Any] = tomllib.loads((member / MANIFEST).read_text())
160
+ source = member / "src" / Path(*package.module.split("."))
161
+ modules = {
162
+ path.stem if path.is_file() else path.name
163
+ for path in (source.iterdir() if source.is_dir() else ())
164
+ if path.is_dir() or path.suffix == ".py"
165
+ }
166
+ extras = set(manifest["project"].get("optional-dependencies", {}))
167
+ problems += adapter_problems(package, extras, modules)
168
+ return problems
169
+
170
+
171
+ def _closure(packages: dict[str, Package], name: str, seen: set[str]) -> set[str]:
172
+ for requirement in packages[name].requires - seen:
173
+ seen.add(requirement)
174
+ _closure(packages, requirement, seen)
175
+ return seen
176
+
177
+
178
+ def _wheel_requires(wheel: Path) -> list[Requirement]:
179
+ with zipfile.ZipFile(wheel) as archive:
180
+ name = next(n for n in archive.namelist() if n.endswith(".dist-info/METADATA"))
181
+ metadata = Parser().parsestr(archive.read(name).decode())
182
+ return [Requirement(line) for line in metadata.get_all("Requires-Dist") or []]
183
+
184
+
185
+ def _active(req: Requirement, extras: set[str]) -> bool:
186
+ return req.marker is None or any(
187
+ req.marker.evaluate({"extra": e}) for e in ("", *extras)
188
+ )
189
+
190
+
191
+ def _local_extras(
192
+ wheels: dict[str, Path], package: str, extra: str
193
+ ) -> dict[str, set[str]]:
194
+ """Return which extras each local wheel is asked for, starting from `package`."""
195
+ local: dict[str, set[str]] = {}
196
+ pending: list[tuple[str, set[str]]] = [(package, {extra} if extra else set())]
197
+ while pending:
198
+ name, extras = pending.pop()
199
+ if name in local and extras <= local[name]:
200
+ continue
201
+ local[name] = local.get(name, set()) | extras
202
+ pending += [
203
+ (normalize(req.name), set(req.extras))
204
+ for req in _wheel_requires(wheels[name])
205
+ if normalize(req.name) in wheels
206
+ and normalize(req.name) != name
207
+ and _active(req, local[name])
208
+ ]
209
+ return local
210
+
211
+
212
+ def _external_requirements(
213
+ wheels: dict[str, Path], local: dict[str, set[str]]
214
+ ) -> set[str]:
215
+ external: set[str] = set()
216
+ for name, extras in local.items():
217
+ for req in _wheel_requires(wheels[name]):
218
+ if normalize(req.name) not in wheels and _active(req, extras):
219
+ req.marker = None
220
+ external.add(str(req))
221
+ return external
222
+
223
+
224
+ def smoke(workspace: Workspace, package_name: str, extra: str) -> int:
225
+ """Install `package_name` with only `extra` from wheels built from this checkout
226
+ into a clean venv, then import the modules its `[tool.workspace-ci.smoke]` lists,
227
+ or the package's own module when it declares none.
228
+
229
+ The install uses exactly what the wheels declare, so an extra that omits a
230
+ dependency another extra brings fails here. An empty `extra` installs the
231
+ package with no extra.
232
+
233
+ Returns:
234
+ The exit status of the import step.
235
+ """
236
+ root, packages = workspace.root, workspace.packages
237
+ package = packages[normalize(package_name)]
238
+ config = package.smoke or Smoke()
239
+ modules = [
240
+ *(config.modules if package.smoke else [package.module]),
241
+ *(config.extras[extra] if extra else []),
242
+ ]
243
+
244
+ with tempfile.TemporaryDirectory() as tmp:
245
+ dist = Path(tmp) / "dist"
246
+ for name in sorted(_closure(packages, package.name, {package.name})):
247
+ subprocess.run( # noqa: S603 # fixed argv, no shell
248
+ [ # noqa: S607 # tool resolved from PATH
249
+ "uv",
250
+ "build",
251
+ "-q",
252
+ "--package",
253
+ name,
254
+ "--wheel",
255
+ "--out-dir",
256
+ str(dist),
257
+ ],
258
+ cwd=root,
259
+ check=True,
260
+ )
261
+ wheels = {normalize(w.name.split("-")[0]): w for w in dist.glob("*.whl")}
262
+ local = _local_extras(wheels, package.name, extra)
263
+ external = _external_requirements(wheels, local)
264
+ print(f"extra={extra or '(none)'} local={local}")
265
+
266
+ venv = Path(tmp) / "venv"
267
+ python = venv / "bin" / "python"
268
+ subprocess.run(["uv", "venv", "-q", str(venv)], cwd=root, check=True) # noqa: S603, S607 # fixed argv, no shell; tool resolved from PATH
269
+ install = ["uv", "pip", "install", "-q", "--python", str(python)]
270
+ # Local wheels go in without deps, so their git-pinned siblings are never
271
+ # fetched; everything else they declare is in `external`.
272
+ if external:
273
+ subprocess.run([*install, *sorted(external)], check=True) # noqa: S603 # fixed argv, no shell
274
+ subprocess.run( # noqa: S603 # fixed argv, no shell
275
+ [*install, "--no-deps", *(str(wheels[n]) for n in local)], check=True
276
+ )
277
+ setup = str(root / package.dir / config.setup) if config.setup else ""
278
+ return subprocess.run( # noqa: S603 # fixed argv, no shell
279
+ [str(python), "-c", IMPORT_SNIPPET, setup, *modules], check=False
280
+ ).returncode
@@ -0,0 +1,74 @@
1
+ Metadata-Version: 2.4
2
+ Name: rn-forge-devops
3
+ Version: 0.3.1
4
+ Summary: CI and release automation for rn-forge repositories in any language, run with uv
5
+ Author: Rohit Narayanan
6
+ Author-email: Rohit Narayanan <rohit.nn@gmail.com>
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Operating System :: OS Independent
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3 :: Only
14
+ Classifier: Programming Language :: Python :: 3.14
15
+ Classifier: Typing :: Typed
16
+ Requires-Dist: packaging>=24
17
+ Requires-Python: >=3.14
18
+ Project-URL: Documentation, https://rn-forge.github.io/pykit/packages/rn-forge-devops/latest/
19
+ Project-URL: Source, https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-devops
20
+ Project-URL: Changelog, https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-devops/CHANGELOG.md
21
+ Project-URL: Issues, https://github.com/rn-forge/pykit/issues
22
+ Description-Content-Type: text/markdown
23
+
24
+ # rn-forge-devops
25
+
26
+ [Documentation](https://rn-forge.github.io/pykit/packages/rn-forge-devops/latest/)
27
+ ·
28
+ [Changelog](https://github.com/rn-forge/pykit/blob/main/packages/rn-forge-devops/CHANGELOG.md)
29
+ · [Source](https://github.com/rn-forge/pykit/tree/main/packages/rn-forge-devops)
30
+ · [All pykit packages](https://rn-forge.github.io/pykit/)
31
+
32
+ CI and release automation for rn-forge repositories in any language, run with
33
+ uv. The `rn-forge-devops` command reads a repository's workspace manifests,
34
+ selects the packages a change affects, prints every CI job's matrix, and gates
35
+ each package's release on its checks. Workflow files call it instead of carrying
36
+ that logic.
37
+
38
+ It depends on `packaging` and on no other rn-forge package. It is a CI tool, not
39
+ a library an application depends on.
40
+
41
+ - `rn_forge.devops.ci` — the core: the member graph, change selection, check
42
+ matrices and release gating. It knows neither the CI platform nor the stack.
43
+ - `rn_forge.devops.requirements` — the `requirements` check: every requirement
44
+ between workspace members is a version range that admits the member's
45
+ current version and has a ceiling.
46
+ - `rn_forge.devops.uv` — the uv workspace adapter: it reads
47
+ `[tool.uv.workspace]` members, their internal requirements and their
48
+ `[tool.workspace-ci]` tables, and runs `smoke`.
49
+ - `rn_forge.devops.github` — the GitHub Actions adapter: `$GITHUB_OUTPUT` lines
50
+ and the event context.
51
+ - `rn_forge.devops.index` and `rn_forge.devops.releases` — the `index`
52
+ subcommand: a PEP 503 simple index rendered from a repository's GitHub
53
+ Release files, and the adapter that reads them with `gh`.
54
+ - `rn_forge.devops.notes` — the `notes` and `umbrella` subcommands: a changelog
55
+ version's section, and the umbrella release for the newest shipped release
56
+ page.
57
+ - `rn_forge.devops.cli` — the `rn-forge-devops` console script.
58
+
59
+ The package facade re-exports the planner core only. The core never imports an
60
+ adapter, and the package never imports another `rn_forge` package;
61
+ `.importlinter` proves both.
62
+
63
+ ## Usage
64
+
65
+ Run it from inside a uv workspace; the workspace root is the nearest directory
66
+ at or above the current one whose `pyproject.toml` declares
67
+ `[tool.uv.workspace]`.
68
+
69
+ ```bash
70
+ uvx --from "rn-forge-devops>=0.3,<0.4" rn-forge-devops plan
71
+ ```
72
+
73
+ The subcommands and the `[tool.workspace-ci]` tables are described in the
74
+ [subcommand reference](https://rn-forge.github.io/pykit/packages/rn-forge-devops/latest/reference/subcommands.html).
@@ -0,0 +1,15 @@
1
+ rn_forge/devops/__init__.py,sha256=rEGywE0GugMXyzImtaCd33VdtqpvKwzM89BYE9CmFWI,506
2
+ rn_forge/devops/ci.py,sha256=vLx170w3yOWI0c8YS9b3bRHzllThoDXeD56yqS0H5MA,10902
3
+ rn_forge/devops/cli.py,sha256=mDRwy1u_IcjA5tTdL24vZKG8qBeWSObmce920jt6cvs,6691
4
+ rn_forge/devops/github.py,sha256=-V3XaJsj8Pa-hoGz2OGKd9v4rR4DLDNjjObDb1t0qL0,1455
5
+ rn_forge/devops/index.py,sha256=dpxM6uJJ9XqtqZVxndQ8myh8zcJL8EKB2VRO0Oin2TM,2143
6
+ rn_forge/devops/notes.py,sha256=L-hMs5BW4BAabH-L4zKxRBsbWxs3Xgjhmj3-QxQ1IrA,3868
7
+ rn_forge/devops/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
8
+ rn_forge/devops/releases.py,sha256=W3KBkXOTly0-2cuOIe54v1sUhXWL0T3BqJQqywNT5Bw,2437
9
+ rn_forge/devops/requirements.py,sha256=lTmzgfaJlTwG-9iRDKnMawvg-hYhbwCgyHqJ2zISjtU,3521
10
+ rn_forge/devops/uv.py,sha256=QLmUttawpNMoPQ4xJEEpzCOBT6pXVV1Tcyjzc5LqIaE,10665
11
+ rn_forge_devops-0.3.1.dist-info/licenses/LICENSE,sha256=buwykOASkbZdpj0j_JmFbwNzbUiuLzOiaMQmVQt5lr8,1072
12
+ rn_forge_devops-0.3.1.dist-info/WHEEL,sha256=3NO1oYsF7mANFUWVdyEQLM-zmecczWWEmmF5rEbXrWk,80
13
+ rn_forge_devops-0.3.1.dist-info/entry_points.txt,sha256=s7nwJpq1fLs0mNK8U08ENTbE6CPlET-88cn97AesZgY,62
14
+ rn_forge_devops-0.3.1.dist-info/METADATA,sha256=27GYo8O7e-bWyXDDLCZ615xARVuFWQ6AUX3mRNAL53M,3513
15
+ rn_forge_devops-0.3.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.6
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ rn-forge-devops = rn_forge.devops.cli:main
3
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Rohit Narayanan
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.