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,13 @@
1
+ """ dev-isolator - A concise podmand based development container
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 .main import main
12
+
13
+ __all__ = ["main"]
@@ -0,0 +1,15 @@
1
+ """Allow running as `python -m dev_isolator`.
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 dev_isolator import main
12
+ import sys
13
+
14
+ if __name__ == "__main__":
15
+ sys.exit(main())
@@ -0,0 +1,429 @@
1
+ """Build the dev-isolator base image (BaseImage).
2
+
3
+ Before a project's image can be built, its base image must exist: a
4
+ base image is built from one of the Containerfiles bundled with
5
+ dev-isolator (``data/base/Containerfile.<name>``, identified by the
6
+ ``DI_BASE`` comment in its first comment block). The resulting image is
7
+ tagged ``dev-isolator-<name>:<tag>``, e.g.
8
+ ``dev-isolator-ubuntu:26.04``.
9
+
10
+ The used Containerfile of a base image merges three sources: the base
11
+ Containerfile itself, the addons enabled in the active ``config.yaml``
12
+ (each ``addon.<name>.jinja2`` file rendered as a jinja2 template with
13
+ the host context, see :class:`Configuration`) and the host user
14
+ block (a user with the invoking host user's UID, GID and username,
15
+ template ``add_user.containerfile.jinja2``).
16
+
17
+ Project image builds (see
18
+ :class:`dev_isolator.container_image.ContainerImage`) then base their
19
+ ``FROM`` instruction on this base 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
+ from pathlib import Path
30
+ from .podman_utils import (get_image_id, remove_superseeded_image,
31
+ replace_from_images)
32
+ from .utils import dprint, Verbosity, get_verbosity
33
+ from .constants import BUNDLE_DIR, TEMPLATES_DIR
34
+ from .waitspinner import WaitSpinner
35
+ from .config import Configuration
36
+
37
+ import os
38
+ import pwd
39
+ import re
40
+ import podman
41
+ import json
42
+ import jinja2
43
+ import hashlib
44
+ from functools import lru_cache
45
+ from tempfile import mkstemp, TemporaryDirectory
46
+
47
+
48
+ def detect_package_manager(image: str) -> str | None:
49
+ """Detect the package manager available in a container image.
50
+
51
+ Runs ``image`` in a short-lived podman container and checks for
52
+ ``apt``, ``dnf``, ``zypper`` and ``pacman`` (in that order). The
53
+ container is removed again afterwards.
54
+
55
+ :param image: The image to run, e.g. ``ubuntu:26.04``.
56
+ :returns: The name of the first package manager found
57
+ (``apt``, ``dnf``, ``zypper`` or ``pacman``), or ``None``
58
+ when none of them is available.
59
+ :raises RuntimeError: if the podman run or exec fails.
60
+ """
61
+ package_managers = ("apt", "dnf", "zypper", "pacman")
62
+ try:
63
+ with WaitSpinner(f"Detecting package manager for {image}") as spinner:
64
+ with podman.PodmanClient() as client:
65
+ container = client.containers.run(image, command=["sleep",
66
+ "infinity"], detach=True)
67
+ try:
68
+ for pm in package_managers:
69
+ exit_code, _ = container.exec_run(
70
+ ["sh", "-c", f"command -v {pm}"])
71
+ if exit_code == 0:
72
+ spinner.set_text(f"-- Package Manager: {pm}")
73
+ return pm
74
+ return None
75
+ finally:
76
+ container.kill()
77
+ container.remove(force=True)
78
+ except podman.errors.APIError as e:
79
+ raise RuntimeError(
80
+ f"Podman API error while detecting the package manager "
81
+ f"of image {image}: {e}") from e
82
+
83
+
84
+ def render_template(template: jinja2.Template) -> str:
85
+ """Render a Containerfile jinja2 template with the host
86
+ context.
87
+
88
+ :param template: The template to render.
89
+ :returns: The rendered template text.
90
+ """
91
+ return template.render(
92
+ uid=os.getuid(),
93
+ gid=os.getgid(),
94
+ username=host_username(),
95
+ home_dir=Path.home()
96
+ )
97
+
98
+
99
+ def host_username() -> str:
100
+ """Return a username usable in the container for the host user.
101
+
102
+ Uses the username of the invoking host user (via
103
+ :func:`os.getuid`); invalid characters are replaced by ``_``.
104
+ When no matching host user is known or the name is not usable
105
+ for :command:`useradd`, a name starting with a letter is
106
+ derived from the UID.
107
+ """
108
+ uid = os.getuid()
109
+ try:
110
+ name = pwd.getpwuid(uid).pw_name
111
+ except KeyError:
112
+ name = ""
113
+ name = re.sub(r"[^a-zA-Z0-9_-]", "_", name).strip("-")
114
+ if not name or not name[0].isalpha():
115
+ name = f"user{uid}"
116
+ return name
117
+
118
+
119
+ @lru_cache(maxsize=1)
120
+ def _jinja_environment() -> jinja2.Environment:
121
+ """Return the (cached) shared jinja2 environment."""
122
+ return jinja2.Environment(
123
+ loader=jinja2.FileSystemLoader(TEMPLATES_DIR),
124
+ # Containerfile instructions, not HTML: no escaping.
125
+ autoescape=False,
126
+ keep_trailing_newline=True,
127
+ )
128
+
129
+
130
+ @lru_cache(maxsize=1)
131
+ def _add_user_template() -> jinja2.Template:
132
+ """Return the (cached) jinja2 template for the add user block."""
133
+ return _jinja_environment().get_template(
134
+ "add_user.containerfile.jinja2")
135
+
136
+
137
+ class BaseImage:
138
+ """Build the base image a project image is based upon.
139
+
140
+ A base image is built from one of the Containerfiles bundled with
141
+ dev-isolator (``data/base/Containerfile.<name>``), with the addons
142
+ enabled in the active ``config.yaml`` and the host user appended
143
+ (see :meth:`merged_container_file_content`). The resulting image
144
+ is tagged ``dev-isolator-<name>:<tag>``.
145
+
146
+ :attr base_image: Identifier of the selected base Containerfile,
147
+ as stored in :attr:`base_images` (its ``DI_BASE`` value,
148
+ including the tag), e.g. ``ubuntu:26.04``.
149
+ :attr tag: The tag of the selected base Containerfile, e.g.
150
+ ``26.04``.
151
+ :attr name: Like ``base_image``; the part of the selected base
152
+ image before its ``:`` separator.
153
+ :attr base_images: Mapping from the ``DI_BASE`` value of every
154
+ bundled base Containerfile to its path, e.g.
155
+ ``ubuntu:26.04`` to ``data/base/Containerfile.ubuntu-26.04``.
156
+ """
157
+
158
+ def __init__(self, config: Configuration = None):
159
+ """Set up the base image for a build context.
160
+
161
+ :param config: The project's
162
+ :class:`dev_isolator.config.Configuration`, determining the
163
+ enabled addons. May be ``None``.
164
+ """
165
+ self.config = config
166
+ self.bundled_dir = BUNDLE_DIR
167
+
168
+ self.base_image_dir = self.bundled_dir / "base"
169
+ dprint(Verbosity.INFO, f"Base image dir: {self.base_image_dir}")
170
+
171
+ self.base_images = {}
172
+ self.package_managers = {}
173
+ for path in sorted(self.base_image_dir.glob("Containerfile.*")):
174
+ value, pkg_man = self._parse_di_base(path)
175
+ for v in value:
176
+ dprint(Verbosity.DEBUG, f"Found base image {v} in {path}")
177
+ self.base_images[v] = path
178
+ if pkg_man:
179
+ if self.package_managers.get(pkg_man):
180
+ dprint(Verbosity.ERROR, "Base image for package manager "
181
+ f"{pkg_man} already exists in "
182
+ f"{self.package_managers[pkg_man]}"
183
+ f", ignore from {path}")
184
+ else:
185
+ dprint(Verbosity.DEBUG, "Found package_manager base for "
186
+ f"{pkg_man} in {path}")
187
+ self.package_managers[pkg_man] = value[0]
188
+
189
+ def list_base_images(self):
190
+ """Return the sorted list of bundled base image names.
191
+
192
+ :returns: Every ``DI_BASE`` value found in the bundled base
193
+ Containerfiles (see :attr:`base_images`), as strings,
194
+ sorted alphabetically, e.g.
195
+ ``["ubuntu:24.04", "ubuntu:26.04"]``. Used by the
196
+ ``list-base`` sub command (see
197
+ :func:`dev_isolator.main.list_base`).
198
+ """
199
+ bil = []
200
+ for value in self.base_images.keys():
201
+ bil.append(str(value))
202
+ bil.sort()
203
+ return bil
204
+
205
+ def get_base_from_pkg(self, pkg):
206
+ file = self.package_managers[pkg]
207
+ for v in self.base_images:
208
+ if self.base_images[v] == file:
209
+ return v
210
+ return None
211
+
212
+ def _parse_di_base(self, path):
213
+ """Return the DI_BASE value from the file's first comment block."""
214
+ # Matches "DI_BASE = VALUE" in a comment line.
215
+ _DI_BASE_RE = re.compile(
216
+ r"#\s*DI_BASE\s*=\s*(\S+)")
217
+ _DI_PKG_RE = re.compile(
218
+ r"#\s*DI_PKG\s*=\s*(\S+)")
219
+
220
+ value = []
221
+ pkg_man = None
222
+ with path.open() as fh:
223
+ for line in fh:
224
+ line = line.strip()
225
+ if not line:
226
+ continue
227
+ if not line.startswith("#"):
228
+ break
229
+ base_match = _DI_BASE_RE.search(line)
230
+ pkg_match = _DI_PKG_RE.search(line)
231
+ if base_match:
232
+ value.append(base_match.group(1))
233
+ if pkg_match:
234
+ pkg_man = pkg_match.group(1)
235
+ return value, pkg_man
236
+
237
+ def write_container_file(self, directory):
238
+ """Write the used Containerfile for the base image build.
239
+
240
+ The used Containerfile is the merged content of the selected
241
+ base Containerfile (see :meth:`merged_container_file_content`).
242
+ At ``Verbosity.TRACE`` the content is printed to stdout.
243
+
244
+ The file is created inside ``directory`` and fsynced,
245
+ so its content reaches disk before podman reads the file
246
+ during the build.
247
+
248
+ :returns: The tuple ``(fd, temp_container_file, content_hash)``
249
+ of the open file descriptor of the written file, its path
250
+ and the SHA-256 hash of the Containerfile content (used
251
+ as part of the built image's tag).
252
+ """
253
+ container_file = self.base_images.get(self.base_image, None)
254
+ base_content = container_file.read_text(encoding="utf-8")
255
+ if self.replace_base:
256
+ base_content = replace_from_images(base_content,
257
+ self.replace_base)
258
+
259
+ file_content = self.merged_container_file_content(base_content)
260
+ m = hashlib.sha256()
261
+ m.update(file_content.encode("utf-8"))
262
+ content_hash = m.hexdigest()
263
+
264
+ if get_verbosity() >= Verbosity.TRACE:
265
+ for line in file_content.splitlines():
266
+ print(f"[Containerfile] {line}")
267
+
268
+ fd, temp_name = mkstemp(dir=directory,
269
+ prefix=".containerfile.")
270
+ temp_container_file = Path(temp_name)
271
+ try:
272
+ with os.fdopen(fd, "w", encoding="utf-8") as fp:
273
+ fp.write(file_content)
274
+ # Make sure the content reaches disk before podman
275
+ # reads the file during the build.
276
+ fp.flush()
277
+ os.fsync(fp.fileno())
278
+ except BaseException:
279
+ temp_container_file.unlink(missing_ok=True)
280
+ raise
281
+ return fd, temp_container_file, content_hash
282
+
283
+ def build(self, image):
284
+ """Build a base image.
285
+
286
+ ``image`` identifies the base image the project's Containerfile
287
+ is based on, for example ``ubuntu:26.04``. It must match the
288
+ ``DI_BASE`` value of
289
+ one of the bundled base Containerfiles (see
290
+ :meth:`_parse_di_base` and :attr:`base_images`).
291
+
292
+ The resulting image is tagged
293
+ ``dev-isolator-<name>:<tag>``, where ``name`` and ``tag`` are
294
+ the parts of the identified base image around its ``:``
295
+ separator (``ubuntu:26.04`` -> ``dev-isolator-ubuntu:26.04``).
296
+
297
+ The built Containerfile is the merged base Containerfile with
298
+ the enabled addons and the host user appended (see
299
+ :meth:`merged_container_file_content`). It requires a
300
+ Debian-style base image (``useradd`` and ``getent`` must
301
+ exist).
302
+
303
+ :param image: The base image to build the project image from,
304
+ e.g. ``ubuntu:26.04``.
305
+ :returns: The tuple ``(image, image_tag, content_hash)`` of the
306
+ built image, its tag and the SHA-256 hash of the built
307
+ Containerfile content.
308
+ :raises RuntimeError: if no bundled base Containerfile matches
309
+ ``image`` and its package manager is not supported (see
310
+ :func:`detect_package_manager`), the tag cannot be derived
311
+ from ``image`` or the podman build fails.
312
+ """
313
+ if not self.base_images.get(image, None):
314
+ pkgman = detect_package_manager(image)
315
+ if pkgman not in self.package_managers:
316
+ raise RuntimeError(f"Package manager {pkgman} not supported.")
317
+ self.replace_base = image
318
+ self.base_image = self.package_managers[pkgman]
319
+ else:
320
+ self.replace_base = None
321
+ self.base_image = image
322
+
323
+ try:
324
+ self.tag = image.split(":")[1]
325
+ except Exception as e:
326
+ raise RuntimeError(f"The base image {image} does not contain a "
327
+ "tag") from e
328
+ self.name = image.split(":")[0]
329
+
330
+ temp_dir_object = TemporaryDirectory(ignore_cleanup_errors=True)
331
+ temp_dir = temp_dir_object.name
332
+
333
+ fd, temp_container_file, content_hash = (self.write_container_file(
334
+ temp_dir))
335
+ image_tag = f"dev-isolator-{self.name}:{self.tag}-{content_hash}"
336
+ dprint(Verbosity.INFO, "Created temporary Containerfile "
337
+ f"{temp_container_file}")
338
+
339
+ try:
340
+ with podman.PodmanClient() as client:
341
+ previous_id = get_image_id(client, image_tag)
342
+ dprint(Verbosity.INFO, f"Building base image "
343
+ f"{image_tag} ...")
344
+ with WaitSpinner(f"Building base image {image_tag}"):
345
+ image, build_logs = client.images.build(
346
+ path=str(temp_dir),
347
+ dockerfile=str(temp_container_file),
348
+ tag=image_tag,
349
+ rm=True,
350
+ forcerm=True,
351
+ pull=True,
352
+ nocache=self.config.build_get_nocache()
353
+ )
354
+ remove_superseeded_image(client, previous_id, image.id,
355
+ image_tag)
356
+
357
+ except podman.errors.BuildError as e:
358
+ raise RuntimeError(
359
+ f"Failed to build base image {image_tag}: {e}") from e
360
+ except podman.errors.APIError as e:
361
+ raise RuntimeError(
362
+ f"Podman API error while building base image "
363
+ f"{image_tag}: {e}") from e
364
+ finally:
365
+ if temp_container_file is not None:
366
+ temp_container_file.unlink(missing_ok=True)
367
+ if temp_dir_object is not None:
368
+ temp_dir_object.cleanup()
369
+
370
+ if get_verbosity() >= Verbosity.TRACE:
371
+ for entry in build_logs:
372
+ if isinstance(entry, bytes):
373
+ entry = json.loads(
374
+ entry.decode(errors='replace').strip())
375
+ for stream in entry.get("stream", "").splitlines():
376
+ dprint(Verbosity.TRACE, f"[build] {stream}")
377
+
378
+ dprint(Verbosity.INFO, f"Built base image {image.id} "
379
+ f"tagged {image_tag} with hash {content_hash}")
380
+ return image, image_tag, content_hash
381
+
382
+ def add_user_content(self) -> str:
383
+ """Return the Containerfile instructions adding the host user.
384
+
385
+ Renders the ``add_user.containerfile.jinja2``
386
+ template shipped with dev-isolator (see :const:`TEMPLATES_DIR`)
387
+ with the host context (see :func:`render_template`), as do the
388
+ ``addon.*`` files in :meth:`merged_container_file_content`.
389
+
390
+ The template removes any pre-existing user/group occupying
391
+ those properties from the image and then creates a user whose
392
+ UID, GID and username match those of the invoking host user,
393
+ making it the image's default user.
394
+
395
+ It requires a Debian-style base image (``useradd`` and
396
+ ``getent`` must exist).
397
+ """
398
+ return render_template(_add_user_template())
399
+
400
+ def merged_container_file_content(self, base_content) -> str:
401
+ """Return the base image's used Containerfile content.
402
+
403
+ Starts with the content of the base ``Containerfile``
404
+ ``base_content`` and appends the host user block (same UID,
405
+ GID and username as the invoking user, see :meth:`add_user_content`),
406
+ followed by every addon file from
407
+ :meth:`Configuration.list_addon_files` rendered as a jinja2
408
+ template (see :func:`render_template` for the template
409
+ variables), separated by a comment naming the addon file.
410
+
411
+ The host user makes shells and exec sessions run as that
412
+ user; addons that need to install packages switch to root and
413
+ must re-assert the host user again themselves.
414
+
415
+ :param base_content: The content of the base Containerfile to
416
+ append the host user and the addons to.
417
+ :returns: The merged Containerfile content.
418
+ :raises RuntimeError: if an addon config file is invalid (via
419
+ :meth:`Configuration.list_addon_files`).
420
+ """
421
+ text = str(base_content)
422
+ text += "\n\n" + self.add_user_content()
423
+ for addon in self.config.list_addon_files():
424
+ dprint(Verbosity.INFO, f"Appending addon: {addon.name}")
425
+ text += f"\n\n# --- appended from {addon.name} ---\n"
426
+ template = _jinja_environment().from_string(
427
+ addon.read_text(encoding="utf-8"))
428
+ text += render_template(template).rstrip("\n") + "\n"
429
+ return text