SPB Git

Repository Public MIT

ArgumentParser.swift 10.6 KB 195 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP GlassKit7// File             : Sources/GlassCLICore/ArgumentParser.swift8// Module           : Glass CLICore9// Repository       : https://git.spboucher.ai/sp-glasskit10// Project Website  : https://glass.spboucher.ai11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : MIT33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import Foundation42import SPGlassRegistry4344/// Arguments after strict parsing: nothing unknown is ever accepted silently.45public struct ParsedArguments: Equatable, Sendable {46    public var command: String47    public var positionals: [String] = []48    public var flags: Set<String> = []49    public var options: [String: String] = [:]5051    public func flag(_ name: String) -> Bool { flags.contains(name) }52    public func option(_ name: String) -> String? { options[name] }53}5455struct CommandSpec: Sendable {56    let name: String57    let summary: String58    let usage: String59    let flags: Set<String>60    let options: Set<String>61    let positionals: ClosedRange<Int>62}6364public enum ArgumentParser {65    static let globalFlags: Set<String> = ["json", "help", "version", "offline"]66    static let globalOptions: Set<String> = ["registry", "cwd", "timeout", "public-key"]6768    static let commands: [CommandSpec] = [69        CommandSpec(name: "init", summary: "Create spglass.json for this project.", usage: "spglass init [--path <dir>] [--themes-path <dir>] [--force]", flags: ["force"], options: ["path", "themes-path"], positionals: 0...0),70        CommandSpec(name: "list", summary: "List registry components or themes.", usage: "spglass list [--category <name>] [--kind <kind>] [--installed] [--themes]", flags: ["installed", "themes"], options: ["category", "kind"], positionals: 0...0),71        CommandSpec(name: "info", summary: "Show the manifest of a component.", usage: "spglass info <id> [--version <x.y.z>]", flags: [], options: ["version"], positionals: 1...1),72        CommandSpec(name: "add", summary: "Install components and their dependencies as source files.", usage: "spglass add <id>… [--version <x.y.z>] [--dry-run] [--overwrite] [--write-incoming]", flags: ["dry-run", "overwrite", "write-incoming"], options: ["version"], positionals: 1...64),73        CommandSpec(name: "theme add", summary: "Install theme files.", usage: "spglass theme add <id>… [--dry-run] [--overwrite]", flags: ["dry-run", "overwrite"], options: ["version"], positionals: 1...64),74        CommandSpec(name: "theme list", summary: "List registry themes.", usage: "spglass theme list", flags: [], options: [], positionals: 0...0),75        CommandSpec(name: "diff", summary: "Show local changes against the installed registry version.", usage: "spglass diff [<id>…]", flags: [], options: [], positionals: 0...64),76        CommandSpec(name: "update", summary: "Update installed components without overwriting local changes.", usage: "spglass update [<id>…] [--version <x.y.z>] [--dry-run] [--overwrite] [--write-incoming]", flags: ["dry-run", "overwrite", "write-incoming"], options: ["version"], positionals: 0...64),77        CommandSpec(name: "remove", summary: "Remove installed components, keeping modified files.", usage: "spglass remove <id>… [--dry-run] [--force] [--prune]", flags: ["dry-run", "force", "prune"], options: [], positionals: 1...64),78        CommandSpec(name: "doctor", summary: "Check the project, the configuration and the registry.", usage: "spglass doctor", flags: [], options: [], positionals: 0...0),79        CommandSpec(name: "verify", summary: "Check installed files against the lock file.", usage: "spglass verify [--strict]", flags: ["strict"], options: [], positionals: 0...0),80        CommandSpec(name: "export", summary: "Export installed themes as Swift or JSON.", usage: "spglass export --format <swift|json> [--theme <id>] [--output <dir>] [--overwrite]", flags: ["overwrite"], options: ["format", "theme", "output"], positionals: 0...0),81    ]8283    /// Parses the arguments that follow the program name.84    ///85    /// Global options may appear anywhere; options of a command must follow the command. `--name value` and86    /// `--name=value` are both accepted, and `--` ends option parsing.87    public static func parse(_ arguments: [String]) throws -> ParsedArguments {88        var command = ""89        var spec: CommandSpec?90        var positionals: [String] = []91        var flags: Set<String> = []92        var options: [String: String] = [:]93        var onlyPositionals = false94        var pending: String?9596        for argument in arguments {97            guard argument.utf8.count <= 4096 else { throw CLIError.usage("An argument is too long.") }98            if let name = pending {99                options[name] = argument100                pending = nil101            } else if onlyPositionals || !argument.hasPrefix("-") || argument == "-" {102                if spec != nil {103                    positionals.append(argument)104                } else if command.isEmpty, argument == "theme" {105                    command = "theme"106                } else {107                    command = command.isEmpty ? argument : "\(command) \(argument)"108                    spec = commands.first { $0.name == command }109                    guard spec != nil else { throw CLIError.usage("Unknown command \"\(RegistryText.clip(command))\".") }110                }111            } else if argument == "--" {112                onlyPositionals = true113            } else if argument == "-h" {114                flags.insert("help")115            } else if argument.hasPrefix("--") {116                let body = String(argument.dropFirst(2))117                let name = body.split(separator: "=", maxSplits: 1, omittingEmptySubsequences: false).first.map(String.init) ?? body118                let inline: String? = body.contains("=") ? String(body.dropFirst(name.count + 1)) : nil119                let commandOptions = spec?.options ?? []120                // `--version` alone is the global flag; after a command that declares it, it takes a value.121                if globalOptions.contains(name) || commandOptions.contains(name) {122                    guard options[name] == nil else { throw CLIError.usage("Option --\(name) is given twice.") }123                    if let inline { options[name] = inline } else { pending = name }124                } else if globalFlags.contains(name) || (spec?.flags ?? []).contains(name) {125                    guard inline == nil else { throw CLIError.usage("Option --\(name) does not take a value.") }126                    flags.insert(name)127                } else {128                    throw CLIError.usage("Unknown option --\(RegistryText.clip(name))" + (command.isEmpty ? "." : " for `spglass \(command)`."))129                }130            } else {131                throw CLIError.usage("Unknown option \"\(RegistryText.clip(argument))\".")132            }133        }134        if let pending { throw CLIError.usage("Option --\(pending) needs a value.") }135        if command == "theme" { throw CLIError.usage("`spglass theme` needs a subcommand: add or list.") }136        if let spec, !flags.contains("help") {137            guard spec.positionals.contains(positionals.count) else {138                throw CLIError.usage("`spglass \(spec.name)` takes \(describe(spec.positionals)).", hint: "Usage: \(spec.usage)")139            }140        }141        return ParsedArguments(command: command, positionals: positionals, flags: flags, options: options)142    }143144    private static func describe(_ range: ClosedRange<Int>) -> String {145        if range == 0...0 { return "no argument" }146        if range.lowerBound == range.upperBound { return "\(range.lowerBound) argument" + (range.lowerBound > 1 ? "s" : "") }147        return range.lowerBound == 0 ? "at most \(range.upperBound) arguments" : "\(range.lowerBound) to \(range.upperBound) arguments"148    }149150    public static var helpText: String {151        var text = """152        spglass \(CLIVersion.current) — SP GlassKit source registry client153154        Usage: spglass <command> [options]155156        Commands:157158        """159        for spec in commands {160            text += "  " + spec.name.padding(toLength: 12, withPad: " ", startingAt: 0) + spec.summary + "\n"161        }162        text += """163164        Global options:165          --registry <url|dir>  Registry to use instead of the configured one (https URL or local directory).166          --public-key <key>    Base64 Ed25519 key the registry index must be signed with.167          --cwd <dir>           Project directory (default: current directory).168          --timeout <seconds>   Network timeout, 1 to 300 (default: 20).169          --offline             Use the local cache only.170          --json                Print one JSON object instead of text.171          --help, -h            Show help.  --version  Show the version.172173        Exit codes: 0 success, 1 failure, 2 usage, 3 conflict (nothing changed), 4 integrity,174        5 network, 6 not found, 7 invalid data, 130 interrupted.175176        """177        return text178    }179180    public static func help(for command: String) -> String? {181        commands.first { $0.name == command }.map { "\($0.summary)\n\nUsage: \($0.usage)\n" }182    }183}184185public enum CLIVersion {186    public static let current = "1.0.0"187}188189/// Makes untrusted text safe to print: one line, no control characters, bounded length.190public enum RegistryText {191    public static func clip(_ text: String, limit: Int = 120) -> String {192        String(text.unicodeScalars.filter { $0.value >= 0x20 && $0.value != 0x7F && !(0x80...0x9F).contains($0.value) }.prefix(limit))193    }194}195
Files main
Menu

Theme