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/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ __version__ = "1.0.2"
2
+ __app_name__ = "ProjectCats"
pcat/box.py ADDED
@@ -0,0 +1,554 @@
1
+ # pcat/box.py
2
+ from __future__ import annotations
3
+ import json
4
+ import os
5
+ import platform
6
+ import shutil
7
+ import signal
8
+ import socket
9
+ import subprocess
10
+ import sys
11
+ import tempfile
12
+ import threading
13
+ import time
14
+ import uuid
15
+ from dataclasses import asdict, dataclass
16
+ from pathlib import Path
17
+ from typing import Any
18
+ from pcat.packer import unpack_project
19
+
20
+ BOXES_ROOT = Path.home() / ".pcat" / "boxes"
21
+ BOXES_STATE_FILE = Path.home() / ".pcat" / "boxes.json"
22
+
23
+ @dataclass
24
+ class BoxRecord:
25
+ box_id: str
26
+ name: str
27
+ status: str # "running" | "stopped"
28
+ pid: int | None
29
+ created_at: int
30
+ source_path: str
31
+ workspace_dir: str
32
+ entry: str
33
+ runtime: str
34
+ stdout_log: str
35
+ stderr_log: str
36
+ console_port: int | None = None
37
+
38
+ def to_dict(self) -> dict[str, Any]:
39
+ return asdict(self)
40
+
41
+ def _load_boxes_state() -> list[BoxRecord]:
42
+ if not BOXES_STATE_FILE.is_file():
43
+ return []
44
+ try:
45
+ raw = json.loads(BOXES_STATE_FILE.read_text(encoding="utf-8"))
46
+ if not isinstance(raw, list):
47
+ return []
48
+ records: list[BoxRecord] = []
49
+ for item in raw:
50
+ if isinstance(item, dict) and "box_id" in item:
51
+ records.append(
52
+ BoxRecord(
53
+ box_id=str(item["box_id"]),
54
+ name=str(item.get("name", item["box_id"])),
55
+ status=str(item.get("status", "stopped")),
56
+ pid=item.get("pid") if isinstance(item.get("pid"), int) else None,
57
+ created_at=int(item.get("created_at", 0)),
58
+ source_path=str(item.get("source_path", "")),
59
+ workspace_dir=str(item.get("workspace_dir", "")),
60
+ entry=str(item.get("entry", "main.py")),
61
+ runtime=str(item.get("runtime", "python")),
62
+ stdout_log=str(item.get("stdout_log", "")),
63
+ stderr_log=str(item.get("stderr_log", "")),
64
+ console_port=(
65
+ item.get("console_port")
66
+ if isinstance(item.get("console_port"), int)
67
+ else None
68
+ ),
69
+ )
70
+ )
71
+ return records
72
+ except Exception:
73
+ return []
74
+
75
+ def _save_boxes_state(records: list[BoxRecord]) -> None:
76
+ BOXES_STATE_FILE.parent.mkdir(parents=True, exist_ok=True)
77
+ BOXES_STATE_FILE.write_text(
78
+ json.dumps([r.to_dict() for r in records], ensure_ascii=False, indent=2) + "\n",
79
+ encoding="utf-8",
80
+ )
81
+
82
+ def _decode_win_output(raw: bytes) -> str:
83
+ for enc in ("cp866", "cp1251", "utf-8"):
84
+ try:
85
+ return raw.decode(enc)
86
+ except UnicodeDecodeError:
87
+ continue
88
+ return raw.decode("cp866", errors="replace")
89
+
90
+ def _is_pid_running(pid: int | None) -> bool:
91
+ if not pid or pid <= 0:
92
+ return False
93
+ if platform.system().lower().startswith("win"):
94
+ try:
95
+ proc = subprocess.run(
96
+ ["tasklist", "/FI", f"PID eq {pid}", "/NH"],
97
+ capture_output=True,
98
+ timeout=5,
99
+ )
100
+ out = _decode_win_output(proc.stdout)
101
+ return str(pid) in out
102
+ except Exception:
103
+ return False
104
+ try:
105
+ os.kill(pid, 0)
106
+ return True
107
+ except ProcessLookupError:
108
+ return False
109
+ except PermissionError:
110
+ return True
111
+ except Exception:
112
+ return False
113
+
114
+ def _kill_pid(pid: int | None) -> bool:
115
+ if not pid or pid <= 0:
116
+ return False
117
+ if platform.system().lower().startswith("win"):
118
+ try:
119
+ subprocess.run(
120
+ ["taskkill", "/F", "/T", "/PID", str(pid)],
121
+ stdout=subprocess.DEVNULL,
122
+ stderr=subprocess.DEVNULL,
123
+ timeout=8,
124
+ )
125
+ return True
126
+ except Exception:
127
+ return False
128
+ try:
129
+ os.kill(pid, signal.SIGTERM)
130
+ time.sleep(0.2)
131
+ if _is_pid_running(pid):
132
+ os.kill(pid, signal.SIGKILL)
133
+ return True
134
+ except Exception:
135
+ return False
136
+
137
+ def _refresh_statuses(records: list[BoxRecord]) -> list[BoxRecord]:
138
+ changed = False
139
+ for rec in records:
140
+ if rec.status == "running" and not _is_pid_running(rec.pid):
141
+ rec.status = "stopped"
142
+ rec.pid = None
143
+ rec.console_port = None
144
+ changed = True
145
+ if changed:
146
+ _save_boxes_state(records)
147
+ return records
148
+
149
+ def _find_box(records: list[BoxRecord], identifier: str) -> BoxRecord:
150
+ ident = identifier.strip()
151
+ for rec in records:
152
+ if rec.box_id == ident or rec.box_id.startswith(ident):
153
+ return rec
154
+ for rec in records:
155
+ if rec.name == ident:
156
+ return rec
157
+ raise KeyError(f"Box not found: '{identifier}'")
158
+
159
+ def _load_box_manifest(workspace_dir: Path, default_name: str) -> dict[str, Any]:
160
+ cfg_file = workspace_dir / "pcatbox.json"
161
+ manifest: dict[str, Any] = {
162
+ "name": default_name,
163
+ "runtime": "python",
164
+ "entry": "main.py",
165
+ "workdir": ".",
166
+ "env": {},
167
+ "requirements": None,
168
+ }
169
+ if cfg_file.is_file():
170
+ loaded = json.loads(cfg_file.read_text(encoding="utf-8"))
171
+ if isinstance(loaded, dict):
172
+ manifest.update({k: v for k, v in loaded.items() if v is not None})
173
+ if not isinstance(manifest.get("env"), dict):
174
+ manifest["env"] = {}
175
+ return manifest
176
+
177
+ def _prepare_workspace(
178
+ source_path: str | Path,
179
+ dest_workspace: Path,
180
+ key: str | None = None,
181
+ ) -> tuple[str, dict[str, Any]]:
182
+ src = Path(source_path).resolve()
183
+ if not src.exists():
184
+ raise FileNotFoundError(f"Source not found: {src}")
185
+ if dest_workspace.exists():
186
+ shutil.rmtree(dest_workspace)
187
+ dest_workspace.mkdir(parents=True, exist_ok=True)
188
+ if src.is_file() and src.suffix.lower() == ".pcat":
189
+ unpack_project(index_file=src, target_dir=dest_workspace, key=key)
190
+ base_name = src.stem
191
+ elif src.is_file():
192
+ shutil.copy2(src, dest_workspace / src.name)
193
+ base_name = src.stem
194
+ else:
195
+ ignore_names = {
196
+ ".git", "__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache",
197
+ "venv", ".venv", "node_modules",
198
+ }
199
+ def _ignore(dirpath: str, names: list[str]) -> set[str]:
200
+ return {n for n in names if n in ignore_names or n.endswith(".pyc")}
201
+ shutil.copytree(src, dest_workspace, ignore=_ignore, dirs_exist_ok=True)
202
+ base_name = src.name
203
+ manifest = _load_box_manifest(dest_workspace, default_name=base_name)
204
+ box_name = str(manifest.get("name") or base_name)
205
+ return box_name, manifest
206
+
207
+ def _maybe_setup_venv(workspace_dir: Path, manifest: dict[str, Any], use_venv: bool) -> Path | None:
208
+ if not use_venv:
209
+ return None
210
+ req_rel = manifest.get("requirements") or "requirements.txt"
211
+ req_file = workspace_dir / str(req_rel)
212
+ venv_dir = workspace_dir / ".pcat_venv"
213
+ python_exe = sys.executable or "python"
214
+ if not venv_dir.exists():
215
+ subprocess.run([python_exe, "-m", "venv", str(venv_dir)], check=True)
216
+ venv_py = (
217
+ venv_dir / "Scripts" / "python.exe"
218
+ if platform.system().lower().startswith("win")
219
+ else venv_dir / "bin" / "python"
220
+ )
221
+ if req_file.is_file():
222
+ content = req_file.read_text(encoding="utf-8").strip()
223
+ if content:
224
+ subprocess.run([str(venv_py), "-m", "pip", "install", "-q", "-r", str(req_file)], check=True)
225
+ return venv_py if venv_py.is_file() else None
226
+
227
+ def _build_box_env(
228
+ manifest: dict[str, Any],
229
+ box_id: str,
230
+ workdir: Path,
231
+ console_port: int | None = None,
232
+ ) -> dict[str, str]:
233
+ env = os.environ.copy()
234
+ env["PCAT_BOX"] = "1"
235
+ env["PCAT_BOX_ID"] = box_id
236
+ env["PCAT_BOX_WORKDIR"] = str(workdir)
237
+ if console_port is not None:
238
+ env["PCAT_BOX_CONSOLE_PORT"] = str(console_port)
239
+ env["PYTHONUTF8"] = "1"
240
+ env["PYTHONIOENCODING"] = "utf-8"
241
+ raw_env = manifest.get("env") or {}
242
+ for k, v in raw_env.items():
243
+ env[str(k)] = str(v)
244
+ return env
245
+
246
+ def _build_launch_cmd(
247
+ runtime: str,
248
+ entry: str,
249
+ workdir: Path,
250
+ venv_python: Path | None,
251
+ extra_args: list[str],
252
+ ) -> list[str]:
253
+ rt = runtime.strip().lower()
254
+ script_target = str((workdir / entry).resolve()) if not os.path.isabs(entry) else entry
255
+ py_bin = str(venv_python) if venv_python else (sys.executable or "python")
256
+ if rt in ("python", "py"):
257
+ return [py_bin, "-u", script_target, *extra_args]
258
+ if rt in ("cmd", "shell", "sh"):
259
+ full_cmd = f"{entry} {' '.join(extra_args)}".strip()
260
+ if platform.system().lower().startswith("win"):
261
+ return ["cmd.exe", "/c", full_cmd]
262
+ return ["/bin/sh", "-c", full_cmd]
263
+ if rt in ("ps", "powershell", "pwsh"):
264
+ ps_bin = "powershell" if platform.system().lower().startswith("win") else "pwsh"
265
+ full_cmd = f"{entry} {' '.join(extra_args)}".strip()
266
+ return [ps_bin, "-NoProfile", "-Command", full_cmd]
267
+ raise ValueError(f"Unsupported runtime in pcatbox.json: '{runtime}'")
268
+
269
+ def _start_box_console(
270
+ proc: subprocess.Popen[bytes],
271
+ stdout_log: Path,
272
+ stderr_log: Path,
273
+ sock: socket.socket,
274
+ ) -> tuple[int, list[threading.Thread]]:
275
+ port = sock.getsockname()[1]
276
+ clients: list[socket.socket] = []
277
+ clients_lock = threading.Lock()
278
+
279
+ def _broadcast(data: bytes) -> None:
280
+ with clients_lock:
281
+ dead = []
282
+ for c in clients:
283
+ try:
284
+ c.sendall(data)
285
+ except OSError:
286
+ dead.append(c)
287
+ for c in dead:
288
+ clients.remove(c)
289
+
290
+ def _accept_loop() -> None:
291
+ while proc.poll() is None:
292
+ try:
293
+ conn, _ = sock.accept()
294
+ with clients_lock:
295
+ clients.append(conn)
296
+
297
+ def _client_reader(c: socket.socket) -> None:
298
+ try:
299
+ while proc.poll() is None:
300
+ data = c.recv(4096)
301
+ if not data:
302
+ break
303
+ if proc.stdin and not proc.stdin.closed:
304
+ proc.stdin.write(data)
305
+ proc.stdin.flush()
306
+ except OSError:
307
+ pass
308
+ finally:
309
+ with clients_lock:
310
+ if c in clients:
311
+ clients.remove(c)
312
+ try:
313
+ c.close()
314
+ except OSError:
315
+ pass
316
+
317
+ threading.Thread(target=_client_reader, args=(conn,), daemon=True).start()
318
+ except socket.timeout:
319
+ continue
320
+ except OSError:
321
+ break
322
+ try:
323
+ sock.close()
324
+ except OSError:
325
+ pass
326
+
327
+ def _pipe_reader(pipe, log_file: Path) -> None:
328
+ try:
329
+ with open(log_file, "ab") as f:
330
+ while True:
331
+ data = pipe.read(1024)
332
+ if not data:
333
+ break
334
+ f.write(data)
335
+ f.flush()
336
+ _broadcast(data)
337
+ except Exception:
338
+ pass
339
+
340
+ threads = []
341
+ t_accept = threading.Thread(target=_accept_loop, daemon=True)
342
+ t_accept.start()
343
+ threads.append(t_accept)
344
+
345
+ if proc.stdout:
346
+ t_out = threading.Thread(target=_pipe_reader, args=(proc.stdout, stdout_log), daemon=True)
347
+ t_out.start()
348
+ threads.append(t_out)
349
+
350
+ if proc.stderr:
351
+ t_err = threading.Thread(target=_pipe_reader, args=(proc.stderr, stderr_log), daemon=True)
352
+ t_err.start()
353
+ threads.append(t_err)
354
+
355
+ return port, threads
356
+
357
+ def box_up(
358
+ source_path: str | Path,
359
+ key: str | None = None,
360
+ use_venv: bool = False,
361
+ ) -> BoxRecord:
362
+ box_id = uuid.uuid4().hex[:10]
363
+ box_dir = BOXES_ROOT / box_id
364
+ workspace_dir = box_dir / "workspace"
365
+ stdout_log = box_dir / "stdout.log"
366
+ stderr_log = box_dir / "stderr.log"
367
+ box_name, manifest = _prepare_workspace(source_path, workspace_dir, key=key)
368
+ workdir_rel = str(manifest.get("workdir") or ".")
369
+ workdir = (workspace_dir / workdir_rel).resolve()
370
+ workdir.mkdir(parents=True, exist_ok=True)
371
+ venv_py = _maybe_setup_venv(workspace_dir, manifest, use_venv=use_venv)
372
+ runtime = str(manifest.get("runtime") or "python")
373
+ entry = str(manifest.get("entry") or "main.py")
374
+
375
+ stdout_log.parent.mkdir(parents=True, exist_ok=True)
376
+
377
+ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
378
+ sock.bind(("127.0.0.1", 0))
379
+ sock.listen(16)
380
+ sock.settimeout(0.5)
381
+ console_port = sock.getsockname()[1]
382
+
383
+ env = _build_box_env(manifest, box_id=box_id, workdir=workdir, console_port=console_port)
384
+ cmd = _build_launch_cmd(runtime, entry, workdir, venv_py, extra_args=[])
385
+
386
+ creationflags = 0
387
+ if platform.system().lower().startswith("win"):
388
+ creationflags = subprocess.CREATE_NEW_PROCESS_GROUP
389
+
390
+ proc = subprocess.Popen(
391
+ cmd,
392
+ cwd=str(workdir),
393
+ env=env,
394
+ stdin=subprocess.PIPE,
395
+ stdout=subprocess.PIPE,
396
+ stderr=subprocess.PIPE,
397
+ bufsize=0,
398
+ creationflags=creationflags,
399
+ )
400
+
401
+ port, _ = _start_box_console(proc, stdout_log, stderr_log, sock)
402
+
403
+ rec = BoxRecord(
404
+ box_id=box_id,
405
+ name=box_name,
406
+ status="running",
407
+ pid=proc.pid,
408
+ created_at=int(time.time()),
409
+ source_path=str(Path(source_path).resolve()),
410
+ workspace_dir=str(workspace_dir),
411
+ entry=entry,
412
+ runtime=runtime,
413
+ stdout_log=str(stdout_log),
414
+ stderr_log=str(stderr_log),
415
+ console_port=port,
416
+ )
417
+ records = _refresh_statuses(_load_boxes_state())
418
+ records.append(rec)
419
+ _save_boxes_state(records)
420
+ return rec
421
+
422
+ def box_attach(identifier: str) -> int:
423
+ records = _refresh_statuses(_load_boxes_state())
424
+ rec = _find_box(records, identifier)
425
+ if rec.status != "running" or not rec.console_port:
426
+ raise RuntimeError(f"Box '{rec.box_id}' ({rec.name}) is not running or has no console port.")
427
+
428
+ print(f"[ATTACHED] Box {rec.box_id} ({rec.name}) @ 127.0.0.1:{rec.console_port} (type a line + Enter; Ctrl+C to detach)")
429
+
430
+ stop_event = threading.Event()
431
+ try:
432
+ client = socket.create_connection(("127.0.0.1", rec.console_port), timeout=2)
433
+ client.settimeout(0.2)
434
+ except Exception as e:
435
+ raise RuntimeError(f"Failed to connect to box console: {e}")
436
+
437
+ def _input_pump() -> None:
438
+ while not stop_event.is_set():
439
+ try:
440
+ line = sys.stdin.readline()
441
+ if not line:
442
+ time.sleep(0.05)
443
+ continue
444
+ client.sendall(line.encode("utf-8"))
445
+ except OSError:
446
+ break
447
+ except Exception:
448
+ break
449
+
450
+ pump_thread = threading.Thread(target=_input_pump, daemon=True)
451
+ pump_thread.start()
452
+
453
+ try:
454
+ buf = bytearray()
455
+ while not stop_event.is_set():
456
+ try:
457
+ data = client.recv(4096)
458
+ if not data:
459
+ break
460
+ buf.extend(data)
461
+ while b"\n" in buf:
462
+ line, buf = buf.split(b"\n", 1)
463
+ sys.stdout.write(line.decode("utf-8", errors="replace").rstrip("\r") + "\n")
464
+ sys.stdout.flush()
465
+ except socket.timeout:
466
+ continue
467
+ except OSError:
468
+ break
469
+
470
+ if buf:
471
+ sys.stdout.write(buf.decode("utf-8", errors="replace").rstrip("\r") + "\n")
472
+ sys.stdout.flush()
473
+
474
+ except KeyboardInterrupt:
475
+ print("\n[DETACHED]")
476
+ finally:
477
+ stop_event.set()
478
+ try:
479
+ client.close()
480
+ except Exception:
481
+ pass
482
+
483
+ return 0
484
+
485
+ def box_run_foreground(
486
+ source_path: str | Path,
487
+ key: str | None = None,
488
+ use_venv: bool = False,
489
+ keep_workspace: bool = False,
490
+ extra_args: list[str] | None = None,
491
+ ) -> int:
492
+ box_id = uuid.uuid4().hex[:10]
493
+ tmp_ctx = tempfile.TemporaryDirectory(prefix=f"pcat_box_{box_id}_")
494
+ try:
495
+ workspace_dir = Path(tmp_ctx.name) / "workspace"
496
+ _, manifest = _prepare_workspace(source_path, workspace_dir, key=key)
497
+ workdir_rel = str(manifest.get("workdir") or ".")
498
+ workdir = (workspace_dir / workdir_rel).resolve()
499
+ workdir.mkdir(parents=True, exist_ok=True)
500
+ venv_py = _maybe_setup_venv(workspace_dir, manifest, use_venv=use_venv)
501
+ runtime = str(manifest.get("runtime") or "python")
502
+ entry = str(manifest.get("entry") or "main.py")
503
+ env = _build_box_env(manifest, box_id=box_id, workdir=workdir)
504
+ cmd = _build_launch_cmd(runtime, entry, workdir, venv_py, extra_args=extra_args or [])
505
+ proc = subprocess.run(cmd, cwd=str(workdir), env=env)
506
+ if keep_workspace:
507
+ persist_dir = BOXES_ROOT / box_id / "workspace"
508
+ persist_dir.parent.mkdir(parents=True, exist_ok=True)
509
+ shutil.copytree(workspace_dir, persist_dir, dirs_exist_ok=True)
510
+ return proc.returncode
511
+ finally:
512
+ tmp_ctx.cleanup()
513
+
514
+ def box_ps() -> list[BoxRecord]:
515
+ return _refresh_statuses(_load_boxes_state())
516
+
517
+ def box_logs(identifier: str, tail: int = 50) -> tuple[BoxRecord, str, str]:
518
+ records = _refresh_statuses(_load_boxes_state())
519
+ rec = _find_box(records, identifier)
520
+ out_text = ""
521
+ err_text = ""
522
+ if rec.stdout_log and Path(rec.stdout_log).is_file():
523
+ lines = Path(rec.stdout_log).read_text(encoding="utf-8", errors="replace").splitlines()
524
+ out_text = "\n".join(lines[-max(1, tail) :])
525
+ if rec.stderr_log and Path(rec.stderr_log).is_file():
526
+ lines = Path(rec.stderr_log).read_text(encoding="utf-8", errors="replace").splitlines()
527
+ err_text = "\n".join(lines[-max(1, tail) :])
528
+ return rec, out_text, err_text
529
+
530
+ def box_stop(identifier: str) -> BoxRecord:
531
+ records = _refresh_statuses(_load_boxes_state())
532
+ rec = _find_box(records, identifier)
533
+ if rec.status == "running" and rec.pid:
534
+ _kill_pid(rec.pid)
535
+ rec.status = "stopped"
536
+ rec.pid = None
537
+ rec.console_port = None
538
+ _save_boxes_state(records)
539
+ return rec
540
+
541
+ def box_rm(identifier: str, force: bool = False) -> BoxRecord:
542
+ records = _refresh_statuses(_load_boxes_state())
543
+ rec = _find_box(records, identifier)
544
+ if rec.status == "running":
545
+ if not force:
546
+ raise RuntimeError(f"Box '{rec.box_id}' ({rec.name}) is running. Stop it first or pass --force.")
547
+ _kill_pid(rec.pid)
548
+ ws_path = Path(rec.workspace_dir)
549
+ box_container_dir = ws_path.parent if ws_path.name == "workspace" else ws_path
550
+ if str(box_container_dir.resolve()).startswith(str(BOXES_ROOT.resolve())) and box_container_dir.exists():
551
+ shutil.rmtree(box_container_dir, ignore_errors=True)
552
+ records = [r for r in records if r.box_id != rec.box_id]
553
+ _save_boxes_state(records)
554
+ return rec