projectcats-cli 1.0.2__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.
pcat/cli.py ADDED
@@ -0,0 +1,583 @@
1
+ # pcat/cli.py
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import json
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from pcat import __app_name__ as app_name, __version__ as version
10
+ from pcat.box import box_attach, box_logs, box_ps, box_rm, box_run_foreground, box_stop, box_up
11
+ from pcat.config import (
12
+ DEFAULT_CONFIG_PATH,
13
+ add_custom_template,
14
+ load_config,
15
+ remove_custom_template,
16
+ reset_config,
17
+ set_config_value,
18
+ )
19
+ from pcat.modules import (
20
+ get_build_profiles,
21
+ inspect_archive,
22
+ merge_archives,
23
+ pack_with_profile,
24
+ split_archive,
25
+ )
26
+ from pcat.packer import pack_project, read_manifest, run_project, unpack_project
27
+ from pcat.plugins import DEFAULT_PLUGINS_DIR, create_plugin_template, get_plugin_manager
28
+ from pcat.templates import create_many_from_template, list_templates
29
+ from pcat.terminal import run_project_cat_terminal
30
+
31
+ HELP_TEXT = f"""{app_name} v{version}
32
+
33
+ Usage:
34
+ pcat Show current version
35
+ pcat -h, --help Show this help message
36
+ pcat -o Open Project Cat Terminal (multitasking mode)
37
+ pcat new <name1> [name2 ...] [-o dir] [--force]
38
+ Create 1+ projects using default_template
39
+ pcat new.<template> <name1> [name2 ...] [-o dir] [--force]
40
+ Create 1+ projects using specified template
41
+ pcat new <template> <name1> [name2 ...] [-o dir] [--force]
42
+ Same with space-separated template name
43
+ pcat new --list List built-in and custom templates
44
+ pcat pack <path> [-o out] [--key k] [--chunk-kb 64] [--entry file.py] [--data-only] [--profile name]
45
+ Pack project into .pcat modules (0 or -1 = 1 single file)
46
+ pcat pack --list-profiles List available build profiles and descriptions
47
+ pcat profiles List available build profiles and descriptions
48
+ pcat inspect <file.pcat> [--key k] [--json]
49
+ Inspect metadata, chunk sizes, and SHA-256 integrity
50
+ pcat merge <out.pcat> <part1.pcat> <part2.pcat> ... [--key k] [--chunk-kb n] [--on-conflict mode]
51
+ Merge multiple .pcat archives into one module bundle
52
+ pcat split <file.pcat> [-o dir] [--key k] [--per-file | --parts n]
53
+ Split a .pcat archive into smaller .pcat modules
54
+ pcat plugins List loaded plugins and custom commands
55
+ pcat plugin init <name> [-o dir] Generate a starter plugin template
56
+ pcat run <file.pcat> [--key k] [--entry file.py] [-- args...]
57
+ Run executable .pcat project directly from terminal
58
+ pcat unpack <file.pcat> [-o dir] [--key k]
59
+ Verify & unpack .pcat modules into directory
60
+ pcat info <file.pcat> [--key k] Inspect manifest and module list of a .pcat archive
61
+ pcat box up <path_or_pcat> [--key k] [--venv]
62
+ Start isolated box in background with pcatbox.json env
63
+ pcat box run <path_or_pcat> [--key k] [--venv] [--keep] [-- args...]
64
+ Run project inside isolated box in foreground
65
+ pcat box ps List boxes and status
66
+ pcat box logs <id_or_name> [--tail 50] Show stdout/stderr logs of a box
67
+ pcat box attach <id_or_name> Attach interactive console to a running box
68
+ pcat box stop <id_or_name> Stop a running box
69
+ pcat box rm <id_or_name> [--force] Remove a box and its workspace
70
+ pcat config show Show saved config
71
+ pcat config set <key> <value> Update config (default_key, chunk_kb, layout_mode, default_template)
72
+ pcat config template add <name> <dir> Register custom template folder
73
+ pcat config template remove <name> Remove custom template
74
+ pcat config template list List custom templates
75
+ pcat config reset Reset config to defaults
76
+
77
+ Keybindings in Project Cat Terminal:
78
+ Ctrl + N Open a new terminal / tab
79
+ Ctrl + D Close current terminal (if only one remains — exit choice modal)
80
+ Ctrl + T Toggle layout mode: Grid <-> Top Tabs
81
+ Ctrl + ←/→/↑/↓ Switch focus between panes or tabs
82
+ Ctrl + V Paste text from clipboard into active input
83
+ F11 Toggle console window maximize / restore
84
+ ↑ / ↓ Cycle previous / next commands in history
85
+ Ctrl+U / Ctrl+J Scroll output up / down
86
+ Alt+U / Alt+J Turbo scroll output up / down
87
+ Ctrl + K Jump straight to the bottom of output
88
+ Ctrl + Q Quit pcat
89
+
90
+ Editor (edit <file> / vim <file>):
91
+ Ctrl + I Toggle editor mode: EDIT <-> CMD (in terminal input bar)
92
+ Editor CMD mode: s (save), sq (save & quit), q (quit without saving),
93
+ py / python / runbypython / rbp (run with Python, live output + input)
94
+ """
95
+
96
+ BUILTIN_COMMANDS = (
97
+ "pack",
98
+ "profiles",
99
+ "inspect",
100
+ "merge",
101
+ "split",
102
+ "plugins",
103
+ "plugin",
104
+ "run",
105
+ "unpack",
106
+ "info",
107
+ "box",
108
+ "config",
109
+ )
110
+
111
+
112
+ def _parse_new_invocation(raw_args: list[str]) -> tuple[str | None, list[str], str | None, bool, bool]:
113
+ first_tok = raw_args[0]
114
+ dot_template: str | None = None
115
+ if first_tok.startswith("new."):
116
+ dot_template = first_tok[4:].strip()
117
+ if not dot_template:
118
+ raise ValueError("Template name after 'new.' cannot be empty")
119
+ rest = raw_args[1:]
120
+ else:
121
+ rest = raw_args[1:]
122
+ names: list[str] = []
123
+ output_dir: str | None = None
124
+ force = False
125
+ list_only = False
126
+ i = 0
127
+ while i < len(rest):
128
+ tok = rest[i]
129
+ if tok == "--list":
130
+ list_only = True
131
+ i += 1
132
+ elif tok == "--force":
133
+ force = True
134
+ i += 1
135
+ elif tok in ("-o", "--output"):
136
+ if i + 1 >= len(rest):
137
+ raise ValueError(f"Missing value after {tok}")
138
+ output_dir = rest[i + 1]
139
+ i += 2
140
+ elif tok.startswith("-"):
141
+ raise ValueError(f"Unknown option for 'new': {tok}")
142
+ else:
143
+ names.append(tok)
144
+ i += 1
145
+ if list_only:
146
+ return dot_template, names, output_dir, force, True
147
+ if dot_template is not None:
148
+ if not names:
149
+ raise ValueError(f"Specify at least one project name: pcat new.{dot_template} <name1> [name2...]")
150
+ return dot_template, names, output_dir, force, False
151
+ if not names:
152
+ raise ValueError("Specify at least one project name: pcat new <name1> [name2...]")
153
+ cfg = load_config()
154
+ known_templates = {"py-cli", "script", "mod", "box"} | set(cfg.custom_templates.keys())
155
+ if len(names) >= 2 and names[0].lower() in known_templates:
156
+ return names[0].lower(), names[1:], output_dir, force, False
157
+ return None, names, output_dir, force, False
158
+
159
+
160
+ def _print_profiles() -> int:
161
+ profiles = get_build_profiles()
162
+ for p_name in sorted(profiles.keys()):
163
+ spec = profiles[p_name]
164
+ desc = str(spec.get("description") or "No description provided.")
165
+ chunk_kb = spec.get("chunk_kb", "cfg")
166
+ exec_flag = spec.get("executable", True)
167
+ print(f" {p_name:<12} [chunk_kb={chunk_kb}, executable={exec_flag}] - {desc}")
168
+ return 0
169
+
170
+
171
+ def _print_plugins() -> int:
172
+ mgr = get_plugin_manager()
173
+ print(f"Plugins dir : {DEFAULT_PLUGINS_DIR}")
174
+ if not mgr.plugins:
175
+ print("No plugins loaded.")
176
+ return 0
177
+ for pl in mgr.plugins:
178
+ if pl.error:
179
+ status = f"ERROR: {pl.error}"
180
+ elif not pl.enabled:
181
+ status = "DISABLED"
182
+ else:
183
+ cmds = ", ".join(pl.commands) if pl.commands else "-"
184
+ status = f"OK (commands: {cmds})"
185
+ print(f" {pl.name:<16} v{pl.version:<8} [{status}] - {pl.description}")
186
+ return 0
187
+
188
+
189
+ def _build_parser() -> argparse.ArgumentParser:
190
+ parser = argparse.ArgumentParser(prog="pcat", add_help=False)
191
+ sub = parser.add_subparsers(dest="command")
192
+
193
+ p_pack = sub.add_parser("pack")
194
+ p_pack.add_argument("source", nargs="?", default=None, help="Project directory or file to pack")
195
+ p_pack.add_argument("-o", "--output", default=None, help="Output folder or base .pcat path")
196
+ p_pack.add_argument("--key", default=None, help="Obfuscation key (defaults to config)")
197
+ p_pack.add_argument(
198
+ "--chunk-kb",
199
+ type=int,
200
+ default=None,
201
+ help="Split module size in KB (0 or -1 = single chunk)",
202
+ )
203
+ p_pack.add_argument("--entry", default=None, help="Entry point file inside project (e.g. main.py)")
204
+ p_pack.add_argument(
205
+ "--data-only",
206
+ action="store_true",
207
+ help="Mark archive as data-only (cannot be launched via 'pcat run')",
208
+ )
209
+ p_pack.add_argument("--profile", default=None, help="Named build profile (dev, release, data, or custom)")
210
+ p_pack.add_argument("--list-profiles", action="store_true", help="List build profiles with descriptions")
211
+
212
+ sub.add_parser("profiles")
213
+
214
+ p_inspect = sub.add_parser("inspect")
215
+ p_inspect.add_argument("archive", help="Path to index .pcat file")
216
+ p_inspect.add_argument("--key", default=None, help="Obfuscation key (defaults to config)")
217
+ p_inspect.add_argument("--json", action="store_true", help="Output inspection report as JSON")
218
+
219
+ p_merge = sub.add_parser("merge")
220
+ p_merge.add_argument("output", help="Merged output .pcat path or directory")
221
+ p_merge.add_argument("archives", nargs="+", help="Source .pcat index files to merge")
222
+ p_merge.add_argument("--key", default=None, help="Obfuscation key (defaults to config)")
223
+ p_merge.add_argument("--chunk-kb", type=int, default=None, help="Output chunk size in KB")
224
+ p_merge.add_argument(
225
+ "--on-conflict",
226
+ default="error",
227
+ choices=["error", "overwrite", "prefix"],
228
+ help="File path conflict strategy across archives",
229
+ )
230
+
231
+ p_split = sub.add_parser("split")
232
+ p_split.add_argument("archive", help="Path to index .pcat file to split")
233
+ p_split.add_argument("-o", "--output", default=None, help="Output directory for split .pcat modules")
234
+ p_split.add_argument("--key", default=None, help="Obfuscation key (defaults to config)")
235
+ p_split.add_argument("--per-file", action="store_true", help="Create one .pcat module per packed file")
236
+ p_split.add_argument("--parts", type=int, default=None, help="Target number of split modules")
237
+
238
+ sub.add_parser("plugins")
239
+ p_plugin = sub.add_parser("plugin")
240
+ pl_sub = p_plugin.add_subparsers(dest="plugin_action")
241
+ pl_sub.add_parser("list")
242
+ p_pl_init = pl_sub.add_parser("init")
243
+ p_pl_init.add_argument("name", help="New plugin name")
244
+ p_pl_init.add_argument("-o", "--output", default=None, help="Target plugins folder")
245
+
246
+ p_run = sub.add_parser("run")
247
+ p_run.add_argument("archive", help="Path to index .pcat file")
248
+ p_run.add_argument("--key", default=None, help="Obfuscation key (defaults to config)")
249
+ p_run.add_argument("--entry", default=None, help="Override entry point file")
250
+ p_run.add_argument("extra_args", nargs=argparse.REMAINDER, help="Arguments passed to script")
251
+
252
+ p_unpack = sub.add_parser("unpack")
253
+ p_unpack.add_argument("archive", help="Path to index .pcat file")
254
+ p_unpack.add_argument("-o", "--output", default=None, help="Destination directory")
255
+ p_unpack.add_argument("--key", default=None, help="Obfuscation key (defaults to config)")
256
+
257
+ p_info = sub.add_parser("info")
258
+ p_info.add_argument("archive", help="Path to index .pcat file")
259
+ p_info.add_argument("--key", default=None, help="Obfuscation key (defaults to config)")
260
+
261
+ p_box = sub.add_parser("box")
262
+ box_sub = p_box.add_subparsers(dest="box_action")
263
+ p_box_up = box_sub.add_parser("up")
264
+ p_box_up.add_argument("source", help="Project directory or .pcat archive")
265
+ p_box_up.add_argument("--key", default=None, help="Obfuscation key for .pcat")
266
+ p_box_up.add_argument("--venv", action="store_true", help="Create isolated venv and install requirements.txt")
267
+
268
+ p_box_run = box_sub.add_parser("run")
269
+ p_box_run.add_argument("source", help="Project directory or .pcat archive")
270
+ p_box_run.add_argument("--key", default=None, help="Obfuscation key for .pcat")
271
+ p_box_run.add_argument("--venv", action="store_true", help="Create isolated venv and install requirements.txt")
272
+ p_box_run.add_argument("--keep", action="store_true", help="Keep workspace copy after run")
273
+ p_box_run.add_argument("extra_args", nargs=argparse.REMAINDER, help="Arguments passed to entry")
274
+
275
+ box_sub.add_parser("ps")
276
+ p_box_logs = box_sub.add_parser("logs")
277
+ p_box_logs.add_argument("target", help="Box ID or name")
278
+ p_box_logs.add_argument("--tail", type=int, default=50, help="Number of last log lines")
279
+ p_box_attach = box_sub.add_parser("attach")
280
+ p_box_attach.add_argument("target", help="Box ID or name")
281
+ p_box_stop = box_sub.add_parser("stop")
282
+ p_box_stop.add_argument("target", help="Box ID or name")
283
+ p_box_rm = box_sub.add_parser("rm")
284
+ p_box_rm.add_argument("target", help="Box ID or name")
285
+ p_box_rm.add_argument("--force", action="store_true", help="Force stop and remove running box")
286
+
287
+ p_cfg = sub.add_parser("config")
288
+ cfg_sub = p_cfg.add_subparsers(dest="cfg_action")
289
+ cfg_sub.add_parser("show")
290
+ p_cfg_set = cfg_sub.add_parser("set")
291
+ p_cfg_set.add_argument("key")
292
+ p_cfg_set.add_argument("value")
293
+ p_cfg_tpl = cfg_sub.add_parser("template")
294
+ tpl_sub = p_cfg_tpl.add_subparsers(dest="tpl_action")
295
+ tpl_sub.add_parser("list")
296
+ p_tpl_add = tpl_sub.add_parser("add")
297
+ p_tpl_add.add_argument("name")
298
+ p_tpl_add.add_argument("path")
299
+ p_tpl_rm = tpl_sub.add_parser("remove")
300
+ p_tpl_rm.add_argument("name")
301
+ cfg_sub.add_parser("reset")
302
+
303
+ # Register dynamic commands provided by loaded plugins
304
+ mgr = get_plugin_manager()
305
+ for cmd_name, reg_cmd in sorted(mgr.commands.items()):
306
+ if cmd_name in BUILTIN_COMMANDS:
307
+ continue
308
+ p_ext = sub.add_parser(cmd_name, help=reg_cmd.help)
309
+ if reg_cmd.parser_setup is not None:
310
+ reg_cmd.parser_setup(p_ext)
311
+
312
+ return parser
313
+
314
+
315
+ def main(argv: list[str] | None = None) -> int:
316
+ args = sys.argv[1:] if argv is None else argv
317
+ if not args:
318
+ print(f"v{version}")
319
+ return 0
320
+ if len(args) == 1 and args[0] in ("-h", "--help", "/?"):
321
+ print(HELP_TEXT.strip())
322
+ return 0
323
+ if len(args) == 1 and args[0] == "-o":
324
+ run_project_cat_terminal(version=version)
325
+ return 0
326
+ if args[0] == "new" or args[0].startswith("new."):
327
+ try:
328
+ tpl, names, out_dir, force, list_only = _parse_new_invocation(args)
329
+ if list_only:
330
+ cfg = load_config()
331
+ print(f"Default template: {cfg.default_template}")
332
+ for tpl_name, kind, info in list_templates():
333
+ print(f" {tpl_name:<12} [{kind}] — {info}")
334
+ return 0
335
+ created_paths = create_many_from_template(
336
+ names=names,
337
+ template_name=tpl,
338
+ output_dir=out_dir,
339
+ force=force,
340
+ )
341
+ for p in created_paths:
342
+ print(f"[CREATED] {p}")
343
+ return 0
344
+ except Exception as exc:
345
+ print(f"[ERR] {exc}")
346
+ return 1
347
+
348
+ mgr = get_plugin_manager()
349
+ known_cmds = BUILTIN_COMMANDS + tuple(mgr.commands.keys())
350
+ if args[0] in known_cmds:
351
+ parser = _build_parser()
352
+ try:
353
+ ns = parser.parse_args(args)
354
+ except SystemExit as exc:
355
+ return exc.code if isinstance(exc.code, int) else 0
356
+ try:
357
+ if ns.command == "plugins":
358
+ return _print_plugins()
359
+
360
+ if ns.command == "plugin":
361
+ if ns.plugin_action in (None, "list"):
362
+ return _print_plugins()
363
+ if ns.plugin_action == "init":
364
+ out_d = Path(ns.output) if ns.output else None
365
+ created = create_plugin_template(ns.name, out_dir=out_d)
366
+ print(f"[PLUGIN CREATED] {created}")
367
+ return 0
368
+ print("[ERR] Usage: pcat plugin {list|init <name>}")
369
+ return 1
370
+
371
+ if ns.command == "profiles" or (ns.command == "pack" and ns.list_profiles):
372
+ return _print_profiles()
373
+
374
+ if ns.command == "pack":
375
+ if not ns.source:
376
+ print("[ERR] Source path is required for 'pcat pack <source>'")
377
+ return 1
378
+ exec_flag: bool | None = False if ns.data_only else None
379
+ res, used_profile = pack_with_profile(
380
+ source_path=ns.source,
381
+ profile_name=ns.profile,
382
+ output_base=ns.output,
383
+ key=ns.key,
384
+ chunk_size_kb=ns.chunk_kb,
385
+ entry_point=ns.entry,
386
+ executable=exec_flag,
387
+ )
388
+ print(f"[PACKED] Index : {res.index_path}")
389
+ if used_profile:
390
+ print(f"[PACKED] Profile : {used_profile}")
391
+ print(f"[PACKED] Modules : {len(res.chunk_paths)} file(s)")
392
+ print(f"[PACKED] Files : {res.file_count}")
393
+ print(f"[PACKED] Executable : {'yes' if res.executable else 'no (data-only)'}")
394
+ print(f"[PACKED] Entry point: {res.entry_point or '-'}")
395
+ print(f"[PACKED] Size : {res.raw_bytes} B -> {res.packed_bytes} B")
396
+ return 0
397
+
398
+ if ns.command == "inspect":
399
+ rep = inspect_archive(ns.archive, key=ns.key)
400
+ if ns.json:
401
+ print(json.dumps(rep.to_dict(), ensure_ascii=False, indent=2))
402
+ return 0 if rep.ok else 1
403
+ print(f"Archive : {rep.index_path}")
404
+ print(f"Project : {rep.project}")
405
+ print(f"Profile : {rep.profile or '-'}")
406
+ print(f"Executable : {'yes' if rep.executable else 'no (data-only)'}")
407
+ print(f"Entry point : {rep.entry_point or '-'}")
408
+ print(
409
+ f"Sizes : raw={rep.raw_bytes} B | compressed={rep.compressed_bytes} B | "
410
+ f"index={rep.index_bytes} B | chunks={rep.chunks_total_bytes} B"
411
+ )
412
+ print(f"Integrity : {'OK' if rep.ok else 'FAILED'}")
413
+ print(f"Chunks ({len(rep.chunks)}):")
414
+ for c in rep.chunks:
415
+ print(
416
+ f" #{c['index']:03d} {c['file']:<28} "
417
+ f"manifest={c['manifest_size']} B disk={c['disk_size']} B "
418
+ f"[{c['status']}] sha256={c['sha256'][:12]}..."
419
+ )
420
+ print(f"Files ({len(rep.files)}):")
421
+ for f_item in rep.files:
422
+ print(
423
+ f" - {f_item['path']:<32} {f_item['size']:>7} B "
424
+ f"[{f_item['status']}] sha256={f_item['sha256'][:12]}..."
425
+ )
426
+ if rep.issues:
427
+ print("Issues:")
428
+ for issue in rep.issues:
429
+ print(f" [ERR] {issue}")
430
+ return 0 if rep.ok else 1
431
+
432
+ if ns.command == "merge":
433
+ res = merge_archives(
434
+ archive_paths=ns.archives,
435
+ output_base=ns.output,
436
+ key=ns.key,
437
+ chunk_size_kb=ns.chunk_kb,
438
+ on_conflict=ns.on_conflict,
439
+ )
440
+ print(f"[MERGED] Index : {res.index_path}")
441
+ print(f"[MERGED] Modules : {len(res.chunk_paths)} file(s)")
442
+ print(f"[MERGED] Files : {res.file_count}")
443
+ print(f"[MERGED] Size : {res.raw_bytes} B -> {res.packed_bytes} B")
444
+ return 0
445
+
446
+ if ns.command == "split":
447
+ parts = split_archive(
448
+ index_file=ns.archive,
449
+ output_dir=ns.output,
450
+ key=ns.key,
451
+ per_file=ns.per_file,
452
+ num_parts=ns.parts,
453
+ )
454
+ print(f"[SPLIT] Created {len(parts)} module bundle(s):")
455
+ for p_res in parts:
456
+ print(f" - {p_res.index_path} ({p_res.file_count} file(s), {p_res.packed_bytes} B)")
457
+ return 0
458
+
459
+ if ns.command == "run":
460
+ forwarded = list(ns.extra_args)
461
+ if forwarded and forwarded[0] == "--":
462
+ forwarded = forwarded[1:]
463
+ return run_project(
464
+ index_file=ns.archive,
465
+ key=ns.key,
466
+ entry_override=ns.entry,
467
+ extra_args=forwarded,
468
+ )
469
+ if ns.command == "unpack":
470
+ out_dir, count = unpack_project(
471
+ index_file=ns.archive,
472
+ target_dir=ns.output,
473
+ key=ns.key,
474
+ )
475
+ print(f"[UNPACKED] {count} file(s) extracted to: {out_dir}")
476
+ return 0
477
+ if ns.command == "info":
478
+ idx_path, _, manifest = read_manifest(ns.archive, key=ns.key)
479
+ print(f"Archive : {idx_path}")
480
+ print(f"Project : {manifest['project']}")
481
+ print(f"Executable : {'yes' if manifest.get('executable', True) else 'no (data-only)'}")
482
+ print(f"Entry point : {manifest.get('entry_point') or '-'}")
483
+ print(f"Modules : {len(manifest['chunks'])} (.pcat)")
484
+ print(f"Files : {len(manifest['files'])} ({manifest['raw_size']} B raw)")
485
+ for f_item in manifest["files"]:
486
+ print(f" - {f_item['path']} ({f_item['size']} B)")
487
+ return 0
488
+ if ns.command == "box":
489
+ if ns.box_action == "up":
490
+ rec = box_up(ns.source, key=ns.key, use_venv=ns.venv)
491
+ print(f"[BOX UP] {rec.box_id} ({rec.name}) PID={rec.pid} entry={rec.entry}")
492
+ return 0
493
+ if ns.box_action == "run":
494
+ forwarded = list(ns.extra_args)
495
+ if forwarded and forwarded[0] == "--":
496
+ forwarded = forwarded[1:]
497
+ return box_run_foreground(
498
+ ns.source,
499
+ key=ns.key,
500
+ use_venv=ns.venv,
501
+ keep_workspace=ns.keep,
502
+ extra_args=forwarded,
503
+ )
504
+ if ns.box_action == "ps":
505
+ rows = box_ps()
506
+ if not rows:
507
+ print("No boxes found.")
508
+ return 0
509
+ for r in rows:
510
+ pid_str = str(r.pid) if r.pid else "-"
511
+ print(f"{r.box_id:<11} {r.name:<18} {r.status:<8} PID={pid_str:<7} entry={r.entry}")
512
+ return 0
513
+ if ns.box_action == "logs":
514
+ rec, out_t, err_t = box_logs(ns.target, tail=ns.tail)
515
+ print(f"=== Box {rec.box_id} ({rec.name}) [{rec.status}] ===")
516
+ if out_t:
517
+ print("--- stdout ---")
518
+ print(out_t)
519
+ if err_t:
520
+ print("--- stderr ---")
521
+ print(err_t)
522
+ return 0
523
+ if ns.box_action == "attach":
524
+ return box_attach(ns.target)
525
+ if ns.box_action == "stop":
526
+ rec = box_stop(ns.target)
527
+ print(f"[BOX STOPPED] {rec.box_id} ({rec.name})")
528
+ return 0
529
+ if ns.box_action == "rm":
530
+ rec = box_rm(ns.target, force=ns.force)
531
+ print(f"[BOX REMOVED] {rec.box_id} ({rec.name})")
532
+ return 0
533
+ print("[ERR] Usage: pcat box {up|run|ps|logs|attach|stop|rm}")
534
+ return 1
535
+ if ns.command == "config":
536
+ if ns.cfg_action == "show" or ns.cfg_action is None:
537
+ cfg = load_config()
538
+ print(f"Config path : {DEFAULT_CONFIG_PATH}")
539
+ for k, v in cfg.to_dict().items():
540
+ print(f" {k} = {v}")
541
+ return 0
542
+ if ns.cfg_action == "set":
543
+ cfg = set_config_value(ns.key, ns.value)
544
+ print(f"[SAVED] {DEFAULT_CONFIG_PATH}")
545
+ for k, v in cfg.to_dict().items():
546
+ print(f" {k} = {v}")
547
+ return 0
548
+ if ns.cfg_action == "template":
549
+ if ns.tpl_action == "add":
550
+ cfg = add_custom_template(ns.name, ns.path)
551
+ print(f"[ADDED] template '{ns.name.lower()}' -> {cfg.custom_templates[ns.name.lower()]}")
552
+ return 0
553
+ if ns.tpl_action == "remove":
554
+ remove_custom_template(ns.name)
555
+ print(f"[REMOVED] template '{ns.name.lower()}'")
556
+ return 0
557
+ cfg = load_config()
558
+ if not cfg.custom_templates:
559
+ print("No custom templates configured.")
560
+ else:
561
+ for t_name, t_path in sorted(cfg.custom_templates.items()):
562
+ print(f" {t_name} -> {t_path}")
563
+ return 0
564
+ if ns.cfg_action == "reset":
565
+ cfg = reset_config()
566
+ print(f"[RESET] {DEFAULT_CONFIG_PATH}")
567
+ for k, v in cfg.to_dict().items():
568
+ print(f" {k} = {v}")
569
+ return 0
570
+
571
+ if ns.command in mgr.commands:
572
+ return int(mgr.commands[ns.command].handler(ns))
573
+ except Exception as exc:
574
+ print(f"[ERR] {exc}")
575
+ return 1
576
+
577
+ print(f"Unknown argument: {' '.join(args)}")
578
+ print("Use 'pcat -h' or 'pcat --help' to see available commands.")
579
+ return 1
580
+
581
+
582
+ if __name__ == "__main__":
583
+ raise SystemExit(main())