dev-isolator 0.1.0__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.
Files changed (38) hide show
  1. dev_isolator/__init__.py +13 -0
  2. dev_isolator/__main__.py +15 -0
  3. dev_isolator/base_image.py +429 -0
  4. dev_isolator/config.py +650 -0
  5. dev_isolator/constants.py +58 -0
  6. dev_isolator/container_image.py +302 -0
  7. dev_isolator/container_manager.py +516 -0
  8. dev_isolator/data/Containerfile +32 -0
  9. dev_isolator/data/addons/addon.claude.jinja2 +16 -0
  10. dev_isolator/data/addons/addon.opencode.jinja2 +16 -0
  11. dev_isolator/data/addons/config.claude.yaml +292 -0
  12. dev_isolator/data/addons/config.opencode.py +4 -0
  13. dev_isolator/data/addons/config.opencode.yaml +8 -0
  14. dev_isolator/data/base/Containerfile.almalinux-10 +5 -0
  15. dev_isolator/data/base/Containerfile.almalinux-9 +5 -0
  16. dev_isolator/data/base/Containerfile.archlinux +6 -0
  17. dev_isolator/data/base/Containerfile.debian-13 +6 -0
  18. dev_isolator/data/base/Containerfile.fedora-43 +5 -0
  19. dev_isolator/data/base/Containerfile.fedora-44 +5 -0
  20. dev_isolator/data/base/Containerfile.fedora-45 +5 -0
  21. dev_isolator/data/base/Containerfile.fedora-rawhide +6 -0
  22. dev_isolator/data/base/Containerfile.opensuse-leap +4 -0
  23. dev_isolator/data/base/Containerfile.opensuse-tumbleweed +5 -0
  24. dev_isolator/data/base/Containerfile.ubuntu-22.04 +6 -0
  25. dev_isolator/data/base/Containerfile.ubuntu-24.04 +7 -0
  26. dev_isolator/data/base/Containerfile.ubuntu-26.04 +8 -0
  27. dev_isolator/data/config.yaml +136 -0
  28. dev_isolator/data/setup/add_user.containerfile.jinja2 +36 -0
  29. dev_isolator/main.py +931 -0
  30. dev_isolator/podman_utils.py +116 -0
  31. dev_isolator/utils.py +86 -0
  32. dev_isolator/waitspinner.py +115 -0
  33. dev_isolator-0.1.0.dist-info/METADATA +131 -0
  34. dev_isolator-0.1.0.dist-info/RECORD +38 -0
  35. dev_isolator-0.1.0.dist-info/WHEEL +5 -0
  36. dev_isolator-0.1.0.dist-info/entry_points.txt +3 -0
  37. dev_isolator-0.1.0.dist-info/licenses/LICENSE +674 -0
  38. dev_isolator-0.1.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,58 @@
1
+ """Constants shared across the dev-isolator modules.
2
+
3
+ Copyright (C) 2026 Martin Köhler
4
+
5
+ This program comes with ABSOLUTELY NO WARRANTY.
6
+ This is free software, and you are welcome to redistribute it
7
+ under certain conditions; see LICENSE for details.
8
+ SPDX-License-Identifier: GPL-3.0-or-later
9
+ """
10
+
11
+ from pathlib import Path
12
+
13
+ #: Repository part of the images built for a project (the image name
14
+ #: is ``dev-isolator:<slug_of_the_project_path>--<tag>``).
15
+ IMAGE_PREFIX = "dev-isolator"
16
+
17
+ #: Length of the random suffix of created container names, so several
18
+ #: containers of the same project can run in parallel.
19
+ CONTAINER_NAME_SUFFIX_LENGTH = 8
20
+
21
+ #: Directory holding the templates shipped with dev-isolator (the
22
+ #: jinja2 Containerfile templates).
23
+ TEMPLATES_DIR = Path(__file__).parent / "data" / "setup"
24
+
25
+ #: Directory holding the addons shipped with dev-isolator (the
26
+ #: jinja2 Containerfile templates).
27
+ ADDON_DIR = Path(__file__).parent / "data" / "addons"
28
+
29
+
30
+ #: Directory bundled with dev-isolator holding the default
31
+ #: ``Containerfile``, the addon templates and the addon configs.
32
+ BUNDLE_DIR = Path(__file__).parent / "data"
33
+
34
+ #: Directory inside a project that holds the project-specific
35
+ #: Containerfile and configuration.
36
+ DEV_ISOLATOR_DIR = ".devisolator"
37
+
38
+ #: File name of the main configuration file (enabled addons,
39
+ #: environment and volumes).
40
+ CONFIG_FILE_NAME = "config.yaml"
41
+
42
+ #: Required version identifier of ``config.yaml``. Loading a
43
+ #: configuration with a different ``version`` value raises an error.
44
+ CONFIG_VERSION = "0.1"
45
+
46
+ #: File name prefix and suffix of a per-addon configuration file:
47
+ #: ``config.<addon_name>.yaml``.
48
+ ADDON_CONFIG_FILE_PREFIX = "config."
49
+ ADDON_CONFIG_FILE_SUFFIX = ".yaml"
50
+
51
+ #: File name prefix and suffix of an addon template:
52
+ #: ``addon.<name>.jinja2``.
53
+ ADDON_FILE_PREFIX = "addon."
54
+ ADDON_FILE_SUFFIX = ".jinja2"
55
+
56
+ #: Name of the default base image referenced by ``di init --base``
57
+ #: (as written in a generated project ``Containerfile``).
58
+ DEFAULT_BASE = "ubuntu:26.04"
@@ -0,0 +1,302 @@
1
+ """Write and build the project image's Containerfile (ContainerImage).
2
+
3
+ The project's ``Containerfile`` inside the build context must be based
4
+ on a base image built from the Containerfiles bundled with dev-isolator
5
+ (see :class:`dev_isolator.base_image.BaseImage`): the single ``FROM``
6
+ instruction of the project's Containerfile must reference a base image
7
+ such as ``ubuntu:26.04``.
8
+
9
+ When the project image is built, the merged Containerfile (the project
10
+ Containerfile plus the trailing workdir block: ``USER`` of the host user
11
+ and ``WORKDIR /workspace``) is written into the build context and passed
12
+ to ``podman build`` with the project's image tag. By default the build
13
+ context is an empty temporary directory holding only that Containerfile
14
+ (the project sources stay on the host and are mounted at ``/workspace``
15
+ at run time); when ``build.local_context`` is set, the project's own
16
+ context directory is used instead so ``ADD``/``COPY`` instructions can
17
+ read the sources. A previous image replaced by the build is removed
18
+ afterwards (see
19
+ :func:`dev_isolator.podman_utils.remove_superseeded_image`).
20
+
21
+ Copyright (C) 2026 Martin Köhler
22
+
23
+ This program comes with ABSOLUTELY NO WARRANTY.
24
+ This is free software, and you are welcome to redistribute it
25
+ under certain conditions; see LICENSE for details.
26
+ SPDX-License-Identifier: GPL-3.0-or-later
27
+ """
28
+
29
+ import os
30
+ from pathlib import Path
31
+ from .base_image import BaseImage, host_username
32
+ from .podman_utils import get_image_id, remove_superseeded_image
33
+ from .utils import dprint, Verbosity, get_verbosity
34
+ from .waitspinner import WaitSpinner
35
+ from tempfile import mkstemp, TemporaryDirectory
36
+ from tree_sitter import Language, Parser
37
+ import tree_sitter_containerfile
38
+ import podman.errors
39
+ import podman
40
+ import json
41
+ from .podman_utils import replace_from_images
42
+
43
+
44
+ class ContainerImage:
45
+ """Write and build the project image's Containerfile.
46
+
47
+ A ContainerImage is created for a build context together with the
48
+ paths of the project's own ``Containerfile``, the project's
49
+ ``config.yaml`` and the addon search paths. Before anything else,
50
+ the ``FROM`` instruction of the project Containerfile identifies
51
+ the dev-isolator base image to use, and that base image is built
52
+ (see :class:`dev_isolator.base_image.BaseImage`).
53
+
54
+ :attr base_image: The
55
+ :class:`dev_isolator.base_image.BaseImage` this Containerfile
56
+ is based on, created on initialization (built during
57
+ :meth:`build`).
58
+ """
59
+
60
+ def __init__(self, context_dir, container_file, config, image_name):
61
+ """Set up the container file and its base image.
62
+
63
+ :param context_dir: Path to the build context directory; the
64
+ temporary merged Containerfile is written here during the
65
+ build.
66
+ :param container_file: Path to the project's ``Containerfile``
67
+ inside the build context.
68
+ :param config: The project's
69
+ :class:`dev_isolator.config.Configuration`, determining the
70
+ enabled addons of the base image build.
71
+ :param image_name: Tag used for the built project image (see
72
+ :meth:`dev_isolator.container_manager.ContainerDefintion.
73
+ image_name`).
74
+ :raises FileNotFoundError: if ``container_file`` does not
75
+ exist.
76
+ :raises RuntimeError: if the Containerfile does not contain
77
+ exactly one ``FROM`` instruction or does not use a
78
+ dev-isolator image as base.
79
+ """
80
+ self.context_dir = Path(context_dir)
81
+ self.container_file = Path(container_file)
82
+ self.image_name = image_name
83
+ self.config = config
84
+
85
+ if not self.container_file.is_file():
86
+ raise FileNotFoundError(f"Containterfile {self.container_file}"
87
+ " not found.")
88
+
89
+ result = self.get_from_image(self.container_file)
90
+ if len(result) != 1:
91
+ raise RuntimeError("The supplied Containerfile contains more than"
92
+ " one FROM statement.")
93
+ result = result[0]
94
+ base_image_name = result.get("image", "xxx")
95
+ base_image_tag = result.get("tag", None)
96
+
97
+ self.from_image_name = f"{base_image_name}{base_image_tag}"
98
+ self.base_image = BaseImage(self.config)
99
+
100
+ def _write_container_file(self, directory):
101
+ """Write the used Containerfile for the image build.
102
+
103
+ The used Containerfile starts with the content of the
104
+ project's ``Containerfile`` and appends the trailing workdir
105
+ block: a comment marker, the host user as default user (same
106
+ username as on the host, see
107
+ :func:`dev_isolator.base_image.host_username`) and
108
+ ``WORKDIR /workspace``. At ``Verbosity.TRACE`` the content is
109
+ printed to stdout.
110
+
111
+ The file is created directly inside the build context, so
112
+ podman-py does not copy it itself (its own copy,
113
+ ``.containerfile.<random>``, would be left behind as an
114
+ artifact in the build context). The content is fsynced, so it
115
+ reaches disk before podman reads the file during the build.
116
+
117
+ :returns: The tuple ``(fd, temp_container_file)`` of the
118
+ open file descriptor of the written file and its path.
119
+ """
120
+ # Setup final Containerfile
121
+ file_content = self.container_file.read_text(encoding="utf-8")
122
+ file_content = replace_from_images(file_content,
123
+ self.base_image_name)
124
+ file_content = str(file_content)
125
+ file_content += "\n\n# --- workdir ---\n"
126
+ file_content += f"USER {host_username()}\n"
127
+ file_content += "WORKDIR /workspace\n"
128
+
129
+ if get_verbosity() >= Verbosity.TRACE:
130
+ for line in file_content.splitlines():
131
+ print(f"[Containerfile] {line}")
132
+
133
+ fd, temp_name = mkstemp(dir=directory,
134
+ prefix=".containerfile.")
135
+ temp_container_file = Path(temp_name)
136
+ try:
137
+ with os.fdopen(fd, "w", encoding="utf-8") as fp:
138
+ fp.write(file_content)
139
+ # Make sure the content reaches disk before podman
140
+ # reads the file during the build.
141
+ fp.flush()
142
+ os.fsync(fp.fileno())
143
+ except BaseException:
144
+ temp_container_file.unlink(missing_ok=True)
145
+ raise
146
+ return fd, temp_container_file
147
+
148
+ def _safe_container_file(self, content):
149
+ """Keep a generated Containerfile for debugging a failure.
150
+
151
+ Writes ``content`` to the current working directory as
152
+ ``Containerfile-fail-<random>`` and reports the kept name in an
153
+ error message. Used when the image build fails and the build was
154
+ requested with ``keep_container_file=True`` (see
155
+ :meth:`dev_isolator.container_manager.ContainerDefintion.
156
+ build_container`).
157
+ """
158
+ fd, temp_name = mkstemp(dir=os.getcwd(),
159
+ prefix="Containerfile-fail-")
160
+ os.close(fd)
161
+ Path(temp_name).write_text(content, encoding="utf-8")
162
+ dprint(Verbosity.ERROR, "Kept generated Containerfile as "
163
+ f"{temp_name}")
164
+
165
+ def build(self, keep_container_file=False):
166
+ """Build the image defined by this container file.
167
+
168
+ The used Containerfile is written by
169
+ :meth:`_write_container_file` directly into the build
170
+ context, passed to ``podman build`` with the
171
+ ``self.image_name`` tag, and removed again after the build.
172
+
173
+ If an image with the same tag existed before, it is removed
174
+ after the build - but only when the build replaced it, i.e.
175
+ its image id changed - so no old image is left as a dangling
176
+ artifact in podman.
177
+
178
+ :param keep_container_file: Keep the generated Containerfile
179
+ in the current directory when the build fails (see
180
+ :meth:`_safe_container_file`).
181
+ :returns: The built podman image.
182
+ :raises RuntimeError: if the podman build fails.
183
+ """
184
+ tag = self.image_name
185
+ _, self.base_image_name, _ = (self.base_image.build(
186
+ self.from_image_name))
187
+
188
+ if self.config.build_get_local_context():
189
+ temp_dir_object = None
190
+ build_image_dir = self.context_dir
191
+ else:
192
+ temp_dir_object = TemporaryDirectory(ignore_cleanup_errors=True)
193
+ build_image_dir = temp_dir_object.name
194
+
195
+ fd, temp_container_file = self._write_container_file(build_image_dir)
196
+
197
+ dprint(Verbosity.INFO, f"Using build context {build_image_dir}")
198
+ dprint(Verbosity.INFO, "Created temporary Containerfile "
199
+ f"{temp_container_file}")
200
+
201
+ try:
202
+ with podman.PodmanClient() as client:
203
+ previous_id = get_image_id(client, tag)
204
+ dprint(Verbosity.INFO, "Building image ...")
205
+ with WaitSpinner(f"Building image {tag}"):
206
+ image, build_logs = client.images.build(
207
+ path=str(build_image_dir),
208
+ dockerfile=str(temp_container_file),
209
+ tag=tag,
210
+ pull=True,
211
+ nocache=self.config.build_get_nocache()
212
+ )
213
+ remove_superseeded_image(client, previous_id, image.id, tag)
214
+ except podman.errors.BuildError as e:
215
+ if keep_container_file:
216
+ self._safe_container_file(
217
+ temp_container_file.read_text(encoding="utf-8"))
218
+ raise RuntimeError(f"Failed to build image {tag}: {e}") from e
219
+ except podman.errors.APIError as e:
220
+ if keep_container_file:
221
+ self._safe_container_file(
222
+ temp_container_file.read_text(encoding="utf-8"))
223
+ raise RuntimeError(f"Podman API error while building {tag}: {e}") \
224
+ from e
225
+ finally:
226
+ temp_container_file.unlink(missing_ok=True)
227
+ if temp_dir_object is not None:
228
+ temp_dir_object.cleanup()
229
+
230
+ if get_verbosity() >= Verbosity.TRACE:
231
+ for entry in build_logs:
232
+ if isinstance(entry, bytes):
233
+ entry = json.loads(
234
+ entry.decode(errors='replace').strip())
235
+ for stream in entry.get("stream", "").splitlines():
236
+ dprint(Verbosity.TRACE, f"[build] {stream}")
237
+
238
+ dprint(Verbosity.INFO, f"Built image {image.id} tagged {tag}")
239
+ return image
240
+
241
+ def get_from_image(self, filename):
242
+ """Return the ``FROM`` instructions of a Containerfile.
243
+
244
+ Parses ``filename`` with the tree-sitter Containerfile
245
+ grammar and returns one entry per ``FROM`` instruction.
246
+
247
+ :param filename: Path to the Containerfile to parse.
248
+ :returns: A list of dicts with the keys ``image`` (the image
249
+ name without tag), ``tag`` (the ``:tag`` part including
250
+ the colon, or ``None``), ``digest`` (the ``@digest``
251
+ part, or ``None``) and ``alias`` (the name after ``AS``,
252
+ or ``None``).
253
+ """
254
+ source = Path(filename).read_bytes()
255
+ language = Language(tree_sitter_containerfile.language())
256
+ parser = Parser(language)
257
+ tree = parser.parse(source)
258
+
259
+ results = []
260
+
261
+ def visit(node):
262
+ """Append the data of one ``FROM`` instruction (if any)
263
+ and recurse into its children."""
264
+ if node.type == "from_instruction":
265
+ image_spec = next(
266
+ (
267
+ child
268
+ for child in node.named_children
269
+ if child.type == "image_spec"
270
+ ),
271
+ None,
272
+ )
273
+
274
+ if image_spec is not None:
275
+
276
+ def field_text(field):
277
+ """Return the raw text of an ``image_spec``
278
+ child field, or ``None``."""
279
+ child = image_spec.child_by_field_name(field)
280
+ if child is None:
281
+ return None
282
+ return source[child.start_byte:child.end_byte].decode()
283
+
284
+ alias_node = node.child_by_field_name("as")
285
+
286
+ results.append({
287
+ "image": field_text("name"),
288
+ "tag": field_text("tag"),
289
+ "digest": field_text("digest"),
290
+ "alias": (
291
+ source[alias_node.start_byte:alias_node.end_byte]
292
+ .decode()
293
+ if alias_node is not None
294
+ else None
295
+ ),
296
+ })
297
+
298
+ for child in node.named_children:
299
+ visit(child)
300
+
301
+ visit(tree.root_node)
302
+ return results