rsbt 0.1.1__tar.gz

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.
rsbt-0.1.1/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ArchMachina
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.
rsbt-0.1.1/PKG-INFO ADDED
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.4
2
+ Name: rsbt
3
+ Version: 0.1.1
4
+ Summary: Really Simple Build Tool - a small library of CI/CD build, test and release helpers
5
+ Description-Content-Type: text/markdown
6
+ License-File: LICENSE
7
+ Requires-Dist: requests>=2.32.3
8
+ Dynamic: description
9
+ Dynamic: description-content-type
10
+ Dynamic: license-file
11
+ Dynamic: requires-dist
12
+ Dynamic: summary
13
+
14
+ # rsbt
15
+
16
+ Really Simple Build Tool - a small Python library of helpers for writing
17
+ CI/CD build, test, lint, release and deploy pipelines as plain Python
18
+ scripts.
19
+
20
+
21
+ ## What it provides
22
+
23
+ - `action` / `run_action()` - register functions as named CLI actions and
24
+ dispatch to them from `sys.argv`, so an `_entrypoint.py` can expose
25
+ `build`, `test`, `lint`, `release`, etc. as subcommands.
26
+ - `exec_cmd` / `bash` / `pwsh` / `shell` - run subprocesses with consistent
27
+ logging, exit-code handling and output capture.
28
+ - `PythonSession` - build and publish a Python package to PyPI.
29
+ - `ContainerSession` - build, tag, log in to a registry and push a
30
+ container image.
31
+ - `TestingSession` / `LintingSession` - run a list of shell commands and
32
+ fail the build if any of them fail.
33
+ - `BuildSession` - parse a semver version out of one or more candidate
34
+ sources (a git tag, a `GITHUB_REF`, a fallback string).
35
+ - `DeploySession` - model an environment promotion chain (e.g.
36
+ `dev -> test -> prod`) and open the promotion pull request on GitHub or
37
+ Forgejo/Gitea.
38
+ - `Util` - assorted helpers: git metadata, GitHub releases, and an HTTP
39
+ request helper with built-in retry/backoff for transient failures.
40
+
41
+ See [`src/rsbt/__init__.py`](src/rsbt/__init__.py) for the full API, this
42
+ repo's own [`_entrypoint.py`](_entrypoint.py) for a worked example of
43
+ building/testing/releasing a PyPI package with it, and
44
+ [`examples/`](examples/) for fuller, reference-only examples of the other
45
+ session types (container images, environment promotion).
46
+
47
+ ## Examples
48
+
49
+ A consuming repo's `_entrypoint.py` registers its pipeline steps as
50
+ actions and ends with `rsbt.run_action()`, which dispatches
51
+ `./entrypoint <action>` to the matching function.
52
+
53
+ ### A simple Python build
54
+
55
+ ```python
56
+ import os
57
+
58
+ import rsbt
59
+ from rsbt import action, Util
60
+
61
+ bs = rsbt.BuildSession([f"0.1.0-rolling+{Util.git_sha()}"])
62
+ pys = rsbt.PythonSession()
63
+
64
+
65
+ @action
66
+ def build():
67
+ os.environ["BUILD_VERSION"] = bs.v_mmp
68
+ pys.setup()
69
+ pys.build()
70
+
71
+
72
+ @action
73
+ def release():
74
+ bs.update_version([os.environ["GITHUB_REF"]])
75
+ build()
76
+ pys.publish("__token__", os.environ["PYPI_TOKEN"])
77
+
78
+
79
+ rsbt.run_action()
80
+ ```
81
+
82
+ ### A simple Docker build
83
+
84
+ ```python
85
+ import os
86
+
87
+ import rsbt
88
+ from rsbt import action
89
+
90
+ cs = rsbt.ContainerSession("myorg/myimage", "src/Dockerfile", "src")
91
+
92
+
93
+ @action
94
+ def build():
95
+ cs.tags = ["latest"]
96
+ cs.build()
97
+
98
+
99
+ @action
100
+ def push():
101
+ build()
102
+ cs.login(
103
+ os.environ["REGISTRY_URL"],
104
+ os.environ["REGISTRY_USERNAME"],
105
+ os.environ["REGISTRY_PASSWORD"],
106
+ )
107
+ cs.push()
108
+
109
+
110
+ rsbt.run_action()
111
+ ```
112
+
113
+ ### A simple deployment
114
+
115
+ ```python
116
+ import os
117
+
118
+ import rsbt
119
+ from rsbt import action
120
+
121
+ ds = rsbt.DeploySession()
122
+ ds.define_env("dev", next_env="prod")
123
+ ds.define_env("prod")
124
+
125
+
126
+ @action
127
+ def apply():
128
+ env_name = os.environ["DEPLOY_ENV"]
129
+ rsbt.bash(f"ansible-playbook -i inventory/{env_name} site.yml")
130
+
131
+
132
+ @action
133
+ def promote():
134
+ ds.promote_github(
135
+ os.environ["DEPLOY_ENV"],
136
+ repo=os.environ["GITHUB_REPOSITORY"],
137
+ promote_token=os.environ["PROMOTE_TOKEN"],
138
+ )
139
+
140
+
141
+ rsbt.run_action()
142
+ ```
143
+
144
+ ## Self-hosting
145
+
146
+ `rsbt` builds, tests and releases itself using itself: `requirements.txt`
147
+ installs this checkout in editable mode (`-e .`), so `_entrypoint.py`'s
148
+ `import rsbt` always resolves to the current working tree rather than a
149
+ previously published release. This keeps the self-hosted pipeline honest -
150
+ it always exercises the code that is actually being shipped.
151
+
152
+ ## Installing
153
+
154
+ ```
155
+ pip install rsbt
156
+ ```
157
+
158
+ ## Development
159
+
160
+ `./entrypoint build|test|lint|release` runs the build, test, lint and
161
+ release actions defined in `_entrypoint.py`. `test` builds and runs
162
+ `src/Dockerfile`'s `testing` stage in a container, so the test suite runs
163
+ in a disposable, reproducible environment rather than directly on the
164
+ host.
rsbt-0.1.1/README.md ADDED
@@ -0,0 +1,151 @@
1
+ # rsbt
2
+
3
+ Really Simple Build Tool - a small Python library of helpers for writing
4
+ CI/CD build, test, lint, release and deploy pipelines as plain Python
5
+ scripts.
6
+
7
+
8
+ ## What it provides
9
+
10
+ - `action` / `run_action()` - register functions as named CLI actions and
11
+ dispatch to them from `sys.argv`, so an `_entrypoint.py` can expose
12
+ `build`, `test`, `lint`, `release`, etc. as subcommands.
13
+ - `exec_cmd` / `bash` / `pwsh` / `shell` - run subprocesses with consistent
14
+ logging, exit-code handling and output capture.
15
+ - `PythonSession` - build and publish a Python package to PyPI.
16
+ - `ContainerSession` - build, tag, log in to a registry and push a
17
+ container image.
18
+ - `TestingSession` / `LintingSession` - run a list of shell commands and
19
+ fail the build if any of them fail.
20
+ - `BuildSession` - parse a semver version out of one or more candidate
21
+ sources (a git tag, a `GITHUB_REF`, a fallback string).
22
+ - `DeploySession` - model an environment promotion chain (e.g.
23
+ `dev -> test -> prod`) and open the promotion pull request on GitHub or
24
+ Forgejo/Gitea.
25
+ - `Util` - assorted helpers: git metadata, GitHub releases, and an HTTP
26
+ request helper with built-in retry/backoff for transient failures.
27
+
28
+ See [`src/rsbt/__init__.py`](src/rsbt/__init__.py) for the full API, this
29
+ repo's own [`_entrypoint.py`](_entrypoint.py) for a worked example of
30
+ building/testing/releasing a PyPI package with it, and
31
+ [`examples/`](examples/) for fuller, reference-only examples of the other
32
+ session types (container images, environment promotion).
33
+
34
+ ## Examples
35
+
36
+ A consuming repo's `_entrypoint.py` registers its pipeline steps as
37
+ actions and ends with `rsbt.run_action()`, which dispatches
38
+ `./entrypoint <action>` to the matching function.
39
+
40
+ ### A simple Python build
41
+
42
+ ```python
43
+ import os
44
+
45
+ import rsbt
46
+ from rsbt import action, Util
47
+
48
+ bs = rsbt.BuildSession([f"0.1.0-rolling+{Util.git_sha()}"])
49
+ pys = rsbt.PythonSession()
50
+
51
+
52
+ @action
53
+ def build():
54
+ os.environ["BUILD_VERSION"] = bs.v_mmp
55
+ pys.setup()
56
+ pys.build()
57
+
58
+
59
+ @action
60
+ def release():
61
+ bs.update_version([os.environ["GITHUB_REF"]])
62
+ build()
63
+ pys.publish("__token__", os.environ["PYPI_TOKEN"])
64
+
65
+
66
+ rsbt.run_action()
67
+ ```
68
+
69
+ ### A simple Docker build
70
+
71
+ ```python
72
+ import os
73
+
74
+ import rsbt
75
+ from rsbt import action
76
+
77
+ cs = rsbt.ContainerSession("myorg/myimage", "src/Dockerfile", "src")
78
+
79
+
80
+ @action
81
+ def build():
82
+ cs.tags = ["latest"]
83
+ cs.build()
84
+
85
+
86
+ @action
87
+ def push():
88
+ build()
89
+ cs.login(
90
+ os.environ["REGISTRY_URL"],
91
+ os.environ["REGISTRY_USERNAME"],
92
+ os.environ["REGISTRY_PASSWORD"],
93
+ )
94
+ cs.push()
95
+
96
+
97
+ rsbt.run_action()
98
+ ```
99
+
100
+ ### A simple deployment
101
+
102
+ ```python
103
+ import os
104
+
105
+ import rsbt
106
+ from rsbt import action
107
+
108
+ ds = rsbt.DeploySession()
109
+ ds.define_env("dev", next_env="prod")
110
+ ds.define_env("prod")
111
+
112
+
113
+ @action
114
+ def apply():
115
+ env_name = os.environ["DEPLOY_ENV"]
116
+ rsbt.bash(f"ansible-playbook -i inventory/{env_name} site.yml")
117
+
118
+
119
+ @action
120
+ def promote():
121
+ ds.promote_github(
122
+ os.environ["DEPLOY_ENV"],
123
+ repo=os.environ["GITHUB_REPOSITORY"],
124
+ promote_token=os.environ["PROMOTE_TOKEN"],
125
+ )
126
+
127
+
128
+ rsbt.run_action()
129
+ ```
130
+
131
+ ## Self-hosting
132
+
133
+ `rsbt` builds, tests and releases itself using itself: `requirements.txt`
134
+ installs this checkout in editable mode (`-e .`), so `_entrypoint.py`'s
135
+ `import rsbt` always resolves to the current working tree rather than a
136
+ previously published release. This keeps the self-hosted pipeline honest -
137
+ it always exercises the code that is actually being shipped.
138
+
139
+ ## Installing
140
+
141
+ ```
142
+ pip install rsbt
143
+ ```
144
+
145
+ ## Development
146
+
147
+ `./entrypoint build|test|lint|release` runs the build, test, lint and
148
+ release actions defined in `_entrypoint.py`. `test` builds and runs
149
+ `src/Dockerfile`'s `testing` stage in a container, so the test suite runs
150
+ in a disposable, reproducible environment rather than directly on the
151
+ host.
@@ -0,0 +1,22 @@
1
+ [tool.black]
2
+ line-length = 100
3
+
4
+ [tool.pylint.format]
5
+ max-line-length = 100
6
+
7
+ [tool.pylint."MESSAGES CONTROL"]
8
+ # redefined-outer-name/unused-argument: pytest's fixture mechanism works by
9
+ # re-declaring a fixture name as a test function parameter, often without
10
+ # using its value directly - that is the idiom, not a bug.
11
+ # too-few-public-methods/too-many-instance-attributes/too-many-arguments/
12
+ # too-many-positional-arguments: rsbt is a library of small, deliberately
13
+ # thin helper/exception/value classes and plumbing functions; these
14
+ # complexity metrics don't fit that shape.
15
+ disable = [
16
+ "redefined-outer-name",
17
+ "unused-argument",
18
+ "too-few-public-methods",
19
+ "too-many-instance-attributes",
20
+ "too-many-arguments",
21
+ "too-many-positional-arguments",
22
+ ]
rsbt-0.1.1/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
rsbt-0.1.1/setup.py ADDED
@@ -0,0 +1,22 @@
1
+ import os
2
+
3
+ from setuptools import find_packages, setup
4
+
5
+ with open("README.md") as readme_file:
6
+ README = readme_file.read()
7
+
8
+ setup_args = {
9
+ "name": "rsbt",
10
+ "version": os.environ["BUILD_VERSION"],
11
+ "description": "Really Simple Build Tool - a small library of CI/CD build, test and release helpers",
12
+ "long_description_content_type": "text/markdown",
13
+ "long_description": README,
14
+ "packages": find_packages(where="src", include=["rsbt", "rsbt.*"]),
15
+ "package_dir": {"": "src"},
16
+ "install_requires": [
17
+ "requests>=2.32.3",
18
+ ],
19
+ }
20
+
21
+ if __name__ == "__main__":
22
+ setup(**setup_args, include_package_data=True)
@@ -0,0 +1,814 @@
1
+ """rsbt - Really Simple Build Tool.
2
+
3
+ A small library of helpers for writing CI/CD build, test, lint, release and
4
+ deploy pipelines as plain Python (an ``_entrypoint.py``) instead of large
5
+ shell scripts or YAML: a CLI action dispatcher, a subprocess runner, and a
6
+ handful of "session" helper classes for the common build/test/release
7
+ shapes (Python packages, container images, environment promotion chains).
8
+ """
9
+
10
+ import argparse
11
+ import inspect
12
+ import json
13
+ import logging
14
+ import os
15
+ import re
16
+ import shlex
17
+ import subprocess
18
+ import sys
19
+ import textwrap
20
+ import time
21
+
22
+ import requests
23
+
24
+
25
+ # Exceptions
26
+ class ArgumentException(Exception):
27
+ """Raised when a function is called with an invalid argument."""
28
+
29
+
30
+ class CommandException(Exception):
31
+ """Raised when a subprocess exits with an exit code that was not allowed."""
32
+
33
+
34
+ class DeployError(Exception):
35
+ """Raised for invalid usage of the deployment/promotion helpers."""
36
+
37
+
38
+ class VersionParseError(Exception):
39
+ """Raised when no semver match could be found among the given sources."""
40
+
41
+
42
+ class BuildFailure(Exception):
43
+ """Raised to fail a build, e.g. when a test or lint command fails."""
44
+
45
+
46
+ def val_arg(val, message):
47
+ """Raise ArgumentException(message) if val is falsy."""
48
+ if not val:
49
+ raise ArgumentException(message)
50
+
51
+
52
+ # Logging
53
+ logger = logging.getLogger(__name__)
54
+ logging.basicConfig(level=logging.INFO, format="%(levelname)s: %(message)s")
55
+
56
+
57
+ def configure_logging(debug=False):
58
+ """(Re)configure the root logger's level and format.
59
+
60
+ debug: when True, sets the level to DEBUG instead of INFO.
61
+ """
62
+ level = logging.DEBUG if debug else logging.INFO
63
+ logging.basicConfig(level=level, format="%(levelname)s: %(message)s", force=True)
64
+
65
+
66
+ # Actions registry, populated by the @action decorator and read by run_action()
67
+ actions = {}
68
+
69
+
70
+ def action(func):
71
+ """Register func as a named CLI action, keyed by its function name."""
72
+ actions[func.__name__] = func
73
+
74
+ return func
75
+
76
+
77
+ # Shortform functions for particular shells or invocation types
78
+ def bash(cmd, **kwargs):
79
+ """Run cmd as a bash script, via exec_cmd's interpreter mode."""
80
+ return exec_cmd(cmd, interpreter="bash", **kwargs)
81
+
82
+
83
+ def pwsh(cmd, **kwargs):
84
+ """Run cmd as a PowerShell script, via exec_cmd's interpreter mode."""
85
+ return exec_cmd(cmd, interpreter="pwsh -noni -c -", **kwargs)
86
+
87
+
88
+ def shell(cmd, **kwargs):
89
+ """Run cmd through the system shell (equivalent to subprocess's shell=True)."""
90
+ return exec_cmd(cmd, shell=True, **kwargs)
91
+
92
+
93
+ class ExecStatus:
94
+ """Placeholder result shape for a subprocess run (returncode, stdout)."""
95
+
96
+ def __init__(self):
97
+ self.returncode = None
98
+ self.stdout = None
99
+
100
+
101
+ def exec_cmd(
102
+ cmd, *, shell=False, env=None, interpreter=None, capture=False, allowed_rc=None, ignore_rc=False
103
+ ):
104
+ """Run cmd as a subprocess and return the completed subprocess.run() result.
105
+
106
+ cmd: a list of argv strings, or a single string (split with shlex unless
107
+ shell=True or an interpreter is given, in which case it is passed
108
+ through as-is - as the shell command line, or as the interpreter's
109
+ stdin, respectively).
110
+ shell: run via the system shell (subprocess's shell=True).
111
+ env: extra environment variables to overlay onto the current environment.
112
+ interpreter: a command (e.g. "bash") to run with cmd piped to its stdin,
113
+ instead of executing cmd directly.
114
+ capture: capture stdout instead of letting it flow through to the
115
+ current process's stdout.
116
+ allowed_rc: exit codes that are not considered a failure. Defaults to [0].
117
+ ignore_rc: when True, never raise CommandException regardless of exit code.
118
+ """
119
+ # Validate all incoming arguments up front, so a bad call fails fast with
120
+ # a clear message rather than partway through building subprocess args.
121
+ val_arg(isinstance(cmd, (list, str)), "Invalid type for cmd. Must be a list or string")
122
+ if isinstance(cmd, list):
123
+ val_arg(
124
+ all(isinstance(x, str) for x in cmd),
125
+ "Invalid value for cmd. Some members are not strings",
126
+ )
127
+
128
+ val_arg(isinstance(shell, bool), "Invalid value for shell argument")
129
+ val_arg(isinstance(capture, bool), "Invalid type for capture. Must be bool")
130
+ val_arg(isinstance(interpreter, (str, type(None))), "Invalid interpreter. Must be str or None")
131
+ val_arg(isinstance(env, (dict, type(None))), "Invalid type for env. Must be dict or None")
132
+
133
+ envs = os.environ.copy()
134
+
135
+ if isinstance(env, dict):
136
+ val_arg(all(isinstance(x, str) for x in env.keys()), "env must be a dict str to str")
137
+ val_arg(all(isinstance(x, str) for x in env.values()), "env must be a dict str to str")
138
+
139
+ envs.update(env)
140
+
141
+ val_arg(
142
+ isinstance(allowed_rc, (list, type(None))),
143
+ "Invalid type for allowed_rc. Must be list or None",
144
+ )
145
+
146
+ if allowed_rc is None:
147
+ allowed_rc = [0]
148
+
149
+ if isinstance(allowed_rc, list):
150
+ val_arg(
151
+ all(isinstance(x, int) for x in allowed_rc), "Invalid values in allowed_rc. Must be int"
152
+ )
153
+
154
+ val_arg(isinstance(ignore_rc, bool), "Invalid type for ignore_rc. Must be bool")
155
+
156
+ # Arguments to subprocess.run
157
+ subprocess_args = {
158
+ "env": envs,
159
+ "stdout": None,
160
+ "stderr": subprocess.STDOUT,
161
+ "shell": shell,
162
+ "text": True,
163
+ }
164
+
165
+ # If we're capturing, stdout should come back via pipe instead of
166
+ # flowing through to this process's stdout
167
+ if capture:
168
+ subprocess_args["stdout"] = subprocess.PIPE
169
+
170
+ # If an interpreter is defined, run that instead and feed it cmd as
171
+ # stdin; otherwise cmd is the command to execute directly, with no stdin
172
+ if interpreter is not None and interpreter != "":
173
+ call_args = interpreter
174
+ subprocess_args["input"] = cmd
175
+ else:
176
+ call_args = cmd
177
+ subprocess_args["stdin"] = subprocess.DEVNULL
178
+
179
+ # If we're not using shell interpretation, split a string command into
180
+ # an argv list
181
+ if not shell:
182
+ call_args = shlex.split(call_args) if isinstance(call_args, str) else call_args
183
+
184
+ logger.info("exec_cmd: %s", cmd)
185
+ logger.debug("Call arguments: %s", call_args)
186
+ debug_args = subprocess_args.copy()
187
+ debug_args["env"] = "*hidden*"
188
+ logger.debug("Subprocess args: %s", debug_args)
189
+
190
+ # Run the process. Flush stdout first so interleaved output from the
191
+ # child process (when not captured) stays in the right order
192
+ sys.stdout.flush()
193
+ proc = subprocess.run(call_args, check=False, **subprocess_args)
194
+
195
+ # Treat the exit code as a failure unless it was explicitly allowed or
196
+ # the caller asked to ignore it entirely
197
+ if not ignore_rc and proc.returncode not in allowed_rc:
198
+ # If output was captured, it would otherwise be lost on failure, so
199
+ # print it before raising
200
+ if subprocess_args["stdout"] is not None:
201
+ print(str(proc.stdout), flush=True)
202
+
203
+ raise CommandException(f"Process exited with bad exit code: {proc.returncode}")
204
+
205
+ return proc
206
+
207
+
208
+ def run_action():
209
+ """Parse sys.argv as "<action> [action_arg...]" and dispatch to the registered action.
210
+
211
+ Exits the process (0 on success, 1 on any exception) rather than
212
+ returning, so this is normally the last call in an _entrypoint.py.
213
+ """
214
+ try:
215
+ parser = argparse.ArgumentParser(
216
+ prog="entrypoint", description="entrypoint", exit_on_error=False
217
+ )
218
+
219
+ parser.add_argument(
220
+ "-v", "-d", action="store_true", dest="debug", help="Verbose/debug output"
221
+ )
222
+
223
+ parser.add_argument("action", action="store", help="Action to perform")
224
+
225
+ parser.add_argument(
226
+ "action_arg",
227
+ action="store",
228
+ help="Optional argument to the action",
229
+ default="",
230
+ nargs=argparse.REMAINDER,
231
+ )
232
+
233
+ args = parser.parse_args()
234
+
235
+ # Honour -v/-d immediately, so debug-level logging covers the
236
+ # action dispatch below too
237
+ configure_logging(debug=args.debug)
238
+
239
+ # Make sure we have an action, and that it is a known one
240
+ if args.action is None or args.action == "":
241
+ raise ArgumentException("Invalid or missing action")
242
+
243
+ if args.action not in actions:
244
+ raise ArgumentException(f"Unknown action {args.action}")
245
+
246
+ # Run the action, passing the joined action argument only if the
247
+ # action function accepts one
248
+ target = actions[args.action]
249
+ if len(inspect.signature(target).parameters) > 0:
250
+ target(" ".join(args.action_arg))
251
+ else:
252
+ target()
253
+
254
+ sys.exit(0)
255
+
256
+ except Exception as e: # pylint: disable=broad-except
257
+ sys.stdout.flush()
258
+ print(e, flush=True)
259
+ sys.exit(1)
260
+
261
+
262
+ # Build helpers
263
+ class ContainerSession:
264
+ """Builds, tags, logs in to a registry for, and pushes a container image."""
265
+
266
+ def __init__(self, container_image, docker_file, container_dir):
267
+ val_arg(isinstance(container_image, str), "Invalid container_image argument. Must be str")
268
+ val_arg(container_image != "", "Empty container_image argument")
269
+ val_arg(isinstance(docker_file, str), "Invalid docker_file argument. Must be str")
270
+ val_arg(docker_file != "", "Empty docker_file argument")
271
+ val_arg(isinstance(container_dir, str), "Invalid container_dir argument. Must be str")
272
+ val_arg(container_dir != "", "Empty container_dir argument")
273
+
274
+ self.engine = "docker"
275
+ self.docker_file = docker_file
276
+ self.container_dir = container_dir
277
+ self.container_image = container_image
278
+ self.build_args = []
279
+ self.tags = []
280
+ self.other_build_args = ""
281
+
282
+ def build(self):
283
+ """Build the image, tagged with every entry in self.tags."""
284
+ cmd = [f"{self.engine} build -f {self.docker_file} {self.container_dir}"]
285
+ cmd = cmd + [f"--build-arg {x}" for x in self.build_args]
286
+ cmd = cmd + [f"--tag {self.container_image}:{x}" for x in self.tags]
287
+ cmd = cmd + [self.other_build_args]
288
+
289
+ bash(" ".join(cmd))
290
+
291
+ def login(self, registry, username, password):
292
+ """Log the container engine in to registry with username/password."""
293
+ bash(
294
+ f"{self.engine} login --password-stdin"
295
+ f' -u "{username}"'
296
+ f' "{registry}" <'
297
+ ' <(echo "$REGISTRY_PASSWORD")',
298
+ env={"REGISTRY_PASSWORD": password},
299
+ )
300
+
301
+ def push(self):
302
+ """Push every tag in self.tags to the registry."""
303
+ for tag in self.tags:
304
+ bash(f"{self.engine} push {self.container_image}:{tag}")
305
+
306
+
307
+ class PythonSession:
308
+ """Builds and publishes a Python package to PyPI via a dedicated venv."""
309
+
310
+ def __init__(self):
311
+ self.venv = "venv"
312
+ self.dist = "dist"
313
+ self.requirements = "requirements.txt"
314
+
315
+ def setup(self):
316
+ """Create the venv and install build tooling, plus self.requirements if present."""
317
+ bash(
318
+ f"python3 -m venv {self.venv} && "
319
+ f"source {self.venv}/bin/activate && "
320
+ "python3 -m pip install --upgrade pip && "
321
+ "python3 -m pip install --upgrade setuptools build twine"
322
+ )
323
+
324
+ if os.path.isfile(self.requirements):
325
+ bash(
326
+ f"source {self.venv}/bin/activate && "
327
+ f"python3 -m pip install -r {self.requirements}"
328
+ )
329
+
330
+ def build(self):
331
+ """Build the sdist/wheel into self.dist."""
332
+ bash(f"source {self.venv}/bin/activate && " "python3 -m build")
333
+
334
+ def clean_venv(self):
335
+ """Remove the venv directory."""
336
+ bash(f"rm -rf {self.venv}")
337
+
338
+ def clean_dist(self):
339
+ """Remove the dist directory."""
340
+ bash(f"rm -rf {self.dist}")
341
+
342
+ def publish(self, username, password):
343
+ """Upload everything in self.dist to PyPI via twine."""
344
+ bash(
345
+ "source ./venv/bin/activate && " f"python3 -m twine upload {self.dist}/*",
346
+ env={"TWINE_USERNAME": username, "TWINE_PASSWORD": password},
347
+ )
348
+
349
+
350
+ class DeployEnvironment:
351
+ """One environment in a DeploySession's promotion chain."""
352
+
353
+ def __init__(self, name):
354
+ self.name = name
355
+ self.next_env = ""
356
+
357
+
358
+ class DeploySession:
359
+ """Models an environment promotion chain (e.g. dev -> test -> prod) and opens promotion PRs."""
360
+
361
+ def __init__(self):
362
+ self._environments = {}
363
+
364
+ def define_env(self, env_name, *, next_env=""):
365
+ """Add env_name to the chain, promoting to next_env (or "" if it is the last)."""
366
+ self._environments[env_name] = DeployEnvironment(env_name)
367
+ self._environments[env_name].next_env = next_env
368
+
369
+ def get_env(self, env_name):
370
+ """Look up a previously defined environment by name."""
371
+ if env_name not in self._environments:
372
+ raise DeployError(f"Environment does not exist: {env_name}")
373
+
374
+ return self._environments[env_name]
375
+
376
+ def promote_forgejo(self, env_name, *, server_url, repo, promote_token):
377
+ """Open a Forgejo/Gitea pull request from env_name's branch to its next environment."""
378
+ val_arg(isinstance(env_name, str), "Invalid env name parameter. Must be str")
379
+ val_arg(isinstance(server_url, str), "Invalid server url parameter. Must be str")
380
+ val_arg(isinstance(repo, str), "Invalid repo parameter. Must be str")
381
+ val_arg(isinstance(promote_token, str), "Invalid promote token parameter. Must be str")
382
+
383
+ val_arg(env_name != "", "Empty env name supplied")
384
+ val_arg(server_url != "", "Empty server url")
385
+ val_arg(repo != "", "Empty repo parameter")
386
+ val_arg(promote_token != "", "Empty promote token")
387
+
388
+ # Make sure the local repo knows about every branch before we try to
389
+ # open a PR between two of them. Best effort - a stale remote-tracking
390
+ # branch list isn't worth failing the whole promotion over.
391
+ bash("git fetch --all", ignore_rc=True)
392
+
393
+ env = self.get_env(env_name)
394
+ next_env = env.next_env
395
+
396
+ # Nothing to do if this is the last environment in the chain
397
+ if next_env == "":
398
+ logger.info("No next environment to promote to")
399
+ return
400
+
401
+ headers = {
402
+ "Authorization": f"token {promote_token}",
403
+ "Content-Type": "application/json",
404
+ }
405
+
406
+ body = textwrap.dedent(f"""\
407
+ {{
408
+ "title": "Promote { env.name } to { next_env }",
409
+ "base": "{ next_env }",
410
+ "head": "{ env.name }",
411
+ "description": "Promote { env.name } to { next_env }"
412
+ }}
413
+ """)
414
+
415
+ args = {
416
+ "url": f"{server_url}/api/v1/repos/{repo}/pulls",
417
+ "method": "post",
418
+ "body": body,
419
+ "headers": headers,
420
+ "verify": False,
421
+ # Creating a PR that already exists returns 409, which is fine
422
+ "status_check": [201, 409],
423
+ }
424
+
425
+ logger.debug("Url args: %s", args)
426
+ Util.url_request(**args)
427
+
428
+ def promote_github(self, env_name, *, repo, promote_token):
429
+ """Open a GitHub pull request from env_name's branch to its next environment."""
430
+ val_arg(isinstance(env_name, str), "Invalid env name parameter. Must be str")
431
+ val_arg(isinstance(repo, str), "Invalid repo parameter. Must be str")
432
+ val_arg(isinstance(promote_token, str), "Invalid promote token parameter. Must be str")
433
+
434
+ val_arg(env_name != "", "Empty env name supplied")
435
+ val_arg(repo != "", "Empty repo parameter")
436
+ val_arg(promote_token != "", "Empty promote token")
437
+
438
+ # Make sure the local repo knows about every branch before we try to
439
+ # open a PR between two of them. Best effort - a stale remote-tracking
440
+ # branch list isn't worth failing the whole promotion over.
441
+ bash("git fetch --all", ignore_rc=True)
442
+
443
+ env = self.get_env(env_name)
444
+ next_env = env.next_env
445
+
446
+ # Nothing to do if this is the last environment in the chain
447
+ if next_env == "":
448
+ logger.info("No next environment to promote to")
449
+ return
450
+
451
+ headers = {
452
+ "Accept": "application/vnd.github.v3+json",
453
+ "Authorization": f"token {promote_token}",
454
+ "Content-Type": "application/json",
455
+ "X-GitHub-Api-Version": "2022-11-28",
456
+ }
457
+
458
+ body = json.dumps(
459
+ {
460
+ "title": f"Promote {env.name} to {next_env}",
461
+ "base": next_env,
462
+ "head": env.name,
463
+ "body": f"Promote {env.name} to {next_env}",
464
+ }
465
+ )
466
+
467
+ args = {
468
+ "url": f"https://api.github.com/repos/{repo}/pulls",
469
+ "method": "post",
470
+ "body": body,
471
+ "headers": headers,
472
+ # Creating a PR that already exists returns 422, which is fine
473
+ "status_check": [201, 422],
474
+ }
475
+
476
+ logger.debug("Url args: %s", args)
477
+ Util.url_request(**args)
478
+
479
+
480
+ # Regex for identifying and splitting semver strings
481
+ # Reference: https://semver.org/
482
+ _SEMVER_REGEX = (
483
+ r"^(?P<major>0|[1-9]\d*)\.(?P<minor>0|[1-9]\d*)\."
484
+ r"(?P<patch>0|[1-9]\d*)(?:-(?P<prerelease>"
485
+ r"(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)"
486
+ r"(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?"
487
+ r"(?:\+(?P<buildmetadata>[0-9a-zA-Z-]+"
488
+ r"(?:\.[0-9a-zA-Z-]+)*))?$"
489
+ )
490
+
491
+
492
+ class BuildSession:
493
+ """Parses a semver version out of one or more candidate version sources."""
494
+
495
+ def __init__(self, version_sources=None):
496
+ if version_sources is None:
497
+ logger.info("Using default version: v0.1.0")
498
+ version_sources = ["v0.1.0"]
499
+ elif not isinstance(version_sources, list):
500
+ version_sources = [version_sources]
501
+
502
+ self.update_version(version_sources)
503
+
504
+ def update_version(self, sources, *, required=True, discard_regex=None, ignore_regex=None):
505
+ """Find the first source that semver-matches and populate self.v_* from it.
506
+
507
+ sources: candidate version strings to try, in order.
508
+ required: raise VersionParseError if none of them match.
509
+ discard_regex: regexes stripped from a source and *not* considered
510
+ part of the version string (e.g. a "refs/tags/" ref prefix).
511
+ Defaults to ["^refs/tags/"].
512
+ ignore_regex: regexes stripped before the semver check, but still
513
+ considered part of the version string (e.g. a "v" tag prefix).
514
+ Defaults to ["^v"].
515
+ """
516
+ val_arg(isinstance(required, bool), "required parameter must be bool")
517
+ val_arg(isinstance(sources, list), "Sources parameter must be a list of strings")
518
+ val_arg(all(isinstance(x, str) for x in sources), "Some values in source are not strings")
519
+ val_arg(
520
+ isinstance(discard_regex, (list, type(None))),
521
+ "discard_regex parameter must be list of string or None",
522
+ )
523
+
524
+ if discard_regex is None:
525
+ discard_regex = ["^refs/tags/"]
526
+
527
+ if ignore_regex is None:
528
+ ignore_regex = ["^v"]
529
+
530
+ for source in sources:
531
+ logger.info("Checking %s", source)
532
+
533
+ # Strip any 'discard' components - these are not part of the
534
+ # version string at all (e.g. a git ref prefix)
535
+ post_discard_source = source
536
+ for regex_item in discard_regex:
537
+ post_discard_source = re.sub(regex_item, "", post_discard_source)
538
+
539
+ logger.debug("Source after discard strip: %s", post_discard_source)
540
+
541
+ # Strip any 'ignore' components - these are part of the version
542
+ # string, but not part of the semver check itself (e.g. a "v" prefix)
543
+ post_ignore_source = post_discard_source
544
+ for regex_item in ignore_regex:
545
+ post_ignore_source = re.sub(regex_item, "", post_ignore_source)
546
+
547
+ logger.debug("Source after ignore strip: %s", post_ignore_source)
548
+
549
+ result = re.match(_SEMVER_REGEX, post_ignore_source)
550
+ if result is None:
551
+ logger.debug("Source (%s) is not a match", post_ignore_source)
552
+ continue
553
+
554
+ logger.info("Semver match on %s", post_ignore_source)
555
+
556
+ # Populate the version components from this match
557
+ self.v_source = source
558
+ self.v_stripped = post_discard_source
559
+ self.v_base = post_ignore_source
560
+ self.v_full = "" if result[0] is None else result[0]
561
+ self.v_major = "" if result[1] is None else result[1]
562
+ self.v_minor = "" if result[2] is None else result[2]
563
+ self.v_patch = "" if result[3] is None else result[3]
564
+ self.v_prerelease = "" if result[4] is None else result[4]
565
+ self.v_buildmeta = "" if result[5] is None else result[5]
566
+ self.v_is_prerelease = result[4] is not None
567
+
568
+ # Build the major[.minor[.patch]] string, stopping at the first
569
+ # component that is missing
570
+ self.v_mmp = self.v_major
571
+ if self.v_mmp != "" and self.v_minor != "":
572
+ self.v_mmp = self.v_mmp + f".{self.v_minor}"
573
+
574
+ if self.v_patch != "":
575
+ self.v_mmp = self.v_mmp + f".{self.v_patch}"
576
+
577
+ return
578
+
579
+ # None of the sources matched
580
+ if required:
581
+ raise VersionParseError("No semver matches found")
582
+
583
+
584
+ class TestingSession:
585
+ """Runs a list of shell commands and fails the build if any of them fail."""
586
+
587
+ def __init__(self, testing_commands=None):
588
+ val_arg(
589
+ isinstance(testing_commands, (list, type(None))),
590
+ "Invalid testing commands argument. Must be list or None",
591
+ )
592
+
593
+ self.testing_commands = testing_commands if testing_commands else []
594
+
595
+ def run(self):
596
+ """Run every testing command, then fail the build if any of them failed."""
597
+ result = [bash(x, ignore_rc=True) for x in self.testing_commands]
598
+
599
+ if any(x.returncode for x in result):
600
+ Util.fail("Some testing commands failed")
601
+
602
+
603
+ class LintingSession:
604
+ """Runs a list of shell commands and fails the build if any of them fail."""
605
+
606
+ def __init__(self, linting_commands=None):
607
+ val_arg(
608
+ isinstance(linting_commands, (list, type(None))),
609
+ "Invalid linting commands argument. Must be list or None",
610
+ )
611
+
612
+ self.linting_commands = linting_commands if linting_commands else []
613
+
614
+ def run(self):
615
+ """Run every linting command, then fail the build if any of them failed."""
616
+ result = [bash(x, ignore_rc=True) for x in self.linting_commands]
617
+
618
+ if any(x.returncode for x in result):
619
+ Util.fail("Some linting commands failed")
620
+
621
+
622
+ # Number of attempts, and the backoff schedule between them, for Util.url_request's
623
+ # retry of transient HTTP failures (connection errors, timeouts, 5xx/429 responses)
624
+ _URL_REQUEST_MAX_ATTEMPTS = 4
625
+ _URL_REQUEST_INITIAL_BACKOFF_SECONDS = 1.0
626
+ _URL_REQUEST_BACKOFF_MULTIPLIER = 2.0
627
+
628
+ # Status codes that are treated as transient (worth retrying) when they are
629
+ # not already an explicitly accepted status_check value
630
+ _RETRYABLE_STATUS_CODES = {429, 500, 502, 503, 504}
631
+
632
+
633
+ class Util:
634
+ """Assorted helpers: failing a build, git metadata, GitHub releases, HTTP requests."""
635
+
636
+ @classmethod
637
+ def fail(cls, message):
638
+ """Raise BuildFailure(message)."""
639
+ raise BuildFailure(message)
640
+
641
+ @classmethod
642
+ def git_sha(cls):
643
+ """Return the current commit's abbreviated SHA."""
644
+ return exec_cmd("git log -1 --format=%h", capture=True).stdout
645
+
646
+ @classmethod
647
+ def git_latest_tag(cls):
648
+ """Return the most recent tag reachable from HEAD, or "" if there is none."""
649
+ return bash('git describe --tags --abbrev=0 2>/dev/null || echo ""', capture=True).stdout
650
+
651
+ @classmethod
652
+ def git_list_tags(cls):
653
+ """Return every tag in the repo, sorted by version."""
654
+ return exec_cmd("git tag --sort v:refname", capture=True)
655
+
656
+ @classmethod
657
+ def git_notes_since_tag(cls, tag=None):
658
+ """Return every non-merge commit subject since tag (the whole history if tag is empty)."""
659
+ if tag is None or tag == "":
660
+ return bash("git log --no-merges --format=%s HEAD", capture=True).stdout
661
+
662
+ return bash(f'git log --no-merges --format=%s HEAD "^{tag}"', capture=True).stdout
663
+
664
+ @classmethod
665
+ def url_request(
666
+ cls, url, method="get", headers=None, body=None, verify=True, status_check=None
667
+ ):
668
+ """Make an HTTP request, retrying transient failures with backoff.
669
+
670
+ url/method/headers/body/verify: passed through to requests.request.
671
+ status_check: an int or list of ints that are the only acceptable
672
+ response status codes. Defaults to requests' own
673
+ raise_for_status() behaviour (anything 4xx/5xx raises).
674
+
675
+ A connection error, timeout, or a 5xx/429 response that is not
676
+ itself an accepted status_check value is retried up to
677
+ _URL_REQUEST_MAX_ATTEMPTS times with exponential backoff; any other
678
+ failure (e.g. a 404, or a 4xx that status_check didn't accept) is
679
+ not retried, since a retry would not change the outcome.
680
+ """
681
+ val_arg(isinstance(url, str), "Invalid url. Must be string")
682
+ val_arg(isinstance(method, str), "Invalid method. Must be string")
683
+ val_arg(isinstance(body, (str, type(None))), "Invalid body. Must be None or str")
684
+ val_arg(isinstance(verify, bool), "Invalid verify parameter. Must be bool")
685
+ val_arg(
686
+ isinstance(status_check, (list, int, type(None))),
687
+ "Invalid status_check parameter. Must be list, int or None",
688
+ )
689
+
690
+ # Wrap a single int in a list, so the rest of this method only has
691
+ # to deal with one shape
692
+ if isinstance(status_check, int):
693
+ status_check = [status_check]
694
+
695
+ if status_check is not None:
696
+ val_arg(
697
+ all(isinstance(x, int) for x in status_check),
698
+ "Invalid values in status check. Must be int",
699
+ )
700
+
701
+ if headers is None:
702
+ headers = {}
703
+
704
+ val_arg(isinstance(headers, dict), "Invalid headers. Must be dict type")
705
+
706
+ for key, value in headers.items():
707
+ val_arg(isinstance(key, str), "Invalid keys in headers. Must be string")
708
+ val_arg(isinstance(value, str), "Invalid values in headers. Must be string")
709
+
710
+ request_args = {
711
+ "method": method,
712
+ "url": url,
713
+ "timeout": (10, 30),
714
+ "headers": headers,
715
+ "verify": verify,
716
+ }
717
+
718
+ if body is not None:
719
+ request_args["data"] = body
720
+
721
+ backoff_seconds = _URL_REQUEST_INITIAL_BACKOFF_SECONDS
722
+ last_exception = None
723
+
724
+ for attempt in range(1, _URL_REQUEST_MAX_ATTEMPTS + 1):
725
+ try:
726
+ response = requests.request(**request_args)
727
+ except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
728
+ # A connection-level failure is always worth retrying
729
+ last_exception = e
730
+ logger.warning(
731
+ "Request attempt %d/%d failed: %s", attempt, _URL_REQUEST_MAX_ATTEMPTS, e
732
+ )
733
+ else:
734
+ logger.debug("Response code: %s", response.status_code)
735
+ logger.debug("Response text: %s", response.text)
736
+
737
+ # An explicitly accepted status is never retried, even if it
738
+ # would otherwise look like a transient failure (e.g. a 409
739
+ # from an already-open PR)
740
+ if status_check is not None and response.status_code in status_check:
741
+ return response
742
+
743
+ if response.status_code not in _RETRYABLE_STATUS_CODES:
744
+ # Not retryable - resolve via status_check or the
745
+ # library's default raise_for_status() handling
746
+ if status_check is None:
747
+ response.raise_for_status()
748
+ return response
749
+
750
+ raise requests.HTTPError(
751
+ f"Status code ({response.status_code}) not in {status_check}"
752
+ )
753
+
754
+ last_exception = requests.HTTPError(
755
+ f"Transient status code: {response.status_code}"
756
+ )
757
+ logger.warning(
758
+ "Request attempt %d/%d got retryable status %d",
759
+ attempt,
760
+ _URL_REQUEST_MAX_ATTEMPTS,
761
+ response.status_code,
762
+ )
763
+
764
+ # Out of attempts - propagate whatever the last failure was
765
+ if attempt == _URL_REQUEST_MAX_ATTEMPTS:
766
+ raise last_exception
767
+
768
+ time.sleep(backoff_seconds)
769
+ backoff_seconds *= _URL_REQUEST_BACKOFF_MULTIPLIER
770
+
771
+ # Unreachable: the loop above always returns or raises
772
+ raise last_exception
773
+
774
+ @classmethod
775
+ def github_release(cls, tag_name, *, name, prerelease, github_token, repo):
776
+ """Create a GitHub release for tag_name."""
777
+ val_arg(isinstance(tag_name, str), "Invalid tag name parameter. Must be str")
778
+ val_arg(isinstance(name, str), "Invalid name parameter. Must be str")
779
+ val_arg(isinstance(prerelease, bool), "Invalid prerelease parameter. Must be bool")
780
+ val_arg(isinstance(github_token, str), "Invalid github token parameter. Must be str")
781
+ val_arg(isinstance(repo, str), "Invalid repo parameter. Must be str")
782
+
783
+ val_arg(tag_name != "", "Empty tag name supplied")
784
+ val_arg(name != "", "Empty name supplied")
785
+ val_arg(github_token != "", "Empty github token")
786
+ val_arg(repo != "", "Empty repo parameter")
787
+
788
+ headers = {
789
+ "Accept": "application/vnd.github.v3+json",
790
+ "Authorization": f"token {github_token}",
791
+ "Content-Type": "application/json",
792
+ "X-GitHub-Api-Version": "2022-11-28",
793
+ }
794
+
795
+ body = json.dumps(
796
+ {
797
+ "tag_name": tag_name,
798
+ "name": name,
799
+ "draft": False,
800
+ "prerelease": prerelease,
801
+ "generate_release_notes": True,
802
+ }
803
+ )
804
+
805
+ args = {
806
+ "url": f"https://api.github.com/repos/{repo}/releases",
807
+ "method": "post",
808
+ "body": body,
809
+ "headers": headers,
810
+ "status_check": [201],
811
+ }
812
+
813
+ logger.debug("Url args: %s", args)
814
+ Util.url_request(**args)
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.4
2
+ Name: rsbt
3
+ Version: 0.1.1
4
+ Summary: Really Simple Build Tool - a small library of CI/CD build, test and release helpers
5
+ Description-Content-Type: text/markdown
6
+ License-File: LICENSE
7
+ Requires-Dist: requests>=2.32.3
8
+ Dynamic: description
9
+ Dynamic: description-content-type
10
+ Dynamic: license-file
11
+ Dynamic: requires-dist
12
+ Dynamic: summary
13
+
14
+ # rsbt
15
+
16
+ Really Simple Build Tool - a small Python library of helpers for writing
17
+ CI/CD build, test, lint, release and deploy pipelines as plain Python
18
+ scripts.
19
+
20
+
21
+ ## What it provides
22
+
23
+ - `action` / `run_action()` - register functions as named CLI actions and
24
+ dispatch to them from `sys.argv`, so an `_entrypoint.py` can expose
25
+ `build`, `test`, `lint`, `release`, etc. as subcommands.
26
+ - `exec_cmd` / `bash` / `pwsh` / `shell` - run subprocesses with consistent
27
+ logging, exit-code handling and output capture.
28
+ - `PythonSession` - build and publish a Python package to PyPI.
29
+ - `ContainerSession` - build, tag, log in to a registry and push a
30
+ container image.
31
+ - `TestingSession` / `LintingSession` - run a list of shell commands and
32
+ fail the build if any of them fail.
33
+ - `BuildSession` - parse a semver version out of one or more candidate
34
+ sources (a git tag, a `GITHUB_REF`, a fallback string).
35
+ - `DeploySession` - model an environment promotion chain (e.g.
36
+ `dev -> test -> prod`) and open the promotion pull request on GitHub or
37
+ Forgejo/Gitea.
38
+ - `Util` - assorted helpers: git metadata, GitHub releases, and an HTTP
39
+ request helper with built-in retry/backoff for transient failures.
40
+
41
+ See [`src/rsbt/__init__.py`](src/rsbt/__init__.py) for the full API, this
42
+ repo's own [`_entrypoint.py`](_entrypoint.py) for a worked example of
43
+ building/testing/releasing a PyPI package with it, and
44
+ [`examples/`](examples/) for fuller, reference-only examples of the other
45
+ session types (container images, environment promotion).
46
+
47
+ ## Examples
48
+
49
+ A consuming repo's `_entrypoint.py` registers its pipeline steps as
50
+ actions and ends with `rsbt.run_action()`, which dispatches
51
+ `./entrypoint <action>` to the matching function.
52
+
53
+ ### A simple Python build
54
+
55
+ ```python
56
+ import os
57
+
58
+ import rsbt
59
+ from rsbt import action, Util
60
+
61
+ bs = rsbt.BuildSession([f"0.1.0-rolling+{Util.git_sha()}"])
62
+ pys = rsbt.PythonSession()
63
+
64
+
65
+ @action
66
+ def build():
67
+ os.environ["BUILD_VERSION"] = bs.v_mmp
68
+ pys.setup()
69
+ pys.build()
70
+
71
+
72
+ @action
73
+ def release():
74
+ bs.update_version([os.environ["GITHUB_REF"]])
75
+ build()
76
+ pys.publish("__token__", os.environ["PYPI_TOKEN"])
77
+
78
+
79
+ rsbt.run_action()
80
+ ```
81
+
82
+ ### A simple Docker build
83
+
84
+ ```python
85
+ import os
86
+
87
+ import rsbt
88
+ from rsbt import action
89
+
90
+ cs = rsbt.ContainerSession("myorg/myimage", "src/Dockerfile", "src")
91
+
92
+
93
+ @action
94
+ def build():
95
+ cs.tags = ["latest"]
96
+ cs.build()
97
+
98
+
99
+ @action
100
+ def push():
101
+ build()
102
+ cs.login(
103
+ os.environ["REGISTRY_URL"],
104
+ os.environ["REGISTRY_USERNAME"],
105
+ os.environ["REGISTRY_PASSWORD"],
106
+ )
107
+ cs.push()
108
+
109
+
110
+ rsbt.run_action()
111
+ ```
112
+
113
+ ### A simple deployment
114
+
115
+ ```python
116
+ import os
117
+
118
+ import rsbt
119
+ from rsbt import action
120
+
121
+ ds = rsbt.DeploySession()
122
+ ds.define_env("dev", next_env="prod")
123
+ ds.define_env("prod")
124
+
125
+
126
+ @action
127
+ def apply():
128
+ env_name = os.environ["DEPLOY_ENV"]
129
+ rsbt.bash(f"ansible-playbook -i inventory/{env_name} site.yml")
130
+
131
+
132
+ @action
133
+ def promote():
134
+ ds.promote_github(
135
+ os.environ["DEPLOY_ENV"],
136
+ repo=os.environ["GITHUB_REPOSITORY"],
137
+ promote_token=os.environ["PROMOTE_TOKEN"],
138
+ )
139
+
140
+
141
+ rsbt.run_action()
142
+ ```
143
+
144
+ ## Self-hosting
145
+
146
+ `rsbt` builds, tests and releases itself using itself: `requirements.txt`
147
+ installs this checkout in editable mode (`-e .`), so `_entrypoint.py`'s
148
+ `import rsbt` always resolves to the current working tree rather than a
149
+ previously published release. This keeps the self-hosted pipeline honest -
150
+ it always exercises the code that is actually being shipped.
151
+
152
+ ## Installing
153
+
154
+ ```
155
+ pip install rsbt
156
+ ```
157
+
158
+ ## Development
159
+
160
+ `./entrypoint build|test|lint|release` runs the build, test, lint and
161
+ release actions defined in `_entrypoint.py`. `test` builds and runs
162
+ `src/Dockerfile`'s `testing` stage in a container, so the test suite runs
163
+ in a disposable, reproducible environment rather than directly on the
164
+ host.
@@ -0,0 +1,10 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ src/rsbt/__init__.py
6
+ src/rsbt.egg-info/PKG-INFO
7
+ src/rsbt.egg-info/SOURCES.txt
8
+ src/rsbt.egg-info/dependency_links.txt
9
+ src/rsbt.egg-info/requires.txt
10
+ src/rsbt.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ requests>=2.32.3
@@ -0,0 +1 @@
1
+ rsbt