walls 0.1.17__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.
walls/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """walls: wall in Claude Code agents to the current folder with Apptainer."""
2
+
3
+ try:
4
+ from importlib.metadata import PackageNotFoundError, version
5
+
6
+ __version__ = version("walls")
7
+ except PackageNotFoundError: # pragma: no cover - running from a source tree
8
+ __version__ = "0+unknown"
walls/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
walls/cli.py ADDED
@@ -0,0 +1,497 @@
1
+ """The ``walls`` command line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import sys
7
+ from pathlib import Path
8
+ from typing import List, Optional, Sequence
9
+
10
+ import click
11
+
12
+ from . import __version__
13
+ from . import config as C
14
+ from . import glibc as G
15
+ from . import images as I
16
+ from . import provision as P
17
+ from .launch import LaunchError, build_command, execute
18
+
19
+ _FOLDER_HELP = "Apply to a folder instead of globally (no value: the current folder)."
20
+
21
+
22
+ def _fail(msg: str) -> None:
23
+ raise click.ClickException(msg)
24
+
25
+
26
+ def _load_raw() -> C.Config:
27
+ try:
28
+ return C.load_raw()
29
+ except C.ConfigError as exc:
30
+ _fail(str(exc))
31
+ return {} # pragma: no cover
32
+
33
+
34
+ def _cfg(folder: Optional[os.PathLike | str] = None) -> C.Config:
35
+ return C.effective(_load_raw(), folder)
36
+
37
+
38
+ class WallsGroup(click.Group):
39
+ """A group that runs ``walls run`` when no subcommand is given.
40
+
41
+ ``walls``, ``walls /some/dir`` and ``walls --ro /x -- claude`` are all
42
+ treated as ``walls run ...``. Everything after ``--`` is the command to
43
+ run in the box.
44
+ """
45
+
46
+ _GROUP_OPTS = {"--help", "-h", "--version"}
47
+
48
+ def parse_args(self, ctx: click.Context, args: List[str]) -> List[str]:
49
+ # Route to `run` when there are no args, or the first is an option or
50
+ # an existing path; anything else is (maybe a mistyped) subcommand.
51
+ if not args or (
52
+ args[0] not in self.commands
53
+ and args[0] not in self._GROUP_OPTS
54
+ and (args[0].startswith("-") or os.path.exists(args[0]))
55
+ ):
56
+ args = ["run", *args]
57
+ if args[0] == "run" and "--" in args:
58
+ i = args.index("--")
59
+ ctx.meta["walls.command"] = args[i + 1:]
60
+ args = args[:i]
61
+ return super().parse_args(ctx, args)
62
+
63
+
64
+ @click.group(cls=WallsGroup, context_settings={"help_option_names": ["-h", "--help"]})
65
+ @click.version_option(__version__, prog_name="walls")
66
+ def walls() -> None:
67
+ """Wall in Claude Code (or anything else) to the current folder.
68
+
69
+ Run `walls` in a project folder to start a bash shell in an Apptainer box
70
+ where only that folder is writable (at /work). Start `claude` there.
71
+
72
+ \b
73
+ First time: walls setup
74
+ Every time: cd my-project && walls
75
+ Run a tool: walls -- claude
76
+ More access: walls --ro /data/ref (or: walls config add mounts.ro /data/ref --folder)
77
+ """
78
+
79
+
80
+ # --------------------------------------------------------------------------
81
+ # run
82
+ # --------------------------------------------------------------------------
83
+
84
+ @walls.command(context_settings={"help_option_names": ["-h", "--help"]})
85
+ @click.argument("ro_dirs", nargs=-1, type=click.Path(exists=True, file_okay=False))
86
+ @click.option("--ro", "ro", multiple=True, type=click.Path(exists=True, file_okay=False),
87
+ help="Extra folder to mount read-only (repeatable).")
88
+ @click.option("--rw", "rw", multiple=True, type=click.Path(exists=True, file_okay=False),
89
+ help="Extra folder to mount read-write (repeatable).")
90
+ @click.option("--image", help="Image name or .sif path (default: image.default).")
91
+ @click.option("--aliases/--no-aliases", default=None, help="Override shell.import_aliases.")
92
+ @click.option("--host-path/--no-host-path", default=None, help="Override path.mount_host_path.")
93
+ @click.option("--private-pid/--no-private-pid", default=None, help="Override apptainer.private_pid.")
94
+ @click.option("--dry-run", is_flag=True, help="Print the apptainer command and rcfile; start nothing.")
95
+ @click.pass_context
96
+ def run(ctx: click.Context, ro_dirs: Sequence[str], ro: Sequence[str], rw: Sequence[str],
97
+ image: Optional[str], aliases: Optional[bool], host_path: Optional[bool],
98
+ private_pid: Optional[bool], dry_run: bool) -> None:
99
+ """Start a box in the current folder: `walls [DIRS...] [-- CMD...]`.
100
+
101
+ DIRS are extra folders mounted read-only at their real paths. Anything
102
+ after `--` is run in the box instead of an interactive bash.
103
+ """
104
+ cwd = Path.cwd()
105
+ cfg = _cfg(cwd)
106
+ if aliases is not None:
107
+ cfg["shell"]["import_aliases"] = aliases
108
+ if host_path is not None:
109
+ cfg["path"]["mount_host_path"] = host_path
110
+ if private_pid is not None:
111
+ cfg["apptainer"]["private_pid"] = private_pid
112
+ command = ctx.meta.get("walls.command", [])
113
+ try:
114
+ launch = build_command(
115
+ cfg, cwd, [*ro_dirs, *ro], rw, command, image,
116
+ apptainer="apptainer" if dry_run else None,
117
+ )
118
+ except LaunchError as exc:
119
+ _fail(str(exc))
120
+ warnings = list(launch.warnings)
121
+ if launch.path_mounts:
122
+ # a dry run starts nothing, so it only uses a remembered image version
123
+ have = G.image_glibc(launch.image, None if dry_run else launch.argv[0])
124
+ glibc_warning = G.launch_warning(G.host_glibc(), have)
125
+ if glibc_warning:
126
+ warnings.append(glibc_warning)
127
+ for w in warnings:
128
+ click.echo(f"walls: warning: {w}", err=True)
129
+ if dry_run:
130
+ click.echo(f"# rcfile {launch.rcfile} (bound read-only at /walls/bashrc):")
131
+ click.echo(launch.rcfile_text)
132
+ click.echo("# command:")
133
+ click.echo(launch.shell_command())
134
+ return
135
+ try:
136
+ execute(launch)
137
+ except LaunchError as exc:
138
+ _fail(str(exc))
139
+
140
+
141
+ # --------------------------------------------------------------------------
142
+ # setup / doctor / claude
143
+ # --------------------------------------------------------------------------
144
+
145
+ @walls.command()
146
+ @click.option("--yes", "-y", is_flag=True, help="Do not ask before pulling the image or installing Claude Code.")
147
+ @click.option("--no-image", is_flag=True, help="Skip pulling the default image.")
148
+ @click.option("--no-claude", is_flag=True, help="Skip installing Claude Code.")
149
+ def setup(yes: bool, no_image: bool, no_claude: bool) -> None:
150
+ """One-time setup: folders, config file, default image and Claude Code."""
151
+ raw = _load_raw()
152
+ cfg = C.effective(raw)
153
+ for p in P.ensure_dirs(cfg):
154
+ click.echo(f"created {p}")
155
+ if not C.config_path().exists():
156
+ C.save_raw({"image": {"default": cfg["image"]["default"]}})
157
+ click.echo(f"created {C.config_path()}")
158
+
159
+ img = I.image_path(cfg, None)
160
+ if not no_image and not img.exists():
161
+ src = cfg["image"]["source"]
162
+ if yes or click.confirm(f"Pull {src} to {img}? (several GB, takes a while)", default=True):
163
+ try:
164
+ cmd = I.pull_command(cfg, src, cfg["image"]["default"])
165
+ except LaunchError as exc:
166
+ _fail(str(exc))
167
+ click.echo("$ " + " ".join(cmd))
168
+ if I.run(cmd) != 0:
169
+ _fail("image pull failed")
170
+
171
+ if not no_claude and not P.claude_installed(cfg):
172
+ if yes or click.confirm("Install Claude Code into the claude home now?", default=True):
173
+ try:
174
+ rc = _install_claude(cfg)
175
+ except LaunchError as exc:
176
+ _fail(str(exc))
177
+ if rc != 0:
178
+ _fail("Claude Code installation failed")
179
+ click.echo("\nDone. Check with 'walls doctor', then cd into a project and run 'walls'.")
180
+
181
+
182
+ @walls.command()
183
+ def doctor() -> None:
184
+ """Check the runtime, image, claude home and the current folder."""
185
+ cfg = _cfg(Path.cwd())
186
+ bad = 0
187
+ for ok, msg in P.doctor(cfg, Path.cwd()):
188
+ bad += ok is False
189
+ click.echo({True: " ok ", False: " FAIL ", None: " warn "}[ok] + msg)
190
+ if bad:
191
+ sys.exit(1)
192
+
193
+
194
+ def _install_claude(cfg: C.Config) -> int:
195
+ """Run the Claude Code installer in a box and say where it really installs.
196
+
197
+ The installer reports box paths such as ``~/.local/bin/claude``. Inside a
198
+ box ``~`` is the claude home, so the host location is printed before and
199
+ after to keep that from reading as the user's own home.
200
+ """
201
+ claude_home = C.expand(cfg["paths"]["claude_home"])
202
+ click.echo(
203
+ "Running the Claude Code installer inside a box. In its output, '~' is the box home,\n"
204
+ f"which is {claude_home} on this machine, not your own home folder.\n"
205
+ )
206
+ rc = P.install_claude(cfg)
207
+ if rc == 0:
208
+ click.echo(
209
+ f"\nClaude Code is installed at {P.claude_binary(cfg)}\n"
210
+ "(seen as ~/.local/bin/claude inside a box). Nothing was written to your own home folder."
211
+ )
212
+ return rc
213
+
214
+
215
+ @walls.group()
216
+ def claude() -> None:
217
+ """Install or update Claude Code in the shared claude home."""
218
+
219
+
220
+ @claude.command("install")
221
+ def claude_install() -> None:
222
+ """Install Claude Code with the official installer, inside a box."""
223
+ try:
224
+ sys.exit(_install_claude(_cfg()))
225
+ except LaunchError as exc:
226
+ _fail(str(exc))
227
+
228
+
229
+ @claude.command("update")
230
+ def claude_update() -> None:
231
+ """Run `claude update` inside a box."""
232
+ try:
233
+ sys.exit(P.update_claude(_cfg()))
234
+ except LaunchError as exc:
235
+ _fail(str(exc))
236
+
237
+
238
+ # --------------------------------------------------------------------------
239
+ # image
240
+ # --------------------------------------------------------------------------
241
+
242
+ @walls.group()
243
+ def image() -> None:
244
+ """Download, build, list and select .sif images."""
245
+
246
+
247
+ @image.command("pull")
248
+ @click.argument("source", required=False)
249
+ @click.option("--name", help="Image name (default: image.default).")
250
+ @click.option("--force", is_flag=True, help="Overwrite an existing image.")
251
+ def image_pull(source: Optional[str], name: Optional[str], force: bool) -> None:
252
+ """Pull SOURCE (default: image.source) into the image dir.
253
+
254
+ Example: walls image pull docker://ubuntu:24.04 --name ubuntu
255
+ """
256
+ cfg = _cfg()
257
+ try:
258
+ cmd = I.pull_command(cfg, source or cfg["image"]["source"], name or cfg["image"]["default"], force)
259
+ except LaunchError as exc:
260
+ _fail(str(exc))
261
+ click.echo("$ " + " ".join(cmd))
262
+ sys.exit(I.run(cmd))
263
+
264
+
265
+ @image.command("build")
266
+ @click.argument("deffile", type=click.Path(exists=True, dir_okay=False))
267
+ @click.option("--name", required=True, help="Name of the new image.")
268
+ @click.option("--fakeroot", is_flag=True, help="Build with --fakeroot (needed without root).")
269
+ @click.option("--force", is_flag=True, help="Overwrite an existing image.")
270
+ def image_build(deffile: str, name: str, fakeroot: bool, force: bool) -> None:
271
+ """Build an image from an Apptainer definition file."""
272
+ cfg = _cfg()
273
+ try:
274
+ cmd = I.build_command(cfg, deffile, name, fakeroot, force)
275
+ except LaunchError as exc:
276
+ _fail(str(exc))
277
+ click.echo("$ " + " ".join(cmd))
278
+ sys.exit(I.run(cmd))
279
+
280
+
281
+ @image.command("list")
282
+ def image_list() -> None:
283
+ """List images; the default is marked with *."""
284
+ cfg = _cfg()
285
+ found = I.list_images(cfg)
286
+ if not found:
287
+ click.echo(f"no images in {I.image_dir(cfg)}; run 'walls image pull'")
288
+ return
289
+ for name, path, size in found:
290
+ mark = "*" if name == cfg["image"]["default"] else " "
291
+ click.echo(f"{mark} {name:<24} {I.human_size(size):>10} {path}")
292
+
293
+
294
+ @image.command("use")
295
+ @click.argument("name")
296
+ @click.option("--folder", is_flag=False, flag_value=".", help=_FOLDER_HELP)
297
+ def image_use(name: str, folder: Optional[str]) -> None:
298
+ """Make NAME the default image (globally or for a folder)."""
299
+ cfg = _cfg()
300
+ try:
301
+ I.resolve_existing(cfg, name)
302
+ except FileNotFoundError as exc:
303
+ _fail(f"no such image: {exc}")
304
+ raw = _load_raw()
305
+ C.set_value(raw, "image.default", name, folder)
306
+ C.save_raw(raw)
307
+ click.echo(f"default image{_where(folder)}: {name}")
308
+
309
+
310
+ @image.command("rm")
311
+ @click.argument("name")
312
+ @click.option("--yes", "-y", is_flag=True, help="Do not ask for confirmation.")
313
+ def image_rm(name: str, yes: bool) -> None:
314
+ """Delete the image called NAME."""
315
+ cfg = _cfg()
316
+ try:
317
+ p = I.resolve_existing(cfg, name)
318
+ except FileNotFoundError as exc:
319
+ _fail(f"no such image: {exc}")
320
+ if yes or click.confirm(f"Delete {p}?"):
321
+ p.unlink()
322
+ click.echo(f"deleted {p}")
323
+
324
+
325
+ # --------------------------------------------------------------------------
326
+ # config
327
+ # --------------------------------------------------------------------------
328
+
329
+ def _where(folder: Optional[str]) -> str:
330
+ return f" for {C.folder_key(folder)}" if folder is not None else ""
331
+
332
+
333
+ @walls.group()
334
+ def config() -> None:
335
+ """Show and change settings in ~/.config/walls/config.toml.
336
+
337
+ \b
338
+ Keys:
339
+ paths.claude_home, paths.work_root, paths.image_dir (global only)
340
+ image.default, image.source
341
+ apptainer.binary, apptainer.private_pid, apptainer.extra_args
342
+ mounts.ro, mounts.rw
343
+ shell.import_aliases, shell.prompt, shell.env_pass
344
+ path.mount_host_path, path.exclude
345
+
346
+ Settings apply globally, or with --folder to one folder only. Folder
347
+ settings are stored in the global file, never in the folder itself.
348
+ Lists from both levels are combined.
349
+ """
350
+
351
+
352
+ @config.command("path")
353
+ def config_path_cmd() -> None:
354
+ """Print the path of the config file."""
355
+ click.echo(C.config_path())
356
+
357
+
358
+ @config.command("show")
359
+ @click.option("--folder", is_flag=False, flag_value=".", help="Show a folder's own settings (no value: the current folder).")
360
+ @click.option("--effective", is_flag=True, help="Show the merged settings (defaults, global, folder).")
361
+ def config_show(folder: Optional[str], effective: bool) -> None:
362
+ """Show the config file, a folder's settings or the effective settings."""
363
+ raw = _load_raw()
364
+ if effective:
365
+ target = folder if folder is not None else os.getcwd()
366
+ click.echo(f"# effective settings for {C.folder_key(target)}")
367
+ click.echo(C.dumps(C.effective(raw, target)))
368
+ elif folder is not None:
369
+ table = raw.get("folders", {}).get(C.folder_key(folder), {})
370
+ click.echo(f"# settings for {C.folder_key(folder)}")
371
+ click.echo(C.dumps(table) if table else "# (none)")
372
+ else:
373
+ click.echo(f"# {C.config_path()}")
374
+ click.echo(C.dumps(raw) if raw else "# (empty: built-in defaults apply; see --effective)")
375
+
376
+
377
+ @config.command("get")
378
+ @click.argument("key")
379
+ @click.option("--folder", is_flag=False, flag_value=".", help="Effective value for a folder (no value: the current folder).")
380
+ def config_get(key: str, folder: Optional[str]) -> None:
381
+ """Print the effective value of KEY."""
382
+ try:
383
+ s, k = C.split_key(key)
384
+ except C.ConfigError as exc:
385
+ _fail(str(exc))
386
+ val = _cfg(folder if folder is not None else os.getcwd())[s][k]
387
+ click.echo("\n".join(val) if isinstance(val, list) else str(val).lower() if isinstance(val, bool) else val)
388
+
389
+
390
+ def _edit(fn, folder: Optional[str], *args) -> object:
391
+ raw = _load_raw()
392
+ try:
393
+ result = fn(raw, *args, folder)
394
+ C.save_raw(raw)
395
+ except C.ConfigError as exc:
396
+ _fail(str(exc))
397
+ return result
398
+
399
+
400
+ @config.command("set")
401
+ @click.argument("key")
402
+ @click.argument("values", nargs=-1, required=True)
403
+ @click.option("--folder", is_flag=False, flag_value=".", help=_FOLDER_HELP)
404
+ def config_set(key: str, values: Sequence[str], folder: Optional[str]) -> None:
405
+ """Set KEY to VALUES (lists take several values and replace the list).
406
+
407
+ \b
408
+ Examples:
409
+ walls config set shell.import_aliases true
410
+ walls config set path.mount_host_path true --folder
411
+ walls config set mounts.ro /data/ref /data/db --folder ~/proj
412
+ """
413
+ try:
414
+ value = C.parse_value(key, list(values))
415
+ except C.ConfigError as exc:
416
+ _fail(str(exc))
417
+ _edit(C.set_value, folder, key, value)
418
+ click.echo(f"{key}{_where(folder)} = {value!r}")
419
+
420
+
421
+ @config.command("unset")
422
+ @click.argument("key")
423
+ @click.option("--folder", is_flag=False, flag_value=".", help=_FOLDER_HELP)
424
+ def config_unset(key: str, folder: Optional[str]) -> None:
425
+ """Remove KEY, so the inherited value applies again."""
426
+ removed = _edit(C.unset_value, folder, key)
427
+ click.echo(f"unset {key}{_where(folder)}" if removed else f"{key} was not set{_where(folder)}")
428
+
429
+
430
+ @config.command("add")
431
+ @click.argument("key")
432
+ @click.argument("values", nargs=-1, required=True)
433
+ @click.option("--folder", is_flag=False, flag_value=".", help=_FOLDER_HELP)
434
+ def config_add(key: str, values: Sequence[str], folder: Optional[str]) -> None:
435
+ """Append VALUES to the list KEY (e.g. mounts.ro)."""
436
+ try:
437
+ vals = C.parse_value(key, list(values))
438
+ except C.ConfigError as exc:
439
+ _fail(str(exc))
440
+ if not isinstance(vals, list):
441
+ _fail(f"{key} is not a list; use 'walls config set'")
442
+ _edit(C.add_values, folder, key, vals)
443
+ click.echo(f"added to {key}{_where(folder)}: {', '.join(vals)}")
444
+
445
+
446
+ @config.command("remove")
447
+ @click.argument("key")
448
+ @click.argument("values", nargs=-1, required=True)
449
+ @click.option("--folder", is_flag=False, flag_value=".", help=_FOLDER_HELP)
450
+ def config_remove(key: str, values: Sequence[str], folder: Optional[str]) -> None:
451
+ """Remove VALUES from the list KEY."""
452
+ try:
453
+ vals = C.parse_value(key, list(values))
454
+ except C.ConfigError as exc:
455
+ _fail(str(exc))
456
+ if not isinstance(vals, list):
457
+ _fail(f"{key} is not a list; use 'walls config unset'")
458
+ n = _edit(C.remove_values, folder, key, vals)
459
+ click.echo(f"removed {n} value(s) from {key}{_where(folder)}")
460
+
461
+
462
+ @config.command("edit")
463
+ def config_edit() -> None:
464
+ """Open the config file in $EDITOR (validated after saving)."""
465
+ path = C.config_path()
466
+ if not path.exists():
467
+ C.save_raw({})
468
+ click.edit(filename=str(path))
469
+ try:
470
+ C.load_raw()
471
+ except C.ConfigError as exc:
472
+ _fail(f"the config file is now invalid, please fix it: {exc}")
473
+
474
+
475
+ @config.command("folders")
476
+ @click.option("--prune", is_flag=True, help="Remove settings for folders that no longer exist.")
477
+ def config_folders(prune: bool) -> None:
478
+ """List folders that have their own settings."""
479
+ raw = _load_raw()
480
+ folders = raw.get("folders", {})
481
+ if not folders:
482
+ click.echo("no folder-specific settings")
483
+ return
484
+ gone = [f for f in folders if not os.path.isdir(f)]
485
+ for f, table in folders.items():
486
+ keys = ", ".join(f"{s}.{k}" for s, t in table.items() for k in t)
487
+ click.echo(f"{f}{' (missing)' if f in gone else ''}\n {keys}")
488
+ if prune and gone:
489
+ for f in gone:
490
+ del folders[f]
491
+ C.save_raw(raw)
492
+ click.echo(f"pruned {len(gone)} folder(s)")
493
+
494
+
495
+ def main() -> None: # pragma: no cover
496
+ """Entry point for ``python -m walls``."""
497
+ walls()