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/packer.py ADDED
@@ -0,0 +1,364 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ import os
6
+ import struct
7
+ import subprocess
8
+ import sys
9
+ import tempfile
10
+ import time
11
+ import zlib
12
+ from dataclasses import dataclass
13
+ from pathlib import Path
14
+
15
+ from pcat.config import load_config
16
+
17
+ MAGIC_INDEX = b"PCATIDX\x01"
18
+ MAGIC_CHUNK = b"PCATMOD\x01"
19
+
20
+ DEFAULT_IGNORE_DIRS = {
21
+ ".git",
22
+ ".hg",
23
+ ".svn",
24
+ "__pycache__",
25
+ ".pytest_cache",
26
+ ".mypy_cache",
27
+ ".ruff_cache",
28
+ "venv",
29
+ ".venv",
30
+ "env",
31
+ "node_modules",
32
+ "dist",
33
+ "build",
34
+ ".idea",
35
+ ".vscode",
36
+ }
37
+
38
+ DEFAULT_IGNORE_EXTS = {".pyc", ".pyo", ".pyd"}
39
+
40
+
41
+ @dataclass
42
+ class PackResult:
43
+ index_path: Path
44
+ chunk_paths: list[Path]
45
+ file_count: int
46
+ raw_bytes: int
47
+ packed_bytes: int
48
+ executable: bool
49
+ entry_point: str | None
50
+
51
+
52
+ def _derive_keystream(key: str, salt: bytes, chunk_index: int, length: int) -> bytes:
53
+ seed = hashlib.sha256(
54
+ key.encode("utf-8") + b":" + salt + b":" + struct.pack("<I", chunk_index)
55
+ ).digest()
56
+ out = bytearray()
57
+ counter = 0
58
+ while len(out) < length:
59
+ block = hashlib.sha256(seed + struct.pack("<I", counter)).digest()
60
+ out.extend(block)
61
+ counter += 1
62
+ return bytes(out[:length])
63
+
64
+
65
+ def _xor_transform(data: bytes, key: str, salt: bytes, chunk_index: int) -> bytes:
66
+ if not data:
67
+ return b""
68
+ ks = _derive_keystream(key=key, salt=salt, chunk_index=chunk_index, length=len(data))
69
+ return bytes(a ^ b for a, b in zip(data, ks))
70
+
71
+
72
+ def _collect_files(source_dir: Path) -> list[tuple[str, Path]]:
73
+ collected: list[tuple[str, Path]] = []
74
+ for root, dirs, files in os.walk(source_dir):
75
+ dirs[:] = [d for d in dirs if d not in DEFAULT_IGNORE_DIRS and not d.endswith(".egg-info")]
76
+ dirs.sort()
77
+ files.sort()
78
+ for fname in files:
79
+ full_path = Path(root) / fname
80
+ if full_path.suffix.lower() in DEFAULT_IGNORE_EXTS:
81
+ continue
82
+ if full_path.suffix.lower() == ".pcat":
83
+ continue
84
+ rel_path = full_path.relative_to(source_dir).as_posix()
85
+ collected.append((rel_path, full_path))
86
+ return collected
87
+
88
+
89
+ def _normalize_rel_path(raw_path: str) -> str:
90
+ return raw_path.strip().replace("\\", "/").lstrip("./")
91
+
92
+
93
+ def pack_project(
94
+ source_path: str | Path,
95
+ output_base: str | Path | None = None,
96
+ key: str | None = None,
97
+ chunk_size_kb: int | None = None,
98
+ entry_point: str | None = None,
99
+ executable: bool = True,
100
+ ) -> PackResult:
101
+ cfg = load_config()
102
+ eff_key = cfg.default_key if key is None else key
103
+ eff_chunk_kb = cfg.chunk_kb if chunk_size_kb is None else chunk_size_kb
104
+
105
+ src = Path(source_path).resolve()
106
+ if not src.exists():
107
+ raise FileNotFoundError(f"Source path not found: {src}")
108
+
109
+ if src.is_file():
110
+ files = [(src.name, src)]
111
+ default_name = src.stem
112
+ else:
113
+ files = _collect_files(src)
114
+ default_name = src.name
115
+
116
+ if not files:
117
+ raise ValueError(f"No packable files found in: {src}")
118
+
119
+ packed_rel_paths = {rel for rel, _ in files}
120
+ norm_entry: str | None = None
121
+
122
+ if executable:
123
+ if entry_point:
124
+ norm_entry = _normalize_rel_path(entry_point)
125
+ if norm_entry not in packed_rel_paths:
126
+ raise ValueError(f"Entry point '{norm_entry}' not found in packed files")
127
+ elif src.is_file():
128
+ norm_entry = src.name
129
+ else:
130
+ for candidate in ("main.py", "app.py", "run.py", "cli.py"):
131
+ if candidate in packed_rel_paths:
132
+ norm_entry = candidate
133
+ break
134
+ if norm_entry is None:
135
+ raise ValueError(
136
+ "Executable project requires --entry <file.py> (no main.py/app.py/run.py/cli.py found)"
137
+ )
138
+ else:
139
+ norm_entry = _normalize_rel_path(entry_point) if entry_point else None
140
+
141
+ if output_base is None:
142
+ out_dir = Path.cwd() / "dist_pcat"
143
+ base_name = default_name
144
+ else:
145
+ out_p = Path(output_base).resolve()
146
+ if out_p.suffix.lower() == ".pcat":
147
+ out_dir = out_p.parent
148
+ base_name = out_p.stem
149
+ else:
150
+ out_dir = out_p
151
+ base_name = default_name
152
+
153
+ out_dir.mkdir(parents=True, exist_ok=True)
154
+
155
+ payload_buf = bytearray()
156
+ manifest_entries: list[dict] = []
157
+ total_raw = 0
158
+
159
+ for rel_path, full_path in files:
160
+ raw = full_path.read_bytes()
161
+ sha256 = hashlib.sha256(raw).hexdigest()
162
+ offset = len(payload_buf)
163
+ size = len(raw)
164
+ payload_buf.extend(raw)
165
+ total_raw += size
166
+ manifest_entries.append(
167
+ {
168
+ "path": rel_path,
169
+ "offset": offset,
170
+ "size": size,
171
+ "sha256": sha256,
172
+ }
173
+ )
174
+
175
+ compressed = zlib.compress(bytes(payload_buf), level=9)
176
+ salt = os.urandom(16)
177
+
178
+ if eff_chunk_kb <= 0:
179
+ slices = [compressed]
180
+ else:
181
+ chunk_bytes = max(1, eff_chunk_kb) * 1024
182
+ slices = [compressed[i : i + chunk_bytes] for i in range(0, len(compressed), chunk_bytes)]
183
+ if not slices:
184
+ slices = [b""]
185
+
186
+ chunk_paths: list[Path] = []
187
+ chunk_meta: list[dict] = []
188
+ total_packed = 0
189
+
190
+ for chunk_idx, slice_data in enumerate(slices):
191
+ obf_data = _xor_transform(slice_data, key=eff_key, salt=salt, chunk_index=chunk_idx)
192
+ chunk_hash = hashlib.sha256(obf_data).hexdigest()
193
+
194
+ chunk_filename = f"{base_name}_{chunk_idx:03d}.pcat"
195
+ chunk_file = out_dir / chunk_filename
196
+ header = MAGIC_CHUNK + struct.pack("<II", chunk_idx, len(obf_data))
197
+ chunk_file.write_bytes(header + obf_data)
198
+
199
+ chunk_paths.append(chunk_file)
200
+ chunk_meta.append(
201
+ {
202
+ "index": chunk_idx,
203
+ "file": chunk_filename,
204
+ "size": len(obf_data),
205
+ "sha256": chunk_hash,
206
+ }
207
+ )
208
+ total_packed += len(header) + len(obf_data)
209
+
210
+ index_payload = {
211
+ "version": 2,
212
+ "project": default_name,
213
+ "executable": bool(executable),
214
+ "entry_point": norm_entry,
215
+ "created_at": int(time.time()),
216
+ "raw_size": total_raw,
217
+ "compressed_size": len(compressed),
218
+ "chunks": chunk_meta,
219
+ "files": manifest_entries,
220
+ }
221
+ raw_manifest = json.dumps(index_payload, ensure_ascii=False).encode("utf-8")
222
+ comp_manifest = zlib.compress(raw_manifest, level=9)
223
+ obf_manifest = _xor_transform(comp_manifest, key=eff_key, salt=salt, chunk_index=0xFFFFFFFF)
224
+
225
+ index_path = out_dir / f"{base_name}.pcat"
226
+ index_header = MAGIC_INDEX + salt + struct.pack("<I", len(obf_manifest))
227
+ index_path.write_bytes(index_header + obf_manifest)
228
+ total_packed += len(index_header) + len(obf_manifest)
229
+
230
+ return PackResult(
231
+ index_path=index_path,
232
+ chunk_paths=chunk_paths,
233
+ file_count=len(manifest_entries),
234
+ raw_bytes=total_raw,
235
+ packed_bytes=total_packed,
236
+ executable=bool(executable),
237
+ entry_point=norm_entry,
238
+ )
239
+
240
+
241
+ def read_manifest(index_file: str | Path, key: str | None = None) -> tuple[Path, bytes, dict]:
242
+ cfg = load_config()
243
+ eff_key = cfg.default_key if key is None else key
244
+
245
+ idx_path = Path(index_file).resolve()
246
+ if not idx_path.is_file():
247
+ raise FileNotFoundError(f"Index .pcat file not found: {idx_path}")
248
+
249
+ blob = idx_path.read_bytes()
250
+ header_len = len(MAGIC_INDEX) + 16 + 4
251
+ if len(blob) < header_len or not blob.startswith(MAGIC_INDEX):
252
+ raise ValueError("Invalid .pcat index file header")
253
+
254
+ salt = blob[len(MAGIC_INDEX) : len(MAGIC_INDEX) + 16]
255
+ (manifest_len,) = struct.unpack("<I", blob[len(MAGIC_INDEX) + 16 : header_len])
256
+ obf_manifest = blob[header_len : header_len + manifest_len]
257
+
258
+ try:
259
+ comp_manifest = _xor_transform(obf_manifest, key=eff_key, salt=salt, chunk_index=0xFFFFFFFF)
260
+ raw_manifest = zlib.decompress(comp_manifest)
261
+ manifest = json.loads(raw_manifest.decode("utf-8"))
262
+ except Exception as exc:
263
+ raise ValueError("Failed to decode manifest (wrong key or corrupted .pcat file)") from exc
264
+
265
+ manifest.setdefault("executable", True)
266
+ manifest.setdefault("entry_point", None)
267
+ return idx_path, salt, manifest
268
+
269
+
270
+ def unpack_project(
271
+ index_file: str | Path,
272
+ target_dir: str | Path | None = None,
273
+ key: str | None = None,
274
+ ) -> tuple[Path, int]:
275
+ cfg = load_config()
276
+ eff_key = cfg.default_key if key is None else key
277
+
278
+ idx_path, salt, manifest = read_manifest(index_file, key=eff_key)
279
+ base_dir = idx_path.parent
280
+
281
+ compressed_buf = bytearray()
282
+ chunk_header_len = len(MAGIC_CHUNK) + 8
283
+
284
+ for c_meta in manifest["chunks"]:
285
+ chunk_file = base_dir / c_meta["file"]
286
+ if not chunk_file.is_file():
287
+ raise FileNotFoundError(f"Missing module chunk: {chunk_file}")
288
+
289
+ c_blob = chunk_file.read_bytes()
290
+ if len(c_blob) < chunk_header_len or not c_blob.startswith(MAGIC_CHUNK):
291
+ raise ValueError(f"Invalid chunk header in {chunk_file.name}")
292
+
293
+ chunk_idx, data_len = struct.unpack("<II", c_blob[len(MAGIC_CHUNK) : chunk_header_len])
294
+ obf_data = c_blob[chunk_header_len : chunk_header_len + data_len]
295
+
296
+ if hashlib.sha256(obf_data).hexdigest() != c_meta["sha256"]:
297
+ raise ValueError(f"Checksum mismatch in module {chunk_file.name}")
298
+
299
+ plain_slice = _xor_transform(obf_data, key=eff_key, salt=salt, chunk_index=chunk_idx)
300
+ compressed_buf.extend(plain_slice)
301
+
302
+ raw_payload = zlib.decompress(bytes(compressed_buf))
303
+
304
+ out_root = (
305
+ Path(target_dir).resolve()
306
+ if target_dir is not None
307
+ else (Path.cwd() / f"{manifest['project']}_unpacked").resolve()
308
+ )
309
+ out_root.mkdir(parents=True, exist_ok=True)
310
+
311
+ for f_meta in manifest["files"]:
312
+ rel_path = f_meta["path"]
313
+ offset = f_meta["offset"]
314
+ size = f_meta["size"]
315
+ file_bytes = raw_payload[offset : offset + size]
316
+
317
+ if hashlib.sha256(file_bytes).hexdigest() != f_meta["sha256"]:
318
+ raise ValueError(f"Integrity check failed for file: {rel_path}")
319
+
320
+ dest_file = (out_root / rel_path).resolve()
321
+ if not str(dest_file).startswith(str(out_root)):
322
+ raise ValueError(f"Unsafe path in archive: {rel_path}")
323
+
324
+ dest_file.parent.mkdir(parents=True, exist_ok=True)
325
+ dest_file.write_bytes(file_bytes)
326
+
327
+ return out_root, len(manifest["files"])
328
+
329
+
330
+ def run_project(
331
+ index_file: str | Path,
332
+ key: str | None = None,
333
+ entry_override: str | None = None,
334
+ extra_args: list[str] | None = None,
335
+ ) -> int:
336
+ cfg = load_config()
337
+ eff_key = cfg.default_key if key is None else key
338
+
339
+ _, _, manifest = read_manifest(index_file, key=eff_key)
340
+ if not manifest.get("executable", True):
341
+ raise PermissionError(
342
+ "This .pcat archive is marked as data-only (not executable). Use 'pcat unpack' instead."
343
+ )
344
+
345
+ target_entry = _normalize_rel_path(entry_override) if entry_override else manifest.get("entry_point")
346
+ if not target_entry:
347
+ raise ValueError("No entry point defined in .pcat archive")
348
+
349
+ with tempfile.TemporaryDirectory(prefix="pcat_run_") as tmp_dir:
350
+ tmp_root = Path(tmp_dir)
351
+ unpack_project(index_file=index_file, target_dir=tmp_root, key=eff_key)
352
+
353
+ script_path = (tmp_root / target_entry).resolve()
354
+ if not str(script_path).startswith(str(tmp_root)) or not script_path.is_file():
355
+ raise FileNotFoundError(f"Entry point file not found in archive: {target_entry}")
356
+
357
+ python_exe = sys.executable or "python"
358
+ env = os.environ.copy()
359
+ env["PYTHONUTF8"] = "1"
360
+ env["PYTHONIOENCODING"] = "utf-8"
361
+
362
+ cmd = [python_exe, str(script_path), *(extra_args or [])]
363
+ proc = subprocess.run(cmd, cwd=str(tmp_root), env=env)
364
+ return proc.returncode
pcat/plugins.py ADDED
@@ -0,0 +1,195 @@
1
+ # pcat/plugins.py
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import importlib.util
6
+ import os
7
+ import sys
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+ from typing import Any, Callable
11
+
12
+ from pcat.config import DEFAULT_CONFIG_PATH, load_config
13
+
14
+ CommandHandler = Callable[[argparse.Namespace], int]
15
+ ParserSetup = Callable[[argparse.ArgumentParser], None]
16
+
17
+ DEFAULT_PLUGINS_DIR = DEFAULT_CONFIG_PATH.parent / "plugins"
18
+
19
+
20
+ @dataclass
21
+ class RegisteredCommand:
22
+ name: str
23
+ handler: CommandHandler
24
+ help: str = ""
25
+ parser_setup: ParserSetup | None = None
26
+ plugin_name: str = ""
27
+
28
+
29
+ @dataclass
30
+ class LoadedPlugin:
31
+ name: str
32
+ file_path: Path
33
+ version: str = "0.1.0"
34
+ description: str = "User-defined ProjectCats plugin."
35
+ enabled: bool = True
36
+ commands: list[str] = field(default_factory=list)
37
+ error: str | None = None
38
+
39
+
40
+ class PluginContext:
41
+ def __init__(self, plugin_name: str, registry: dict[str, RegisteredCommand]) -> None:
42
+ self.plugin_name = plugin_name
43
+ self._registry = registry
44
+
45
+ def register_command(
46
+ self,
47
+ name: str,
48
+ handler: CommandHandler,
49
+ help: str = "",
50
+ parser_setup: ParserSetup | None = None,
51
+ ) -> None:
52
+ cmd_name = name.strip().lower()
53
+ if not cmd_name:
54
+ raise ValueError(f"Plugin '{self.plugin_name}' tried to register an empty command name")
55
+ self._registry[cmd_name] = RegisteredCommand(
56
+ name=cmd_name,
57
+ handler=handler,
58
+ help=help or f"Command '{cmd_name}' from plugin '{self.plugin_name}'.",
59
+ parser_setup=parser_setup,
60
+ plugin_name=self.plugin_name,
61
+ )
62
+
63
+
64
+ class PluginManager:
65
+ def __init__(self, plugins_dirs: list[Path] | None = None) -> None:
66
+ if plugins_dirs is None:
67
+ dirs = [DEFAULT_PLUGINS_DIR]
68
+ local_dir = Path.cwd() / "plugins"
69
+ if local_dir.is_dir() and local_dir.resolve() != DEFAULT_PLUGINS_DIR.resolve():
70
+ dirs.append(local_dir)
71
+ env_dir = os.environ.get("PCAT_PLUGINS_DIR", "").strip()
72
+ if env_dir:
73
+ p_env = Path(env_dir)
74
+ if p_env not in dirs:
75
+ dirs.append(p_env)
76
+ self.plugins_dirs = dirs
77
+ else:
78
+ self.plugins_dirs = [Path(d) for d in plugins_dirs]
79
+
80
+ self.plugins: list[LoadedPlugin] = []
81
+ self.commands: dict[str, RegisteredCommand] = {}
82
+
83
+ def discover_and_load(self) -> None:
84
+ self.plugins.clear()
85
+ self.commands.clear()
86
+ _ = load_config()
87
+
88
+ seen_files: list[Path] = []
89
+ for p_dir in self.plugins_dirs:
90
+ if not p_dir.is_dir():
91
+ continue
92
+ for entry in sorted(p_dir.iterdir()):
93
+ if entry.is_file() and entry.suffix.lower() == ".py" and not entry.name.startswith("_"):
94
+ resolved = entry.resolve()
95
+ if resolved not in seen_files:
96
+ seen_files.append(resolved)
97
+
98
+ for file_path in seen_files:
99
+ plugin_name = file_path.stem
100
+ mod_name = f"pcat_user_plugin_{plugin_name}_{abs(hash(str(file_path)))}"
101
+ loaded = LoadedPlugin(name=plugin_name, file_path=file_path)
102
+
103
+ try:
104
+ spec = importlib.util.spec_from_file_location(mod_name, str(file_path))
105
+ if spec is None or spec.loader is None:
106
+ raise ImportError(f"Cannot create module spec for {file_path}")
107
+ module = importlib.util.module_from_spec(spec)
108
+ sys.modules[mod_name] = module
109
+ spec.loader.exec_module(module)
110
+
111
+ if hasattr(module, "PLUGIN_VERSION") and isinstance(module.PLUGIN_VERSION, str):
112
+ loaded.version = module.PLUGIN_VERSION
113
+ if hasattr(module, "PLUGIN_DESCRIPTION") and isinstance(module.PLUGIN_DESCRIPTION, str):
114
+ loaded.description = module.PLUGIN_DESCRIPTION
115
+ if hasattr(module, "ENABLED") and isinstance(module.ENABLED, bool):
116
+ loaded.enabled = module.ENABLED
117
+
118
+ if not loaded.enabled:
119
+ self.plugins.append(loaded)
120
+ continue
121
+
122
+ before_cmds = set(self.commands.keys())
123
+ ctx = PluginContext(plugin_name=plugin_name, registry=self.commands)
124
+
125
+ if hasattr(module, "register") and callable(module.register):
126
+ module.register(ctx)
127
+ elif hasattr(module, "Plugin") and callable(module.Plugin):
128
+ inst = module.Plugin()
129
+ if hasattr(inst, "register") and callable(inst.register):
130
+ inst.register(ctx)
131
+ else:
132
+ raise AttributeError("Plugin class must implement register(ctx)")
133
+ else:
134
+ raise AttributeError("Plugin module must define register(ctx) or Plugin.register(ctx)")
135
+
136
+ after_cmds = [k for k in self.commands.keys() if k not in before_cmds]
137
+ loaded.commands = after_cmds
138
+ except Exception as exc:
139
+ loaded.error = str(exc)
140
+
141
+ self.plugins.append(loaded)
142
+
143
+
144
+ _MANAGER_CACHE: PluginManager | None = None
145
+
146
+
147
+ def get_plugin_manager(reload: bool = False) -> PluginManager:
148
+ global _MANAGER_CACHE
149
+ if _MANAGER_CACHE is None or reload:
150
+ mgr = PluginManager()
151
+ mgr.discover_and_load()
152
+ _MANAGER_CACHE = mgr
153
+ return _MANAGER_CACHE
154
+
155
+
156
+ def create_plugin_template(name: str, out_dir: Path | None = None) -> Path:
157
+ clean = "".join(ch if (ch.isalnum() or ch == "_") else "_" for ch in name.strip().lower()).strip("_")
158
+ if not clean:
159
+ raise ValueError("Invalid plugin name")
160
+ target_dir = (out_dir or DEFAULT_PLUGINS_DIR).resolve()
161
+ target_dir.mkdir(parents=True, exist_ok=True)
162
+ target_file = target_dir / f"{clean}.py"
163
+ if target_file.exists():
164
+ raise FileExistsError(f"Plugin file already exists: {target_file}")
165
+
166
+ template_code = f'''"""Example ProjectCats plugin: {clean}."""
167
+
168
+ from __future__ import annotations
169
+
170
+ import argparse
171
+
172
+ PLUGIN_VERSION = "0.1.0"
173
+ PLUGIN_DESCRIPTION = "Custom command plugin '{clean}' for ProjectCats."
174
+ ENABLED = True
175
+
176
+
177
+ def _setup_parser(parser: argparse.ArgumentParser) -> None:
178
+ parser.add_argument("--text", default="hello from plugin", help="Message to print")
179
+
180
+
181
+ def _handle_cmd(args: argparse.Namespace) -> int:
182
+ print(f"[{clean}] {{args.text}}")
183
+ return 0
184
+
185
+
186
+ def register(ctx) -> None:
187
+ ctx.register_command(
188
+ name="{clean}",
189
+ handler=_handle_cmd,
190
+ help="Run custom command '{clean}'.",
191
+ parser_setup=_setup_parser,
192
+ )
193
+ '''
194
+ target_file.write_text(template_code, encoding="utf-8")
195
+ return target_file