Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : ORIX Cosmos10# File : DataPipeline/packs/packtool.py11# Description : Pack tooling (standard library only): validate a pack12# directory against manifest schema v1, compute file hashes,13# announce a signature, build a deterministic .orixpack14# archive (ustar, optional gzip), and generate the pack15# index.16# Module : DataPipeline17# Repository : https://git.spboucher.ai/orix-cosmos18# Project Website : https://www.orixlab.dev19# Created : 2026-11-2420# Last Modified : 2026-11-2421#22# =============================================================================23# AUTHOR & PROFESSIONAL AFFILIATION24# =============================================================================25#26# Author : Simon-Pierre Boucher27# Position : Professor of Finance28# Institution : Université du Québec en Outaouais (UQO)29# Department : Département des sciences administratives30# Organization : SP Boucher31#32# Website : https://spboucher.ai33# Git : https://git.spboucher.ai34#35# =============================================================================36# OFFICIAL CONTACT DIRECTORY37# =============================================================================38#39# General : info@spboucher.ai40# Professional : contact@spboucher.ai41# Direct : simon@spboucher.ai42# Research : research@spboucher.ai43# Development : dev@spboucher.ai44# Support : support@spboucher.ai45# Security/Admin : admin@spboucher.ai46# Notifications : notifications@spboucher.ai47#48# Preferred Contact: support@spboucher.ai49#50# =============================================================================51# COPYRIGHT & INTELLECTUAL PROPERTY52# =============================================================================53#54# Copyright (c) 202655# Simon-Pierre Boucher56#57# All rights reserved where applicable.58#59# This file is governed by the applicable project license,60# copyright notices, institutional agreements and relevant law.61#62# Unless expressly authorized by the applicable license or63# rights holder, copying, redistribution, sublicensing,64# publication and commercial exploitation are not permitted.65#66# Existing third-party rights and notices remain unaffected.67#68# =============================================================================69# CONFIDENTIALITY & SECURITY70# =============================================================================71#72# Classification : Public73# Distribution : Public repository; use is governed by the project license74# Security Contact : admin@spboucher.ai75#76# Access to this source does not independently grant permission77# to redistribute or disclose confidential materials.78#79# Do not embed credentials, private keys, access tokens,80# certificates or confidential personal information.81#82# =============================================================================83# LICENSE & MAINTENANCE84# =============================================================================85#86# License : None specified (no license file in this repository)87# Maintainer : Simon-Pierre Boucher88# Technical Contact: dev@spboucher.ai89#90# =============================================================================91# END OF SP BOUCHER SOURCE HEADER92# =============================================================================9394"""Usage:95 packtool.py validate <pack dir>... [--no-hash] check manifest.json and the files on disk96 packtool.py hash <pack dir> [--all] [--write] recompute files[].size/sha256 and installedSize97 packtool.py announce-signature <pack dir> <key id> add the signature block to manifest.json (before signing)98 packtool.py build <pack dir> -o <archive> [--gzip] write the archive (manifest.json first, manifest.sig if present)99 packtool.py index <archive>... -o <index.json> [--base-url URL] [--generated ISO8601]100101The rules implemented here mirror Packages/CosmosDataPacks (PackManifest.validate, PackPath); the Swift reader is the102authority. Signing itself needs Ed25519, which the Python standard library lacks: see packsign.swift.103No network access. Exit status 0 = success, 1 = validation errors, 2 = usage or I/O error.104"""105import argparse106import gzip107import hashlib108import io109import json110import os111import re112import stat113import sys114import unicodedata115116SCHEMA_VERSION = 1117MANIFEST = "manifest.json"118SIGNATURE = "manifest.sig"119KINDS = ["ephemeris", "catalogue", "textures", "sky-imagery", "missions", "satellites", "time", "other"]120ID_RE = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$")121SEMVER_RE = re.compile(r"^(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})\.(0|[1-9][0-9]{0,8})(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?(\+[0-9A-Za-z.-]+)?$")122SHA_RE = re.compile(r"^[0-9a-f]{64}$")123# canonical key -> legacy alias accepted by the reader124TOP_ALIASES = {"schemaVersion": "format", "license": "licence", "installedSize": "total_bytes"}125FILE_ALIASES = {"path": "name", "size": "bytes", "source": "provenance_id"}126SOURCE_ALIASES = {"license": "licence"}127KNOWN_TOP = {"schemaVersion", "id", "version", "kind", "title", "description", "installedSize", "downloadSize", "files",128 "sources", "license", "coverage", "redistribution", "dependencies", "minimumAppVersion", "signature"}129CHUNK = 1 << 20130USTAR_MAX = 0o77777777777131132133def collision_key(path):134 return unicodedata.normalize("NFD", unicodedata.normalize("NFD", path).lower())135136137def path_problem(path):138 """Returns None when the relative path is acceptable, else the reason (same rules as PackPath.validate)."""139 if not isinstance(path, str) or path == "":140 return "empty path"141 if len(path.encode("utf-8")) > 1024:142 return "longer than 1024 bytes"143 for ch in path:144 c = ord(ch)145 if c == 0:146 return "contains a NUL character"147 if c < 0x20 or c == 0x7F or 0x80 <= c <= 0x9F:148 return "contains a control character"149 if ch == "\\":150 return "contains a backslash"151 if c in (0x2028, 0x2029, 0xFFFD) or 0x202A <= c <= 0x202E or 0x2066 <= c <= 0x2069:152 return "contains a line separator, bidirectional control or replacement character"153 if path.startswith("/"):154 return "absolute path"155 if path.startswith("~"):156 return "starts with a tilde"157 comps = path.split("/")158 for comp in comps:159 if comp == "":160 return "empty path component"161 if comp in (".", ".."):162 return "contains a %r component" % comp163 if len(comp.encode("utf-8")) > 255:164 return "component longer than 255 bytes"165 if comp.endswith(" ") or comp.endswith("."):166 return "component ends with a space or a dot"167 if len(comps) == 1 and collision_key(comps[0]) in (MANIFEST, SIGNATURE):168 return "reserved name"169 if comps[0].startswith("."):170 return "top-level names starting with a dot are reserved for the store"171 return None172173174def normalise(obj, aliases, notes, where):175 """Renames legacy aliases to canonical keys (canonical wins when both are present) and records each use."""176 out = dict(obj)177 for canonical, alias in aliases.items():178 if alias in out:179 value = out.pop(alias)180 notes.add("%s: legacy key %r should be renamed %r" % (where, alias, canonical))181 out.setdefault(canonical, value)182 return out183184185def is_int(v):186 return isinstance(v, int) and not isinstance(v, bool)187188189def check_localized(value, key, errors, notes):190 if isinstance(value, str):191 notes.add("%s is a plain string; schema v1 wants {\"en\": ..., \"fr\": ...}" % key)192 return193 if not isinstance(value, dict) or not all(isinstance(k, str) and isinstance(v, str) for k, v in value.items()):194 errors.append("%s must be a {language: text} object" % key)195 elif not value.get("en"):196 errors.append("%s.en is required" % key)197 elif "fr" not in value:198 notes.add("%s has no French text (fr)" % key)199200201def validate_manifest(raw):202 """Returns (canonical manifest or None, errors, notes). Errors make the Swift reader refuse the pack."""203 errors, notes = [], set()204 if not isinstance(raw, dict):205 return None, ["the manifest must be a JSON object"], notes206 m = normalise(raw, TOP_ALIASES, notes, "manifest")207 sv = m.get("schemaVersion")208 if not is_int(sv):209 errors.append("schemaVersion is required (integer)")210 elif sv != SCHEMA_VERSION:211 errors.append("unsupported schemaVersion %d (this tool handles %d)" % (sv, SCHEMA_VERSION))212 if not isinstance(m.get("id"), str) or not ID_RE.match(m["id"]):213 errors.append("id is required and must match [a-z0-9][a-z0-9._-]{0,63}")214 if not isinstance(m.get("version"), str) or not SEMVER_RE.match(m["version"]):215 errors.append("version is required (semantic version major.minor.patch)")216 if "kind" not in m:217 errors.append("kind is required (one of %s)" % ", ".join(KINDS))218 elif m["kind"] not in KINDS:219 errors.append("kind %r is not one of %s" % (m["kind"], ", ".join(KINDS)))220 if "title" not in m:221 errors.append("title is required")222 else:223 check_localized(m["title"], "title", errors, notes)224 if m.get("description") is not None:225 check_localized(m["description"], "description", errors, notes)226 else:227 notes.add("description (en/fr) is absent")228 if "redistribution" not in m:229 errors.append("redistribution is required (\"redistributable\" or \"localBuildOnly\")")230 elif m["redistribution"] not in ("redistributable", "localBuildOnly"):231 errors.append("redistribution must be \"redistributable\" or \"localBuildOnly\"")232233 source_ids = set()234 sources = m.get("sources")235 if sources is None:236 notes.add("sources[] is absent: provenance (name, url, version, retrieved, license, citation) is not machine-readable")237 sources = []238 if not isinstance(sources, list):239 errors.append("sources must be an array")240 sources = []241 canonical_sources = []242 for i, s in enumerate(sources):243 if not isinstance(s, dict):244 errors.append("sources[%d] must be an object" % i)245 continue246 s = normalise(s, SOURCE_ALIASES, notes, "sources[]")247 for key in ("id", "name", "version", "license"):248 if not isinstance(s.get(key), str) or (key in ("id", "name") and not s[key]):249 errors.append("sources[%d].%s is required (string)" % (i, key))250 extra = set(s) - {"id", "name", "url", "version", "retrieved", "license", "citation", "method"}251 if extra:252 errors.append("sources[%d]: unknown key(s) %s" % (i, ", ".join(sorted(extra))))253 if isinstance(s.get("id"), str):254 if s["id"] in source_ids:255 errors.append("duplicate source id %r" % s["id"])256 source_ids.add(s["id"])257 canonical_sources.append(s)258 m["sources"] = canonical_sources259260 files = m.get("files")261 canonical_files, total = [], 0262 if not isinstance(files, list):263 errors.append("files is required (array of {path, size, sha256})")264 files = []265 seen, dirs, undeclared = {}, {}, {}266 for i, f in enumerate(files):267 if not isinstance(f, dict):268 errors.append("files[%d] must be an object" % i)269 continue270 f = normalise(f, FILE_ALIASES, notes, "files[]")271 path = f.get("path")272 label = path if isinstance(path, str) else "files[%d]" % i273 problem = path_problem(path)274 if problem:275 errors.append("%s: unsafe path (%s)" % (label, problem))276 else:277 key = collision_key(path)278 if key in seen:279 errors.append("%s: %s" % (label, "duplicate path" if seen[key] == path else "collides with %r on a case-insensitive volume" % seen[key]))280 seen[key] = path281 prefix = ""282 for comp in path.split("/")[:-1]:283 prefix = comp if not prefix else prefix + "/" + comp284 dk = collision_key(prefix)285 if dirs.get(dk, prefix) != prefix:286 errors.append("%s: directory %r collides with %r on a case-insensitive volume" % (label, prefix, dirs[dk]))287 dirs[dk] = prefix288 if not is_int(f.get("size")) or f["size"] < 0:289 errors.append("%s: size is required (non-negative integer, bytes)" % label)290 else:291 total += f["size"]292 if not isinstance(f.get("sha256"), str) or not SHA_RE.match(f["sha256"]):293 errors.append("%s: sha256 must be 64 lower-case hexadecimal digits" % label)294 for key in ("role", "description", "source", "url"):295 if key in f and f[key] is not None and not isinstance(f[key], str):296 errors.append("%s: %s must be a string" % (label, key))297 if isinstance(f.get("source"), str) and f["source"] not in source_ids:298 undeclared.setdefault(f["source"], 0)299 undeclared[f["source"]] += 1300 canonical_files.append(f)301 for dk, d in dirs.items():302 if dk in seen:303 errors.append("%r is used both as a file and as a directory" % d)304 if undeclared:305 errors.append("%d file(s) reference %d source id(s) not declared in sources[]: %s" % (sum(undeclared.values()), len(undeclared), ", ".join(sorted(undeclared))))306 m["files"] = canonical_files307 if "installedSize" not in m:308 errors.append("installedSize is required (sum of files[].size = %d)" % total)309 elif not is_int(m["installedSize"]) or m["installedSize"] != total:310 errors.append("installedSize %r differs from the sum of files[].size (%d)" % (m["installedSize"], total))311 if m.get("downloadSize") is not None and (not is_int(m["downloadSize"]) or m["downloadSize"] < 0):312 errors.append("downloadSize must be a non-negative integer")313 if m.get("license") is not None and not isinstance(m["license"], str):314 errors.append("license must be a string")315316 dep_ids = set()317 deps = m.get("dependencies", [])318 if not isinstance(deps, list):319 errors.append("dependencies must be an array")320 deps = []321 for d in deps:322 if not isinstance(d, dict) or not isinstance(d.get("id"), str) or not ID_RE.match(d["id"]) or d["id"] == m.get("id") or d["id"] in dep_ids:323 errors.append("bad dependency %r" % (d,))324 continue325 dep_ids.add(d["id"])326 if set(d) - {"id", "minimumVersion"}:327 errors.append("dependency %s: unknown key" % d["id"])328 if d.get("minimumVersion") is not None and (not isinstance(d["minimumVersion"], str) or not SEMVER_RE.match(d["minimumVersion"])):329 errors.append("dependency %s: minimumVersion is not a semantic version" % d["id"])330 mav = m.get("minimumAppVersion")331 if mav is not None and (not isinstance(mav, str) or not SEMVER_RE.match(mav)):332 errors.append("minimumAppVersion is not a semantic version")333 elif mav is None:334 notes.add("minimumAppVersion is absent")335 sig = m.get("signature")336 if sig is not None:337 if not isinstance(sig, dict) or sig.get("algorithm") != "ed25519" or sig.get("file") != SIGNATURE or not sig.get("keyID") or set(sig) != {"algorithm", "keyID", "file"}:338 errors.append("signature must be {\"algorithm\": \"ed25519\", \"keyID\": ..., \"file\": \"manifest.sig\"}")339 if "coverage" not in m:340 notes.add("coverage is absent")341 extensions = sorted(set(m) - KNOWN_TOP)342 if extensions:343 notes.add("extension keys kept as-is (allowed): " + ", ".join(extensions))344 return (m if not errors else None), errors, notes345346347def sha256_file(path):348 h = hashlib.sha256()349 size = 0350 with open(path, "rb") as fh:351 while True:352 chunk = fh.read(CHUNK)353 if not chunk:354 break355 h.update(chunk)356 size += len(chunk)357 return h.hexdigest(), size358359360def walk(pack_dir):361 """Yields (relative path, lstat) of every non-directory below the pack directory, without following links."""362 for root, dirs, names in os.walk(pack_dir, followlinks=False):363 dirs.sort()364 for name in sorted(names + [d for d in dirs if os.path.islink(os.path.join(root, d))]):365 full = os.path.join(root, name)366 yield os.path.relpath(full, pack_dir).replace(os.sep, "/"), os.lstat(full)367368369def check_directory(pack_dir, raw, do_hash):370 """Compares the directory with whatever file list the manifest has (aliases tolerated). Returns error strings."""371 errors = []372 listed = {}373 files = raw.get("files") if isinstance(raw, dict) else None374 for f in files if isinstance(files, list) else []:375 if isinstance(f, dict):376 path = f.get("path", f.get("name"))377 if isinstance(path, str) and path_problem(path) is None:378 listed[path] = (f.get("size", f.get("bytes")), f.get("sha256"))379 on_disk, unlisted = set(), []380 for rel, st in walk(pack_dir):381 if rel in (MANIFEST, SIGNATURE) or os.path.basename(rel) == ".DS_Store":382 continue383 if not stat.S_ISREG(st.st_mode):384 errors.append("%s: not a regular file (links and devices are refused)" % rel)385 continue386 on_disk.add(rel)387 if rel not in listed:388 unlisted.append(rel)389 if unlisted:390 shown = ", ".join(unlisted[:4]) + (", ..." if len(unlisted) > 4 else "")391 errors.append("%d file(s) on disk are not listed in files[]: %s" % (len(unlisted), shown))392 for path, (size, sha) in sorted(listed.items()):393 if path not in on_disk:394 errors.append("%s: listed but missing on disk" % path)395 continue396 full = os.path.join(pack_dir, path)397 actual = os.path.getsize(full)398 if size != actual:399 errors.append("%s: size on disk %d differs from the manifest (%r)" % (path, actual, size))400 elif do_hash and sha256_file(full)[0] != sha:401 errors.append("%s: SHA-256 differs from the manifest" % path)402 return errors403404405def load_manifest(pack_dir):406 path = os.path.join(pack_dir, MANIFEST)407 with open(path, "rb") as fh:408 data = fh.read()409 return data, json.loads(data.decode("utf-8"))410411412def dump(obj):413 return (json.dumps(obj, indent=2, sort_keys=True, ensure_ascii=False) + "\n").encode("utf-8")414415416def cmd_validate(args):417 failed = False418 for pack_dir in args.packs:419 print("== %s" % pack_dir)420 try:421 _, raw = load_manifest(pack_dir)422 except (OSError, ValueError) as exc:423 print(" ERROR cannot read manifest.json: %s" % exc)424 failed = True425 continue426 _, errors, notes = validate_manifest(raw)427 disk = check_directory(pack_dir, raw, not args.no_hash)428 for e in errors:429 print(" ERROR schema: %s" % e)430 for e in disk:431 print(" ERROR files: %s" % e)432 for n in sorted(notes):433 print(" note: %s" % n)434 print(" result: %s" % ("VALID (schema v1)" if not errors and not disk else "INVALID (%d schema error(s), %d file error(s))" % (len(errors), len(disk))))435 failed = failed or bool(errors or disk)436 return 1 if failed else 0437438439def cmd_hash(args):440 data, raw = load_manifest(args.pack)441 listed = [f.get("path", f.get("name")) for f in raw.get("files", []) if isinstance(f, dict)]442 by_path = {f.get("path", f.get("name")): f for f in raw.get("files", []) if isinstance(f, dict)}443 if args.all:444 listed = [rel for rel, st in walk(args.pack) if stat.S_ISREG(st.st_mode) and rel not in (MANIFEST, SIGNATURE) and os.path.basename(rel) != ".DS_Store"]445 out, total = [], 0446 for path in listed:447 sha, size = sha256_file(os.path.join(args.pack, path))448 entry = dict(by_path.get(path, {}))449 for alias in ("name", "bytes"):450 entry.pop(alias, None)451 entry.update({"path": path, "size": size, "sha256": sha})452 out.append(entry)453 total += size454 if args.write:455 raw["files"] = out456 raw["installedSize"] = total457 with open(os.path.join(args.pack, MANIFEST), "wb") as fh:458 fh.write(dump(raw))459 print("updated %s: %d file(s), installedSize %d" % (os.path.join(args.pack, MANIFEST), len(out), total))460 else:461 sys.stdout.write(dump({"files": out, "installedSize": total}).decode("utf-8"))462 return 0463464465def cmd_announce(args):466 _, raw = load_manifest(args.pack)467 raw["signature"] = {"algorithm": "ed25519", "keyID": args.key_id, "file": SIGNATURE}468 with open(os.path.join(args.pack, MANIFEST), "wb") as fh:469 fh.write(dump(raw))470 print("signature block written; now sign with packsign.swift (any later edit of manifest.json invalidates the signature)")471 return 0472473474def tar_header(path, size):475 raw = path.encode("utf-8")476 name, prefix = raw, b""477 if len(raw) > 100:478 split = None479 for i, b in enumerate(raw):480 if b == 0x2F and i <= 155 and len(raw) - i - 1 <= 100:481 split = i482 if split is None:483 raise ValueError("%s: path too long for a ustar header" % path)484 prefix, name = raw[:split], raw[split + 1:]485 if size > USTAR_MAX:486 raise ValueError("%s: larger than the 8 GiB ustar limit" % path)487 h = bytearray(512)488 h[0:len(name)] = name489 h[100:107] = b"0000644"490 h[108:115] = b"0000000"491 h[116:123] = b"0000000"492 h[124:135] = b"%011o" % size493 h[136:147] = b"%011o" % 0494 h[148:156] = b" " * 8495 h[156] = ord("0")496 h[257:262] = b"ustar"497 h[263:265] = b"00"498 h[345:345 + len(prefix)] = prefix499 h[148:154] = b"%06o" % sum(h)500 h[154] = 0501 h[155] = 0x20502 return bytes(h)503504505def cmd_build(args):506 data, raw = load_manifest(args.pack)507 manifest, errors, _ = validate_manifest(raw)508 errors += check_directory(args.pack, raw, True)509 if errors:510 for e in errors:511 print("ERROR %s" % e, file=sys.stderr)512 return 1513 tmp = args.output + ".partial"514 sink = open(tmp, "wb")515 # mtime=0 and no file name in the gzip header: identical inputs give identical archives.516 out = gzip.GzipFile(filename="", mode="wb", fileobj=sink, mtime=0, compresslevel=6) if args.gzip else sink517 try:518 def entry(name, size, reader):519 out.write(tar_header(name, size))520 written = 0521 while True:522 chunk = reader.read(CHUNK)523 if not chunk:524 break525 out.write(chunk)526 written += len(chunk)527 if written != size:528 raise ValueError("%s changed while it was being archived" % name)529 out.write(b"\0" * ((512 - size % 512) % 512))530 entry(MANIFEST, len(data), io.BytesIO(data)) # exact bytes on disk: a signature covers them531 sig = os.path.join(args.pack, SIGNATURE)532 if os.path.isfile(sig) and not os.path.islink(sig):533 with open(sig, "rb") as fh:534 blob = fh.read()535 entry(SIGNATURE, len(blob), io.BytesIO(blob))536 for f in manifest["files"]:537 with open(os.path.join(args.pack, f["path"]), "rb") as fh:538 entry(f["path"], f["size"], fh)539 out.write(b"\0" * 1024)540 if args.gzip:541 out.close()542 sink.close()543 os.replace(tmp, args.output)544 except BaseException:545 sink.close()546 if os.path.exists(tmp):547 os.remove(tmp)548 raise549 sha, size = sha256_file(args.output)550 print(json.dumps({"archive": args.output, "id": manifest["id"], "version": manifest["version"], "archiveSize": size, "archiveSHA256": sha,551 "installedSize": manifest["installedSize"], "signed": os.path.isfile(os.path.join(args.pack, SIGNATURE))}, indent=2))552 return 0553554555def read_archive_manifest(path):556 with open(path, "rb") as fh:557 magic = fh.read(2)558 opener = gzip.open if magic == b"\x1f\x8b" else open559 with opener(path, "rb") as fh:560 header = fh.read(512)561 name = header[0:100].split(b"\0", 1)[0].decode("utf-8")562 if len(header) != 512 or name != MANIFEST or header[257:262] != b"ustar":563 raise ValueError("%s: the first entry is not manifest.json" % path)564 size = int(header[124:135], 8)565 if size > 32 << 20:566 raise ValueError("%s: manifest too large" % path)567 return json.loads(fh.read(size).decode("utf-8"))568569570def cmd_index(args):571 entries = []572 for archive in args.archives:573 manifest, errors, _ = validate_manifest(read_archive_manifest(archive))574 if errors:575 for e in errors:576 print("ERROR %s: %s" % (archive, e), file=sys.stderr)577 return 1578 sha, size = sha256_file(archive)579 title = manifest["title"] if isinstance(manifest["title"], dict) else {"en": manifest["title"]}580 entry = {581 "id": manifest["id"], "version": manifest["version"], "kind": manifest["kind"], "title": title,582 "installedSize": manifest["installedSize"], "archiveSize": size,583 "license": manifest.get("license") or " · ".join(s["license"] for s in manifest["sources"]),584 "redistribution": manifest["redistribution"],585 "archiveURL": (args.base_url.rstrip("/") + "/" if args.base_url else "") + os.path.basename(archive),586 "archiveSHA256": sha, "dependencies": manifest.get("dependencies", []),587 }588 desc = manifest.get("description")589 if desc is not None:590 entry["description"] = desc if isinstance(desc, dict) else {"en": desc}591 for key in ("coverage", "minimumAppVersion"):592 if manifest.get(key) is not None:593 entry[key] = manifest[key]594 if manifest.get("signature"):595 entry["signatureKeyID"] = manifest["signature"]["keyID"]596 if manifest["redistribution"] != "redistributable":597 print("ERROR %s: pack %s is localBuildOnly and must not be published in an index" % (archive, manifest["id"]), file=sys.stderr)598 return 1599 entries.append(entry)600 ids = [e["id"] for e in entries]601 if len(set(ids)) != len(ids):602 print("ERROR the same pack id appears twice", file=sys.stderr)603 return 1604 index = {"schemaVersion": 1, "packs": sorted(entries, key=lambda e: e["id"])}605 if args.generated:606 index["generated"] = args.generated607 with open(args.output, "wb") as fh:608 fh.write(dump(index))609 print("wrote %s (%d pack(s))" % (args.output, len(entries)))610 return 0611612613def main(argv):614 parser = argparse.ArgumentParser(description="ORIX Cosmos pack tooling", epilog=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)615 sub = parser.add_subparsers(dest="command", required=True)616 p = sub.add_parser("validate"); p.add_argument("packs", nargs="+"); p.add_argument("--no-hash", action="store_true"); p.set_defaults(func=cmd_validate)617 p = sub.add_parser("hash"); p.add_argument("pack"); p.add_argument("--all", action="store_true"); p.add_argument("--write", action="store_true"); p.set_defaults(func=cmd_hash)618 p = sub.add_parser("announce-signature"); p.add_argument("pack"); p.add_argument("key_id"); p.set_defaults(func=cmd_announce)619 p = sub.add_parser("build"); p.add_argument("pack"); p.add_argument("-o", "--output", required=True); p.add_argument("--gzip", action="store_true"); p.set_defaults(func=cmd_build)620 p = sub.add_parser("index"); p.add_argument("archives", nargs="+"); p.add_argument("-o", "--output", required=True); p.add_argument("--base-url"); p.add_argument("--generated"); p.set_defaults(func=cmd_index)621 args = parser.parse_args(argv)622 try:623 return args.func(args)624 except (OSError, ValueError) as exc:625 print("ERROR %s" % exc, file=sys.stderr)626 return 2627628629if __name__ == "__main__":630 sys.exit(main(sys.argv[1:]))631