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 +2 -0
- pcat/box.py +554 -0
- pcat/cli.py +583 -0
- pcat/config.py +118 -0
- pcat/modules.py +440 -0
- pcat/packer.py +364 -0
- pcat/plugins.py +195 -0
- pcat/templates.py +223 -0
- pcat/terminal.py +1321 -0
- projectcats_cli-1.0.2.dist-info/METADATA +11 -0
- projectcats_cli-1.0.2.dist-info/RECORD +15 -0
- projectcats_cli-1.0.2.dist-info/WHEEL +5 -0
- projectcats_cli-1.0.2.dist-info/entry_points.txt +2 -0
- projectcats_cli-1.0.2.dist-info/licenses/LICENSE +21 -0
- projectcats_cli-1.0.2.dist-info/top_level.txt +1 -0
pcat/config.py
ADDED
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
from dataclasses import asdict, dataclass, field
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
DEFAULT_CONFIG_PATH = Path.home() / ".pcat" / "config.json"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@dataclass
|
|
11
|
+
class PcatConfig:
|
|
12
|
+
default_key: str = "projectcats-default"
|
|
13
|
+
chunk_kb: int = 64
|
|
14
|
+
layout_mode: str = "grid" # "grid" or "tabs"
|
|
15
|
+
default_template: str = "py-cli"
|
|
16
|
+
custom_templates: dict[str, str] = field(default_factory=dict)
|
|
17
|
+
|
|
18
|
+
def to_dict(self) -> dict:
|
|
19
|
+
return asdict(self)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def load_config(config_path: Path = DEFAULT_CONFIG_PATH) -> PcatConfig:
|
|
23
|
+
cfg = PcatConfig()
|
|
24
|
+
if not config_path.is_file():
|
|
25
|
+
save_config(cfg, config_path)
|
|
26
|
+
return cfg
|
|
27
|
+
try:
|
|
28
|
+
data = json.loads(config_path.read_text(encoding="utf-8"))
|
|
29
|
+
if isinstance(data, dict):
|
|
30
|
+
if isinstance(data.get("default_key"), str):
|
|
31
|
+
cfg.default_key = data["default_key"]
|
|
32
|
+
if isinstance(data.get("chunk_kb"), int):
|
|
33
|
+
cfg.chunk_kb = data["chunk_kb"]
|
|
34
|
+
if data.get("layout_mode") in ("grid", "tabs"):
|
|
35
|
+
cfg.layout_mode = data["layout_mode"]
|
|
36
|
+
if isinstance(data.get("default_template"), str) and data["default_template"].strip():
|
|
37
|
+
cfg.default_template = data["default_template"].strip()
|
|
38
|
+
if isinstance(data.get("custom_templates"), dict):
|
|
39
|
+
cfg.custom_templates = {
|
|
40
|
+
str(k).strip().lower(): str(v)
|
|
41
|
+
for k, v in data["custom_templates"].items()
|
|
42
|
+
if str(k).strip() and isinstance(v, str)
|
|
43
|
+
}
|
|
44
|
+
except Exception:
|
|
45
|
+
save_config(cfg, config_path)
|
|
46
|
+
return cfg
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def save_config(cfg: PcatConfig, config_path: Path = DEFAULT_CONFIG_PATH) -> Path:
|
|
50
|
+
config_path.parent.mkdir(parents=True, exist_ok=True)
|
|
51
|
+
config_path.write_text(
|
|
52
|
+
json.dumps(cfg.to_dict(), ensure_ascii=False, indent=2) + "\n",
|
|
53
|
+
encoding="utf-8",
|
|
54
|
+
)
|
|
55
|
+
return config_path
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def set_config_value(key: str, raw_value: str, config_path: Path = DEFAULT_CONFIG_PATH) -> PcatConfig:
|
|
59
|
+
cfg = load_config(config_path)
|
|
60
|
+
norm_key = key.strip().lower()
|
|
61
|
+
if norm_key in ("default_key", "key"):
|
|
62
|
+
cfg.default_key = raw_value
|
|
63
|
+
elif norm_key in ("chunk_kb", "chunk"):
|
|
64
|
+
cfg.chunk_kb = int(raw_value)
|
|
65
|
+
elif norm_key in ("layout_mode", "mode", "layout"):
|
|
66
|
+
val = raw_value.strip().lower()
|
|
67
|
+
if val not in ("grid", "tabs"):
|
|
68
|
+
raise ValueError("layout_mode must be 'grid' or 'tabs'")
|
|
69
|
+
cfg.layout_mode = val
|
|
70
|
+
elif norm_key in ("default_template", "template", "tpl"):
|
|
71
|
+
val = raw_value.strip().lower()
|
|
72
|
+
if not val:
|
|
73
|
+
raise ValueError("default_template cannot be empty")
|
|
74
|
+
cfg.default_template = val
|
|
75
|
+
else:
|
|
76
|
+
raise ValueError(
|
|
77
|
+
"Unknown config key "
|
|
78
|
+
f"'{key}'. Allowed: default_key, chunk_kb, layout_mode, default_template"
|
|
79
|
+
)
|
|
80
|
+
save_config(cfg, config_path)
|
|
81
|
+
return cfg
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def add_custom_template(
|
|
85
|
+
name: str,
|
|
86
|
+
template_dir: str | Path,
|
|
87
|
+
config_path: Path = DEFAULT_CONFIG_PATH,
|
|
88
|
+
) -> PcatConfig:
|
|
89
|
+
tpl_name = name.strip().lower()
|
|
90
|
+
if not tpl_name:
|
|
91
|
+
raise ValueError("Template name cannot be empty")
|
|
92
|
+
src_dir = Path(template_dir).resolve()
|
|
93
|
+
if not src_dir.is_dir():
|
|
94
|
+
raise FileNotFoundError(f"Template directory not found: {src_dir}")
|
|
95
|
+
|
|
96
|
+
cfg = load_config(config_path)
|
|
97
|
+
cfg.custom_templates[tpl_name] = str(src_dir)
|
|
98
|
+
save_config(cfg, config_path)
|
|
99
|
+
return cfg
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def remove_custom_template(
|
|
103
|
+
name: str,
|
|
104
|
+
config_path: Path = DEFAULT_CONFIG_PATH,
|
|
105
|
+
) -> PcatConfig:
|
|
106
|
+
tpl_name = name.strip().lower()
|
|
107
|
+
cfg = load_config(config_path)
|
|
108
|
+
if tpl_name not in cfg.custom_templates:
|
|
109
|
+
raise KeyError(f"Custom template '{name}' not found in config")
|
|
110
|
+
del cfg.custom_templates[tpl_name]
|
|
111
|
+
save_config(cfg, config_path)
|
|
112
|
+
return cfg
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def reset_config(config_path: Path = DEFAULT_CONFIG_PATH) -> PcatConfig:
|
|
116
|
+
cfg = PcatConfig()
|
|
117
|
+
save_config(cfg, config_path)
|
|
118
|
+
return cfg
|
pcat/modules.py
ADDED
|
@@ -0,0 +1,440 @@
|
|
|
1
|
+
# pcat/modules.py
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import struct
|
|
8
|
+
import tempfile
|
|
9
|
+
import time
|
|
10
|
+
import zlib
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from pathlib import Path
|
|
13
|
+
from typing import Any
|
|
14
|
+
|
|
15
|
+
from pcat.config import DEFAULT_CONFIG_PATH, load_config
|
|
16
|
+
from pcat.packer import (
|
|
17
|
+
MAGIC_CHUNK,
|
|
18
|
+
MAGIC_INDEX,
|
|
19
|
+
PackResult,
|
|
20
|
+
_xor_transform,
|
|
21
|
+
pack_project,
|
|
22
|
+
read_manifest,
|
|
23
|
+
unpack_project,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
DEFAULT_BUILD_PROFILES: dict[str, dict[str, Any]] = {
|
|
27
|
+
"dev": {
|
|
28
|
+
"description": "Development build profile with smaller chunks and default key for fast iteration.",
|
|
29
|
+
"chunk_kb": 32,
|
|
30
|
+
"executable": True,
|
|
31
|
+
},
|
|
32
|
+
"release": {
|
|
33
|
+
"description": "Release build profile packed into a single module chunk for compact distribution.",
|
|
34
|
+
"chunk_kb": 0,
|
|
35
|
+
"executable": True,
|
|
36
|
+
},
|
|
37
|
+
"data": {
|
|
38
|
+
"description": "Data-only archive profile disabled for direct execution via 'pcat run'.",
|
|
39
|
+
"chunk_kb": 64,
|
|
40
|
+
"executable": False,
|
|
41
|
+
},
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass
|
|
46
|
+
class ModuleInspection:
|
|
47
|
+
index_path: Path
|
|
48
|
+
project: str
|
|
49
|
+
executable: bool
|
|
50
|
+
entry_point: str | None
|
|
51
|
+
profile: str | None
|
|
52
|
+
raw_bytes: int
|
|
53
|
+
compressed_bytes: int
|
|
54
|
+
index_bytes: int
|
|
55
|
+
chunks_total_bytes: int
|
|
56
|
+
chunks: list[dict[str, Any]]
|
|
57
|
+
files: list[dict[str, Any]]
|
|
58
|
+
ok: bool
|
|
59
|
+
issues: list[str]
|
|
60
|
+
|
|
61
|
+
def to_dict(self) -> dict[str, Any]:
|
|
62
|
+
return {
|
|
63
|
+
"index_path": str(self.index_path),
|
|
64
|
+
"project": self.project,
|
|
65
|
+
"executable": self.executable,
|
|
66
|
+
"entry_point": self.entry_point,
|
|
67
|
+
"profile": self.profile,
|
|
68
|
+
"raw_bytes": self.raw_bytes,
|
|
69
|
+
"compressed_bytes": self.compressed_bytes,
|
|
70
|
+
"index_bytes": self.index_bytes,
|
|
71
|
+
"chunks_total_bytes": self.chunks_total_bytes,
|
|
72
|
+
"chunks": self.chunks,
|
|
73
|
+
"files": self.files,
|
|
74
|
+
"ok": self.ok,
|
|
75
|
+
"issues": self.issues,
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def get_build_profiles(config_path: Path = DEFAULT_CONFIG_PATH) -> dict[str, dict[str, Any]]:
|
|
80
|
+
profiles: dict[str, dict[str, Any]] = {
|
|
81
|
+
k: dict(v) for k, v in DEFAULT_BUILD_PROFILES.items()
|
|
82
|
+
}
|
|
83
|
+
if config_path.is_file():
|
|
84
|
+
try:
|
|
85
|
+
raw = json.loads(config_path.read_text(encoding="utf-8"))
|
|
86
|
+
if isinstance(raw, dict) and isinstance(raw.get("build_profiles"), dict):
|
|
87
|
+
for name, spec in raw["build_profiles"].items():
|
|
88
|
+
if isinstance(name, str) and isinstance(spec, dict):
|
|
89
|
+
base = dict(profiles.get(name, {}))
|
|
90
|
+
base.update(spec)
|
|
91
|
+
if "description" not in base:
|
|
92
|
+
base["description"] = f"Custom build profile '{name}'."
|
|
93
|
+
profiles[name] = base
|
|
94
|
+
except Exception:
|
|
95
|
+
pass
|
|
96
|
+
return profiles
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def pack_with_profile(
|
|
100
|
+
source_path: str | Path,
|
|
101
|
+
profile_name: str | None = None,
|
|
102
|
+
output_base: str | Path | None = None,
|
|
103
|
+
key: str | None = None,
|
|
104
|
+
chunk_size_kb: int | None = None,
|
|
105
|
+
entry_point: str | None = None,
|
|
106
|
+
executable: bool | None = None,
|
|
107
|
+
) -> tuple[PackResult, str | None]:
|
|
108
|
+
profiles = get_build_profiles()
|
|
109
|
+
eff_key = key
|
|
110
|
+
eff_chunk = chunk_size_kb
|
|
111
|
+
eff_entry = entry_point
|
|
112
|
+
eff_exec = True if executable is None else executable
|
|
113
|
+
eff_out = output_base
|
|
114
|
+
applied_profile: str | None = None
|
|
115
|
+
|
|
116
|
+
if profile_name is not None:
|
|
117
|
+
p_key = profile_name.strip().lower()
|
|
118
|
+
if p_key not in profiles:
|
|
119
|
+
available = ", ".join(sorted(profiles.keys()))
|
|
120
|
+
raise KeyError(f"Unknown build profile '{profile_name}'. Available: {available}")
|
|
121
|
+
spec = profiles[p_key]
|
|
122
|
+
applied_profile = p_key
|
|
123
|
+
if eff_key is None and isinstance(spec.get("key"), str):
|
|
124
|
+
eff_key = spec["key"]
|
|
125
|
+
if eff_chunk is None and isinstance(spec.get("chunk_kb"), int):
|
|
126
|
+
eff_chunk = spec["chunk_kb"]
|
|
127
|
+
if eff_entry is None and isinstance(spec.get("entry"), str):
|
|
128
|
+
eff_entry = spec["entry"]
|
|
129
|
+
if executable is None and isinstance(spec.get("executable"), bool):
|
|
130
|
+
eff_exec = spec["executable"]
|
|
131
|
+
if eff_out is None and isinstance(spec.get("output"), str):
|
|
132
|
+
eff_out = spec["output"]
|
|
133
|
+
|
|
134
|
+
res = pack_project(
|
|
135
|
+
source_path=source_path,
|
|
136
|
+
output_base=eff_out,
|
|
137
|
+
key=eff_key,
|
|
138
|
+
chunk_size_kb=eff_chunk,
|
|
139
|
+
entry_point=eff_entry,
|
|
140
|
+
executable=eff_exec,
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
# Embed profile metadata into index manifest while preserving chunks
|
|
144
|
+
cfg = load_config()
|
|
145
|
+
actual_key = cfg.default_key if eff_key is None else eff_key
|
|
146
|
+
idx_path, salt, manifest = read_manifest(res.index_path, key=actual_key)
|
|
147
|
+
if applied_profile is not None:
|
|
148
|
+
manifest["profile"] = applied_profile
|
|
149
|
+
manifest["profile_description"] = profiles[applied_profile].get("description", "")
|
|
150
|
+
raw_manifest = json.dumps(manifest, ensure_ascii=False).encode("utf-8")
|
|
151
|
+
comp_manifest = zlib.compress(raw_manifest, level=9)
|
|
152
|
+
obf_manifest = _xor_transform(comp_manifest, key=actual_key, salt=salt, chunk_index=0xFFFFFFFF)
|
|
153
|
+
index_header = MAGIC_INDEX + salt + struct.pack("<I", len(obf_manifest))
|
|
154
|
+
idx_path.write_bytes(index_header + obf_manifest)
|
|
155
|
+
|
|
156
|
+
return res, applied_profile
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def inspect_archive(index_file: str | Path, key: str | None = None) -> ModuleInspection:
|
|
160
|
+
cfg = load_config()
|
|
161
|
+
eff_key = cfg.default_key if key is None else key
|
|
162
|
+
|
|
163
|
+
idx_path, salt, manifest = read_manifest(index_file, key=eff_key)
|
|
164
|
+
base_dir = idx_path.parent
|
|
165
|
+
issues: list[str] = []
|
|
166
|
+
|
|
167
|
+
chunk_header_len = len(MAGIC_CHUNK) + 8
|
|
168
|
+
chunks_info: list[dict[str, Any]] = []
|
|
169
|
+
chunks_total_bytes = 0
|
|
170
|
+
rebuilt_compressed = bytearray()
|
|
171
|
+
|
|
172
|
+
for c_meta in manifest.get("chunks", []):
|
|
173
|
+
c_name = str(c_meta.get("file", ""))
|
|
174
|
+
c_idx = int(c_meta.get("index", 0))
|
|
175
|
+
expected_hash = str(c_meta.get("sha256", ""))
|
|
176
|
+
chunk_file = base_dir / c_name
|
|
177
|
+
status = "OK"
|
|
178
|
+
actual_size = 0
|
|
179
|
+
actual_hash = ""
|
|
180
|
+
|
|
181
|
+
if not chunk_file.is_file():
|
|
182
|
+
status = "MISSING"
|
|
183
|
+
issues.append(f"Missing chunk module: {c_name}")
|
|
184
|
+
else:
|
|
185
|
+
c_blob = chunk_file.read_bytes()
|
|
186
|
+
actual_size = len(c_blob)
|
|
187
|
+
chunks_total_bytes += actual_size
|
|
188
|
+
if len(c_blob) < chunk_header_len or not c_blob.startswith(MAGIC_CHUNK):
|
|
189
|
+
status = "CORRUPT_HEADER"
|
|
190
|
+
issues.append(f"Invalid header in chunk: {c_name}")
|
|
191
|
+
else:
|
|
192
|
+
parsed_idx, data_len = struct.unpack("<II", c_blob[len(MAGIC_CHUNK) : chunk_header_len])
|
|
193
|
+
obf_data = c_blob[chunk_header_len : chunk_header_len + data_len]
|
|
194
|
+
actual_hash = hashlib.sha256(obf_data).hexdigest()
|
|
195
|
+
if parsed_idx != c_idx or len(obf_data) != data_len or actual_hash != expected_hash:
|
|
196
|
+
status = "CORRUPT_HASH"
|
|
197
|
+
issues.append(f"Checksum or index mismatch in chunk: {c_name}")
|
|
198
|
+
else:
|
|
199
|
+
plain_slice = _xor_transform(obf_data, key=eff_key, salt=salt, chunk_index=parsed_idx)
|
|
200
|
+
rebuilt_compressed.extend(plain_slice)
|
|
201
|
+
|
|
202
|
+
chunks_info.append(
|
|
203
|
+
{
|
|
204
|
+
"index": c_idx,
|
|
205
|
+
"file": c_name,
|
|
206
|
+
"manifest_size": int(c_meta.get("size", 0)),
|
|
207
|
+
"disk_size": actual_size,
|
|
208
|
+
"sha256": expected_hash,
|
|
209
|
+
"actual_sha256": actual_hash,
|
|
210
|
+
"status": status,
|
|
211
|
+
}
|
|
212
|
+
)
|
|
213
|
+
|
|
214
|
+
files_info: list[dict[str, Any]] = []
|
|
215
|
+
if not issues:
|
|
216
|
+
try:
|
|
217
|
+
raw_payload = zlib.decompress(bytes(rebuilt_compressed))
|
|
218
|
+
for f_meta in manifest.get("files", []):
|
|
219
|
+
rel = str(f_meta.get("path", ""))
|
|
220
|
+
off = int(f_meta.get("offset", 0))
|
|
221
|
+
sz = int(f_meta.get("size", 0))
|
|
222
|
+
exp_h = str(f_meta.get("sha256", ""))
|
|
223
|
+
f_bytes = raw_payload[off : off + sz]
|
|
224
|
+
f_hash = hashlib.sha256(f_bytes).hexdigest()
|
|
225
|
+
f_ok = len(f_bytes) == sz and f_hash == exp_h
|
|
226
|
+
if not f_ok:
|
|
227
|
+
issues.append(f"Payload checksum mismatch for entry: {rel}")
|
|
228
|
+
files_info.append(
|
|
229
|
+
{
|
|
230
|
+
"path": rel,
|
|
231
|
+
"size": sz,
|
|
232
|
+
"sha256": exp_h,
|
|
233
|
+
"status": "OK" if f_ok else "CORRUPT",
|
|
234
|
+
}
|
|
235
|
+
)
|
|
236
|
+
except Exception as exc:
|
|
237
|
+
issues.append(f"Decompression error: {exc}")
|
|
238
|
+
else:
|
|
239
|
+
for f_meta in manifest.get("files", []):
|
|
240
|
+
files_info.append(
|
|
241
|
+
{
|
|
242
|
+
"path": str(f_meta.get("path", "")),
|
|
243
|
+
"size": int(f_meta.get("size", 0)),
|
|
244
|
+
"sha256": str(f_meta.get("sha256", "")),
|
|
245
|
+
"status": "UNVERIFIED",
|
|
246
|
+
}
|
|
247
|
+
)
|
|
248
|
+
|
|
249
|
+
return ModuleInspection(
|
|
250
|
+
index_path=idx_path,
|
|
251
|
+
project=str(manifest.get("project", idx_path.stem)),
|
|
252
|
+
executable=bool(manifest.get("executable", True)),
|
|
253
|
+
entry_point=manifest.get("entry_point"),
|
|
254
|
+
profile=manifest.get("profile"),
|
|
255
|
+
raw_bytes=int(manifest.get("raw_size", 0)),
|
|
256
|
+
compressed_bytes=int(manifest.get("compressed_size", 0)),
|
|
257
|
+
index_bytes=idx_path.stat().st_size,
|
|
258
|
+
chunks_total_bytes=chunks_total_bytes,
|
|
259
|
+
chunks=chunks_info,
|
|
260
|
+
files=files_info,
|
|
261
|
+
ok=len(issues) == 0,
|
|
262
|
+
issues=issues,
|
|
263
|
+
)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def merge_archives(
|
|
267
|
+
archive_paths: list[str | Path],
|
|
268
|
+
output_base: str | Path,
|
|
269
|
+
key: str | None = None,
|
|
270
|
+
chunk_size_kb: int | None = None,
|
|
271
|
+
on_conflict: str = "error",
|
|
272
|
+
) -> PackResult:
|
|
273
|
+
if len(archive_paths) < 2:
|
|
274
|
+
raise ValueError("Provide at least two .pcat archives to merge")
|
|
275
|
+
conflict_mode = on_conflict.strip().lower()
|
|
276
|
+
if conflict_mode not in ("error", "overwrite", "prefix"):
|
|
277
|
+
raise ValueError("on_conflict must be one of: error, overwrite, prefix")
|
|
278
|
+
|
|
279
|
+
cfg = load_config()
|
|
280
|
+
eff_key = cfg.default_key if key is None else key
|
|
281
|
+
|
|
282
|
+
merged_files: dict[str, bytes] = {}
|
|
283
|
+
first_entry: str | None = None
|
|
284
|
+
any_executable = False
|
|
285
|
+
merged_names: list[str] = []
|
|
286
|
+
|
|
287
|
+
with tempfile.TemporaryDirectory(prefix="pcat_merge_") as tmp_root_str:
|
|
288
|
+
tmp_root = Path(tmp_root_str)
|
|
289
|
+
for idx, arch in enumerate(archive_paths):
|
|
290
|
+
idx_path, _, manifest = read_manifest(arch, key=eff_key)
|
|
291
|
+
stage_dir = tmp_root / f"part_{idx}_{idx_path.stem}"
|
|
292
|
+
unpack_project(index_file=idx_path, target_dir=stage_dir, key=eff_key)
|
|
293
|
+
part_label = str(manifest.get("project") or idx_path.stem)
|
|
294
|
+
merged_names.append(part_label)
|
|
295
|
+
|
|
296
|
+
if manifest.get("executable", True):
|
|
297
|
+
any_executable = True
|
|
298
|
+
if first_entry is None and manifest.get("entry_point"):
|
|
299
|
+
first_entry = str(manifest["entry_point"])
|
|
300
|
+
|
|
301
|
+
for f_meta in manifest.get("files", []):
|
|
302
|
+
rel = str(f_meta["path"])
|
|
303
|
+
src_file = stage_dir / rel
|
|
304
|
+
data = src_file.read_bytes()
|
|
305
|
+
|
|
306
|
+
target_rel = rel
|
|
307
|
+
if target_rel in merged_files:
|
|
308
|
+
if conflict_mode == "error":
|
|
309
|
+
raise ValueError(f"Conflicting file '{target_rel}' while merging '{idx_path.name}'")
|
|
310
|
+
if conflict_mode == "prefix":
|
|
311
|
+
target_rel = f"{part_label}/{rel}"
|
|
312
|
+
# overwrite keeps latest bytes under target_rel
|
|
313
|
+
|
|
314
|
+
merged_files[target_rel] = data
|
|
315
|
+
|
|
316
|
+
bundle_dir = tmp_root / "merged_bundle"
|
|
317
|
+
bundle_dir.mkdir(parents=True, exist_ok=True)
|
|
318
|
+
for rel, data in merged_files.items():
|
|
319
|
+
out_f = bundle_dir / rel
|
|
320
|
+
out_f.parent.mkdir(parents=True, exist_ok=True)
|
|
321
|
+
out_f.write_bytes(data)
|
|
322
|
+
|
|
323
|
+
entry_to_use = first_entry if (first_entry and first_entry in merged_files) else None
|
|
324
|
+
if any_executable and entry_to_use is None:
|
|
325
|
+
for py_candidate in sorted(merged_files.keys()):
|
|
326
|
+
if py_candidate.endswith(".py"):
|
|
327
|
+
entry_to_use = py_candidate
|
|
328
|
+
break
|
|
329
|
+
|
|
330
|
+
out_p = Path(output_base).resolve()
|
|
331
|
+
out_dir = out_p.parent if out_p.suffix.lower() == ".pcat" else out_p
|
|
332
|
+
bundle_name = out_p.stem if out_p.suffix.lower() == ".pcat" else ("_".join(merged_names) or "merged")
|
|
333
|
+
out_dir.mkdir(parents=True, exist_ok=True)
|
|
334
|
+
|
|
335
|
+
# Pack into temporary folder then move with bundle_name
|
|
336
|
+
pack_tmp = tmp_root / "pack_out"
|
|
337
|
+
res = pack_project(
|
|
338
|
+
source_path=bundle_dir,
|
|
339
|
+
output_base=pack_tmp,
|
|
340
|
+
key=eff_key,
|
|
341
|
+
chunk_size_kb=chunk_size_kb,
|
|
342
|
+
entry_point=entry_to_use,
|
|
343
|
+
executable=any_executable,
|
|
344
|
+
)
|
|
345
|
+
|
|
346
|
+
final_index = out_dir / f"{bundle_name}.pcat"
|
|
347
|
+
final_chunks: list[Path] = []
|
|
348
|
+
_, salt, man = read_manifest(res.index_path, key=eff_key)
|
|
349
|
+
man["project"] = bundle_name
|
|
350
|
+
man["merged_from"] = merged_names
|
|
351
|
+
man["created_at"] = int(time.time())
|
|
352
|
+
|
|
353
|
+
for c_meta in man["chunks"]:
|
|
354
|
+
old_chunk = res.index_path.parent / c_meta["file"]
|
|
355
|
+
new_c_name = f"{bundle_name}_{int(c_meta['index']):03d}.pcat"
|
|
356
|
+
new_chunk = out_dir / new_c_name
|
|
357
|
+
new_chunk.write_bytes(old_chunk.read_bytes())
|
|
358
|
+
c_meta["file"] = new_c_name
|
|
359
|
+
final_chunks.append(new_chunk)
|
|
360
|
+
|
|
361
|
+
raw_man = json.dumps(man, ensure_ascii=False).encode("utf-8")
|
|
362
|
+
comp_man = zlib.compress(raw_man, level=9)
|
|
363
|
+
obf_man = _xor_transform(comp_man, key=eff_key, salt=salt, chunk_index=0xFFFFFFFF)
|
|
364
|
+
final_index.write_bytes(MAGIC_INDEX + salt + struct.pack("<I", len(obf_man)) + obf_man)
|
|
365
|
+
|
|
366
|
+
return PackResult(
|
|
367
|
+
index_path=final_index,
|
|
368
|
+
chunk_paths=final_chunks,
|
|
369
|
+
file_count=res.file_count,
|
|
370
|
+
raw_bytes=res.raw_bytes,
|
|
371
|
+
packed_bytes=final_index.stat().st_size + sum(p.stat().st_size for p in final_chunks),
|
|
372
|
+
executable=res.executable,
|
|
373
|
+
entry_point=res.entry_point,
|
|
374
|
+
)
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def split_archive(
|
|
378
|
+
index_file: str | Path,
|
|
379
|
+
output_dir: str | Path | None = None,
|
|
380
|
+
key: str | None = None,
|
|
381
|
+
per_file: bool = False,
|
|
382
|
+
num_parts: int | None = None,
|
|
383
|
+
) -> list[PackResult]:
|
|
384
|
+
cfg = load_config()
|
|
385
|
+
eff_key = cfg.default_key if key is None else key
|
|
386
|
+
|
|
387
|
+
idx_path, _, manifest = read_manifest(index_file, key=eff_key)
|
|
388
|
+
out_root = (
|
|
389
|
+
Path(output_dir).resolve()
|
|
390
|
+
if output_dir is not None
|
|
391
|
+
else (Path.cwd() / f"{manifest['project']}_split").resolve()
|
|
392
|
+
)
|
|
393
|
+
out_root.mkdir(parents=True, exist_ok=True)
|
|
394
|
+
|
|
395
|
+
results: list[PackResult] = []
|
|
396
|
+
with tempfile.TemporaryDirectory(prefix="pcat_split_") as tmp_str:
|
|
397
|
+
tmp_root = Path(tmp_str)
|
|
398
|
+
unpacked_dir = tmp_root / "unpacked"
|
|
399
|
+
unpack_project(index_file=idx_path, target_dir=unpacked_dir, key=eff_key)
|
|
400
|
+
|
|
401
|
+
file_items = list(manifest.get("files", []))
|
|
402
|
+
if not file_items:
|
|
403
|
+
raise ValueError("Archive contains no files to split")
|
|
404
|
+
|
|
405
|
+
if per_file:
|
|
406
|
+
groups = [[f] for f in file_items]
|
|
407
|
+
else:
|
|
408
|
+
parts = max(2, num_parts or len(manifest.get("chunks", [])) or 2)
|
|
409
|
+
parts = min(parts, len(file_items))
|
|
410
|
+
groups = [[] for _ in range(parts)]
|
|
411
|
+
for idx_f, f_meta in enumerate(file_items):
|
|
412
|
+
groups[idx_f % parts].append(f_meta)
|
|
413
|
+
|
|
414
|
+
for g_idx, group in enumerate(groups):
|
|
415
|
+
sub_dir = tmp_root / f"group_{g_idx:03d}"
|
|
416
|
+
sub_dir.mkdir(parents=True, exist_ok=True)
|
|
417
|
+
group_py_entry: str | None = None
|
|
418
|
+
|
|
419
|
+
for f_meta in group:
|
|
420
|
+
rel = str(f_meta["path"])
|
|
421
|
+
src_f = unpacked_dir / rel
|
|
422
|
+
dst_f = sub_dir / rel
|
|
423
|
+
dst_f.parent.mkdir(parents=True, exist_ok=True)
|
|
424
|
+
dst_f.write_bytes(src_f.read_bytes())
|
|
425
|
+
if group_py_entry is None and rel.endswith(".py"):
|
|
426
|
+
group_py_entry = rel
|
|
427
|
+
|
|
428
|
+
part_base = out_root / f"{manifest['project']}_part{g_idx:03d}"
|
|
429
|
+
is_exec = bool(manifest.get("executable", True)) and group_py_entry is not None
|
|
430
|
+
pack_res = pack_project(
|
|
431
|
+
source_path=sub_dir,
|
|
432
|
+
output_base=part_base,
|
|
433
|
+
key=eff_key,
|
|
434
|
+
chunk_size_kb=0,
|
|
435
|
+
entry_point=group_py_entry if is_exec else None,
|
|
436
|
+
executable=is_exec,
|
|
437
|
+
)
|
|
438
|
+
results.append(pack_res)
|
|
439
|
+
|
|
440
|
+
return results
|