forked from thebaselab/codeapp
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcreate_visx.py
More file actions
312 lines (255 loc) · 9.85 KB
/
create_visx.py
File metadata and controls
312 lines (255 loc) · 9.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#!/usr/bin/env python3
"""
VISX Creator - Compress WASM and Node.js packages
Creates .visx (Virtual iOS Extension Package) files that bundle WASM modules,
Node.js packages, and their dependencies for remote distribution.
Format:
- .visx is a gzipped tar archive
- Contains a manifest.json with metadata
- Includes all necessary files and dependencies
- Optimized for mobile distribution (compressed)
Usage:
python create_visx.py [OPTIONS] SOURCE_DIR OUTPUT_FILE
Examples:
# Create VISX from WASM module
python create_visx.py ./my-wasm-module ./output/module.visx --type wasm
# Create VISX from Node.js package
python create_visx.py ./my-node-package ./output/package.visx --type node
# Create with custom metadata
python create_visx.py ./src ./out.visx --name "MyPackage" --version "1.0.0"
"""
import argparse
import json
import os
import sys
import tarfile
import hashlib
import gzip
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Optional
class VISXCreator:
"""Creates .visx packages from source directories."""
VISX_VERSION = "1.0"
def __init__(self, source_dir: str, output_file: str, package_type: str = "auto"):
self.source_dir = Path(source_dir).resolve()
self.output_file = Path(output_file).resolve()
self.package_type = package_type
if not self.source_dir.exists():
raise FileNotFoundError(f"Source directory not found: {source_dir}")
# Ensure output directory exists
self.output_file.parent.mkdir(parents=True, exist_ok=True)
def detect_package_type(self) -> str:
"""Auto-detect package type from source directory."""
if (self.source_dir / "package.json").exists():
return "node"
elif any(self.source_dir.glob("*.wasm")):
return "wasm"
elif any(self.source_dir.glob("*.js")):
return "javascript"
else:
return "generic"
def get_package_info(self) -> Dict:
"""Extract package information from source."""
info = {
"name": self.source_dir.name,
"version": "1.0.0",
"description": "",
"dependencies": {}
}
# Try to read package.json for Node.js packages
package_json = self.source_dir / "package.json"
if package_json.exists():
try:
with open(package_json, 'r') as f:
pkg_data = json.load(f)
info["name"] = pkg_data.get("name", info["name"])
info["version"] = pkg_data.get("version", info["version"])
info["description"] = pkg_data.get("description", "")
info["dependencies"] = pkg_data.get("dependencies", {})
except Exception as e:
print(f"Warning: Could not read package.json: {e}")
return info
def calculate_checksum(self, file_path: Path) -> str:
"""Calculate SHA256 checksum of a file."""
sha256 = hashlib.sha256()
with open(file_path, 'rb') as f:
for chunk in iter(lambda: f.read(4096), b""):
sha256.update(chunk)
return sha256.hexdigest()
def get_file_list(self, exclude_patterns: Optional[List[str]] = None) -> List[Path]:
"""Get list of files to include in the archive."""
if exclude_patterns is None:
exclude_patterns = [
".git",
".gitignore",
"node_modules/.cache",
"__pycache__",
"*.pyc",
".DS_Store",
"*.visx"
]
files = []
for file_path in self.source_dir.rglob('*'):
if file_path.is_file():
# Check exclusions
rel_path = file_path.relative_to(self.source_dir)
should_exclude = any(
part.startswith('.') or
any(pat in str(rel_path) for pat in exclude_patterns)
for part in rel_path.parts
)
if not should_exclude:
files.append(file_path)
return files
def create_manifest(self, pkg_info: Dict, files: List[Path]) -> Dict:
"""Create manifest.json for the package."""
# Calculate total size and file checksums
total_size = 0
file_manifest = []
for file_path in files:
rel_path = file_path.relative_to(self.source_dir)
file_size = file_path.stat().st_size
total_size += file_size
file_manifest.append({
"path": str(rel_path),
"size": file_size,
"checksum": self.calculate_checksum(file_path)
})
manifest = {
"visx_version": self.VISX_VERSION,
"package": {
"name": pkg_info["name"],
"version": pkg_info["version"],
"description": pkg_info["description"],
"type": self.package_type,
},
"created_at": datetime.utcnow().isoformat() + "Z",
"stats": {
"total_files": len(files),
"total_size": total_size,
"compressed_size": 0 # Will be updated after compression
},
"files": file_manifest,
"dependencies": pkg_info.get("dependencies", {}),
"metadata": {
"platform": "ios",
"minimum_version": "17.0",
"requires": []
}
}
return manifest
def create_archive(self, files: List[Path], manifest: Dict) -> None:
"""Create the .visx archive."""
print(f"📦 Creating VISX package...")
print(f" Source: {self.source_dir}")
print(f" Output: {self.output_file}")
print(f" Type: {self.package_type}")
print(f" Files: {len(files)}")
# Create tar.gz archive
with tarfile.open(self.output_file, 'w:gz') as tar:
# Add manifest first
manifest_json = json.dumps(manifest, indent=2).encode('utf-8')
import io
manifest_tarinfo = tarfile.TarInfo(name='manifest.json')
manifest_tarinfo.size = len(manifest_json)
tar.addfile(manifest_tarinfo, io.BytesIO(manifest_json))
# Add all files
for i, file_path in enumerate(files, 1):
rel_path = file_path.relative_to(self.source_dir)
arcname = str(rel_path)
if i % 100 == 0:
print(f" Adding files... {i}/{len(files)}")
tar.add(file_path, arcname=arcname)
# Update compressed size in manifest
compressed_size = self.output_file.stat().st_size
original_size = manifest["stats"]["total_size"]
compression_ratio = (1 - compressed_size / original_size) * 100 if original_size > 0 else 0
print(f"\n✅ Package created successfully!")
print(f" Original size: {self._format_size(original_size)}")
print(f" Compressed size: {self._format_size(compressed_size)}")
print(f" Compression: {compression_ratio:.1f}%")
print(f" Output: {self.output_file}")
def _format_size(self, size: int) -> str:
"""Format byte size in human-readable format."""
for unit in ['B', 'KB', 'MB', 'GB']:
if size < 1024.0:
return f"{size:.2f} {unit}"
size /= 1024.0
return f"{size:.2f} TB"
def create(self) -> None:
"""Main creation workflow."""
try:
# Detect or validate package type
if self.package_type == "auto":
self.package_type = self.detect_package_type()
print(f"🔍 Auto-detected package type: {self.package_type}")
# Get package information
pkg_info = self.get_package_info()
# Get file list
files = self.get_file_list()
if not files:
raise ValueError("No files found in source directory")
# Create manifest
manifest = self.create_manifest(pkg_info, files)
# Create archive
self.create_archive(files, manifest)
except Exception as e:
print(f"\n❌ Error creating VISX package: {e}")
if self.output_file.exists():
self.output_file.unlink()
raise
def main():
parser = argparse.ArgumentParser(
description="Create .visx packages for CodeApp",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
# WASM module
python create_visx.py ./wasm-module ./output/module.visx --type wasm
# Node.js package
python create_visx.py ./node-package ./output/pkg.visx --type node
# Auto-detect
python create_visx.py ./my-package ./output.visx
"""
)
parser.add_argument(
"source",
help="Source directory containing the package"
)
parser.add_argument(
"output",
help="Output .visx file path"
)
parser.add_argument(
"--type",
choices=["auto", "wasm", "node", "javascript", "generic"],
default="auto",
help="Package type (auto-detect if not specified)"
)
parser.add_argument(
"--name",
help="Override package name"
)
parser.add_argument(
"--version",
help="Override package version"
)
parser.add_argument(
"--description",
help="Package description"
)
args = parser.parse_args()
# Ensure output has .visx extension
output_path = Path(args.output)
if output_path.suffix != '.visx':
output_path = output_path.with_suffix('.visx')
# Create VISX package
creator = VISXCreator(
source_dir=args.source,
output_file=str(output_path),
package_type=args.type
)
creator.create()
if __name__ == "__main__":
main()