SPB Git

Repository Public BSD-3-Clause

CommandLineTool.swift 25.2 KB 461 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Infrastructure/package-builder/Sources/PackageBuilderKit/CommandLineTool.swift10// Module           : PackageBuilderKit11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import CryptoKit89import Foundation90import ORIXGeoCore91import ORIXMapPackage9293/// The `orix-package` command. Kept in the library so that tests drive it without spawning a process.94public enum CommandLineTool {95    public static let version = "1.0.0"9697    public static let usage = """98    orix-package \(version) — builds, signs, verifies and publishes ORIX Maps region packages (.orixmap)99100    USAGE101      orix-package keygen  --out <dir> [--label <text>]102      orix-package build   --region <id> --name-en <text> --name-fr <text> [--name <lang>=<text>]...103                           --data-version <v> --data-timestamp <YYYY-MM-DDTHH:MM:SSZ>104                           [--bbox <minLon,minLat,maxLon,maxLat>] --map <file.pmtiles> [--search <file.sqlite>]105                           [--routing <file.orixgraph>] [--terrain <file.pmtiles>] --licences <file.json>106                           [--languages <en,fr,...>] [--search-format <n>] [--routing-format <n>] [--min-app-version <v>]107                           [--builder <tool>=<version>]... [--build-date <timestamp>]108                           [--key <private key file>] --out <file.orixmap>109      orix-package verify  <file.orixmap> --trust <public key or trust store json>110      orix-package inspect <file.orixmap> [--trust <public key or trust store json>] [--json]111      orix-package publish <file.orixmap> --dir <distribution dir> --trust <...>112      orix-package catalog --dir <distribution dir> --trust <...> [--latest <id>=<version>]... [--unpin <id>]...113      orix-package install <file.orixmap> --store <dir> --trust <...> [--allow-downgrade] [--reinstall]114      orix-package fixture --kind <pmtiles|blob> --size <bytes> --out <file> [--bbox <...>] [--seed <n>]115116    The private key is read from --key, or from the file named by the environment variable117    \(SigningKeys.environmentVariable). It must be a regular file with mode 600 owned by the current user118    (expected location on the build machine: \(SigningKeys.expectedDirectory)/).119    """120121    struct Failure: Error { var message: String }122123    struct Arguments {124        var positionals: [String] = []125        var options: [String: [String]] = [:]126        var flags: Set<String> = []127128        init(_ raw: [String], flags known: Set<String>) throws {129            var i = 0130            while i < raw.count {131                let a = raw[i]132                if a.hasPrefix("--") {133                    let name = String(a.dropFirst(2))134                    if known.contains(name) { flags.insert(name) } else {135                        guard i + 1 < raw.count else { throw Failure(message: "missing value for --\(name)") }136                        options[name, default: []].append(raw[i + 1])137                        i += 1138                    }139                } else { positionals.append(a) }140                i += 1141            }142        }143144        func one(_ name: String) throws -> String? {145            guard let values = options[name] else { return nil }146            guard values.count == 1 else { throw Failure(message: "--\(name) given more than once") }147            return values[0]148        }149150        func required(_ name: String) throws -> String {151            guard let v = try one(name) else { throw Failure(message: "missing --\(name)") }152            return v153        }154155        func checkKnown(_ names: Set<String>) throws {156            for name in options.keys where !names.contains(name) { throw Failure(message: "unknown option --\(name)") }157        }158    }159160    /// Runs one command. Returns the process exit status: 0 success, 1 failure, 2 usage error.161    public static func run(arguments: [String], environment: [String: String], output: (String) -> Void, errorOutput: (String) -> Void) async -> Int32 {162        guard let command = arguments.first, command != "--help", command != "-h", command != "help" else {163            output(usage)164            return arguments.isEmpty ? 2 : 0165        }166        do {167            let args = try Arguments(Array(arguments.dropFirst()), flags: ["json", "allow-downgrade", "reinstall"])168            switch command {169            case "keygen": try keygen(args, output)170            case "build": try build(args, environment, output)171            case "verify": try verify(args, output)172            case "inspect": try inspect(args, output)173            case "publish": try publish(args, output)174            case "catalog": try catalog(args, output)175            case "install": try await install(args, output)176            case "fixture": try fixture(args, output)177            case "--version", "version": output(version)178            default:179                errorOutput("unknown command \(command)\n\n\(usage)")180                return 2181            }182            return 0183        } catch let failure as Failure {184            errorOutput("error: \(failure.message)")185            return 1186        } catch {187            errorOutput("error: \(error)")188            return 1189        }190    }191192    static func fileURL(_ path: String) -> URL { URL(fileURLWithPath: (path as NSString).expandingTildeInPath) }193194    static func trust(_ args: Arguments) throws -> TrustStore {195        do { return try SigningKeys.loadTrust(at: fileURL(try args.required("trust"))) } catch let e as SigningKeys.KeyError { throw Failure(message: e.description) }196    }197198    static func parseBBox(_ text: String) throws -> BoundingBox {199        let parts = text.split(separator: ",").map { Double($0.trimmingCharacters(in: .whitespaces)) }200        guard parts.count == 4, let minLon = parts[0], let minLat = parts[1], let maxLon = parts[2], let maxLat = parts[3] else {201            throw Failure(message: "--bbox expects minLon,minLat,maxLon,maxLat")202        }203        return BoundingBox(minLat: minLat, minLon: minLon, maxLat: maxLat, maxLon: maxLon)204    }205206    static func pairs(_ values: [String], option: String) throws -> [String: String] {207        var out: [String: String] = [:]208        for v in values {209            guard let eq = v.firstIndex(of: "="), eq != v.startIndex else { throw Failure(message: "--\(option) expects <key>=<value>, got \(v)") }210            out[String(v[..<eq])] = String(v[v.index(after: eq)...])211        }212        return out213    }214215    // MARK: keygen216217    static func keygen(_ args: Arguments, _ output: (String) -> Void) throws {218        try args.checkKnown(["out", "label"])219        let generated: SigningKeys.Generated220        do { generated = try SigningKeys.generate(in: fileURL(try args.required("out")), label: try args.one("label")) } catch let e as SigningKeys.KeyError {221            throw Failure(message: e.description)222        }223        output("""224        key id      \(generated.keyId)225        private key \(generated.privateKeyURL.path)   (mode 600 — never commit, never copy into the app)226        public key  \(generated.publicKeyURL.path)227        trust store \(generated.trustStoreURL.path)228229        Swift, for the application trust store:230        \(SigningKeys.swiftSnippet(keyId: generated.keyId, publicKeyBase64: generated.publicKeyBase64, label: try args.one("label")))231232        JSON:233        \((try? String(contentsOf: generated.trustStoreURL, encoding: .utf8)) ?? "")234        """)235    }236237    // MARK: build238239    static func build(_ args: Arguments, _ environment: [String: String], _ output: (String) -> Void) throws {240        try args.checkKnown(["region", "name-en", "name-fr", "name", "data-version", "data-timestamp", "bbox", "map", "search", "routing", "terrain",241                             "licences", "languages", "search-format", "routing-format", "min-app-version", "builder", "build-date", "key", "out"])242        guard let keyPath = try args.one("key") ?? environment[SigningKeys.environmentVariable] else {243            throw Failure(message: "no signing key: pass --key <file> or set \(SigningKeys.environmentVariable)")244        }245        let key: Curve25519.Signing.PrivateKey246        do throws(SigningKeys.KeyError) { key = try SigningKeys.loadPrivateKey(at: fileURL(keyPath)) } catch { throw Failure(message: error.description) }247248        guard let dataVersion = DataVersion(try args.required("data-version")) else { throw Failure(message: "--data-version must look like 2026.11.24") }249        guard let dataTimestamp = Timestamp.parse(try args.required("data-timestamp")) else { throw Failure(message: "--data-timestamp must look like 2026-11-24T00:00:00Z") }250        var buildDate = Date(timeIntervalSince1970: Date().timeIntervalSince1970.rounded(.down))251        if let text = try args.one("build-date") {252            guard let d = Timestamp.parse(text) else { throw Failure(message: "--build-date must look like 2026-11-25T08:00:00Z") }253            buildDate = d254        }255        var minApp: AppVersion?256        if let text = try args.one("min-app-version") {257            guard let v = AppVersion(text) else { throw Failure(message: "--min-app-version must look like 1.2.0") }258            minApp = v259        }260261        // The map component: zoom range and bounds come from its PMTiles header.262        let mapURL = fileURL(try args.required("map"))263        func pmtiles(_ url: URL, _ what: String) throws -> PMTilesHeader {264            do { return try PMTilesHeader.read(url) } catch { throw Failure(message: "\(what) \(url.path) is not a valid PMTiles v3 archive: \(error)") }265        }266        let mapHeader = try pmtiles(mapURL, "--map")267        guard mapHeader.tileType == .mvt else { throw Failure(message: "--map must contain Mapbox Vector Tiles (tile type 1), found type \(mapHeader.tileTypeRaw)") }268        let bbox: BoundingBox269        if let text = try args.one("bbox") { bbox = try parseBBox(text) } else {270            guard let fromHeader = mapHeader.bounds else { throw Failure(message: "the PMTiles header has no usable bounds: pass --bbox") }271            bbox = fromHeader272        }273274        var components = [PackageWriter.ComponentSource(id: .map, url: mapURL, formatVersion: 3)]275        func format(_ option: String) throws -> Int {276            guard let text = try args.one(option) else { return 1 }277            guard let n = Int(text), n >= 1 else { throw Failure(message: "--\(option) expects a positive integer") }278            return n279        }280        if let path = try args.one("search") { components.append(.init(id: .search, url: fileURL(path), formatVersion: try format("search-format"))) }281        if let path = try args.one("routing") { components.append(.init(id: .routing, url: fileURL(path), formatVersion: try format("routing-format"))) }282        if let path = try args.one("terrain") {283            _ = try pmtiles(fileURL(path), "--terrain")284            components.append(.init(id: .terrain, url: fileURL(path), formatVersion: 3))285        }286287        let licencesURL = fileURL(try args.required("licences"))288        guard let licenceData = try? Data(contentsOf: licencesURL), let licences = try? JSONDecoder().decode([Licence].self, from: licenceData) else {289            throw Failure(message: "--licences must be a JSON array of {source, licence, attribution, url}: \(licencesURL.path)")290        }291        var names = try pairs(args.options["name"] ?? [], option: "name")292        names["en"] = try args.required("name-en")293        names["fr"] = try args.required("name-fr")294        var builder = try pairs(args.options["builder"] ?? [], option: "builder")295        builder["orix-package"] = version296        let languages = (try args.one("languages") ?? "en,fr").split(separator: ",").map(String.init)297298        let description = PackageWriter.Description(299            regionId: try args.required("region"), names: names, bbox: bbox, dataVersion: dataVersion, dataTimestamp: dataTimestamp, buildDate: buildDate,300            mapZoom: ZoomRange(minZoom: Int(mapHeader.minZoom), maxZoom: Int(mapHeader.maxZoom)), languages: languages, licences: licences,301            builder: builder, minAppVersion: minApp)302        let out = fileURL(try args.required("out"))303        let start = Date()304        let manifest = try PackageWriter.write(description: description, components: components, signingKey: key, to: out)305        output("wrote \(out.path)")306        output("  region \(manifest.regionId)  data version \(manifest.dataVersion)  key \(manifest.signingKeyId)")307        output("  download size \(manifest.downloadSize) bytes, installed size \(manifest.installedSize) bytes, container overhead \(manifest.downloadSize - manifest.installedSize) bytes")308        output(String(format: "  built in %.2f s", Date().timeIntervalSince(start)))309    }310311    // MARK: verify, inspect312313    static func verify(_ args: Arguments, _ output: (String) -> Void) throws {314        try args.checkKnown(["trust"])315        guard args.positionals.count == 1 else { throw Failure(message: "verify expects one file") }316        let url = fileURL(args.positionals[0])317        let start = Date()318        let verified: VerifiedPackage319        let trustStore = try trust(args)320        do throws(PackageError) { verified = try PackageVerifier(trustStore: trustStore).verify(at: url) } catch {321            throw Failure(message: "INVALID \(url.lastPathComponent): \(error)")322        }323        let m = verified.manifest324        output("OK \(url.lastPathComponent)")325        output("  region \(m.regionId)  data version \(m.dataVersion)  signed by \(m.signingKeyId)\(verified.preamble.signingKey.label.map { " (\($0))" } ?? "")")326        output("  \(m.components.count) components, \(m.installedSize) bytes verified, file \(verified.fileSize) bytes")327        if !verified.ignoredComponents.isEmpty { output("  ignored (unknown) components: \(verified.ignoredComponents.map(\.rawValue).joined(separator: ", "))") }328        output(String(format: "  verified in %.3f s", Date().timeIntervalSince(start)))329    }330331    static func inspect(_ args: Arguments, _ output: (String) -> Void) throws {332        try args.checkKnown(["trust"])333        guard args.positionals.count == 1 else { throw Failure(message: "inspect expects one file") }334        let url = fileURL(args.positionals[0])335        guard let handle = try? FileHandle(forReadingFrom: url) else { throw Failure(message: "cannot open \(url.path)") }336        defer { try? handle.close() }337        let fileSize = (try? handle.seekToEnd()) ?? 0338        try? handle.seek(toOffset: 0)339        let prefix = (try? handle.read(upToCount: PackageFormat.fixedHeaderLength)) ?? Data()340        let header = try PackageHeader.parse(prefix)341        try? handle.seek(toOffset: header.manifestOffset)342        let manifestBytes = (try? handle.read(upToCount: Int(header.manifestLength))) ?? Data()343        guard manifestBytes.count == Int(header.manifestLength) else { throw Failure(message: "file truncated inside the manifest") }344345        if args.flags.contains("json") {346            output(String(decoding: manifestBytes, as: UTF8.self))347            return348        }349        let manifest = try PackageManifest.decode(manifestBytes)350        var signature = "not checked (no --trust)"351        if args.options["trust"] != nil {352            let trustStore = try trust(args)353            do throws(PackageError) {354                _ = try PackageVerifier(trustStore: trustStore).readPreamble(at: url)355                signature = "valid, key trusted"356            } catch { signature = "REJECTED: \(error)" }357        }358        var layout = "valid"359        do throws(PackageError) { try PackageLayout.validate(header: header, manifest: manifest, fileSize: fileSize) } catch { layout = "INVALID: \(error)" }360361        output("file            \(url.path)")362        output("format          orixmap \(header.versionMajor).\(header.versionMinor), header \(header.headerLength) B, manifest \(header.manifestLength) B, signature \(header.signatureLength) B (Ed25519)")363        output("preamble        \(header.preambleLength) bytes (fetch with Range: bytes=0-\(header.preambleLength - 1))")364        output("total length    \(header.totalLength) bytes (file on disk: \(fileSize))")365        output("signing key     \(header.keyId) — signature \(signature)")366        output("layout          \(layout)")367        output("region          \(manifest.regionId) — \(manifest.names.sorted { $0.key < $1.key }.map { "\($0.key): \($0.value)" }.joined(separator: " / "))")368        output("data version    \(manifest.dataVersion) (OSM data \(manifest.dataTimestamp), built \(manifest.buildDate))")369        output("bbox            \(manifest.bbox.minLon),\(manifest.bbox.minLat),\(manifest.bbox.maxLon),\(manifest.bbox.maxLat)")370        if let z = manifest.mapZoom { output("map zoom        \(z.minZoom)–\(z.maxZoom)") }371        output("capabilities    \(manifest.capabilities.joined(separator: ", "))")372        output("languages       \(manifest.languages.joined(separator: ", "))")373        output("min app version \(manifest.minAppVersion?.rawValue ?? "—")")374        output("builder         \(manifest.builder.sorted { $0.key < $1.key }.map { "\($0.key) \($0.value)" }.joined(separator: ", "))")375        output("sizes           download \(manifest.downloadSize), installed \(manifest.installedSize), overhead \(manifest.downloadSize - manifest.installedSize)")376        output("licences")377        for l in manifest.licences { output("  \(l.source) — \(l.licence) — \(l.attribution) — \(l.url)") }378        output("components")379        output("  id        offset        length        format  media type                    installed as        sha256")380        for c in manifest.components {381            func pad(_ s: String, _ n: Int) -> String { s.count >= n ? s : s + String(repeating: " ", count: n - s.count) }382            output("  \(pad(c.id.rawValue, 9)) \(pad(String(c.offset), 13)) \(pad(String(c.length), 13)) \(pad(String(c.formatVersion), 7)) \(pad(c.mediaType, 29)) \(pad(c.id.installedFileName ?? "(ignored)", 19)) \(c.sha256)")383        }384    }385386    // MARK: publish, catalog387388    static func describe(_ report: CatalogGenerator.Report, _ output: (String) -> Void) {389        output("verified \(report.packagesVerified) package(s)")390        for r in report.regions {391            output("  \(r.id): latest \(r.latest)\(r.pinned ? " (pinned)" : ""), versions \(r.versions.map(\.rawValue).joined(separator: ", "))")392        }393        for path in report.written { output("  wrote \(path)") }394        for path in report.removed { output("  removed \(path)") }395    }396397    static func publish(_ args: Arguments, _ output: (String) -> Void) throws {398        try args.checkKnown(["dir", "trust"])399        guard args.positionals.count == 1 else { throw Failure(message: "publish expects one file") }400        let distribution = fileURL(try args.required("dir"))401        let store = try trust(args)402        do throws(CatalogGenerator.BuildError) {403            let path = try CatalogGenerator.addPackage(fileURL(args.positionals[0]), to: distribution, trust: store)404            output("added \(path)")405            describe(try CatalogGenerator.generate(distribution: distribution, trust: store), output)406        } catch { throw Failure(message: error.description) }407    }408409    static func catalog(_ args: Arguments, _ output: (String) -> Void) throws {410        try args.checkKnown(["dir", "trust", "latest", "unpin", "generated-at"])411        var latest: [String: DataVersion] = [:]412        for (id, text) in try pairs(args.options["latest"] ?? [], option: "latest") {413            guard let v = DataVersion(text) else { throw Failure(message: "--latest \(id)=\(text): invalid version") }414            latest[id] = v415        }416        var generatedAt = Date()417        if let text = try args.one("generated-at") {418            guard let d = Timestamp.parse(text) else { throw Failure(message: "--generated-at must look like 2026-11-25T09:00:00Z") }419            generatedAt = d420        }421        do {422            describe(try CatalogGenerator.generate(distribution: fileURL(try args.required("dir")), trust: try trust(args), generatedAt: generatedAt,423                                                   setLatest: latest, unpin: args.options["unpin"] ?? []), output)424        } catch let e as CatalogGenerator.BuildError { throw Failure(message: e.description) }425    }426427    // MARK: install (development: what the phone does, on this Mac)428429    static func install(_ args: Arguments, _ output: (String) -> Void) async throws {430        try args.checkKnown(["store", "trust"])431        guard args.positionals.count == 1 else { throw Failure(message: "install expects one file") }432        let store = try RegionStore(root: fileURL(try args.required("store")), configuration: RegionStore.Configuration(trustStore: try trust(args)))433        if !store.recoveryReport.isClean { output("recovered: \(store.recoveryReport)") }434        let start = Date()435        let region = try await store.install(packageAt: fileURL(args.positionals[0]),436                                             options: InstallOptions(allowDowngrade: args.flags.contains("allow-downgrade"), reinstall: args.flags.contains("reinstall")))437        output("installed \(region.id) \(region.dataVersion) in \(region.directory.path)")438        output("  size on disk \(region.sizeOnDisk) bytes\(region.previousVersion.map { ", previous version kept: \($0)" } ?? "")")439        output(String(format: "  installed in %.3f s", Date().timeIntervalSince(start)))440    }441442    // MARK: fixture443444    static func fixture(_ args: Arguments, _ output: (String) -> Void) throws {445        try args.checkKnown(["kind", "size", "out", "bbox", "seed"])446        guard let size = Int(try args.required("size")), size >= 0, size <= 8 << 30 else { throw Failure(message: "--size expects a number of bytes (at most 8 GiB)") }447        let out = fileURL(try args.required("out"))448        let seed = UInt64(try args.one("seed") ?? "1") ?? 1449        switch try args.required("kind") {450        case "pmtiles":451            let bbox = try parseBBox(try args.one("bbox") ?? "-74.35,45.15,-73.15,45.95")452            try Fixtures.writePMTiles(to: out, size: size, bounds: bbox, seed: seed)453        case "blob":454            try Fixtures.writeBlob(to: out, size: size, seed: seed)455        default:456            throw Failure(message: "--kind must be pmtiles or blob")457        }458        output("wrote synthetic \(out.path) (\(size) bytes) — test data, not a map")459    }460}461
Files main
Menu

Theme