SPB Git

Repository Public License

Arguments.swift 8.3 KB 182 lines swift

1// ORIX Convert — Packages/ConvertKit/Sources/ConvertCLI/Arguments.swift2// Description: Argument parsing of the `orix-convert` tool: a small declarative parser (flags, single and repeated3//              options, positionals), exit codes, and the I/O seam that lets the tests capture output.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation67/// Exit statuses of `orix-convert` (documented in docs/cli.md).8public enum ExitCode: Int32, Sendable, CaseIterable {9    /// Everything asked for was done (files skipped by `--on-conflict skip` count as done).10    case success = 011    /// At least one conversion (or verification item) failed.12    case conversionFailed = 113    /// The command line is wrong.14    case usage = 215    /// An input file is missing, unreadable or of unrecognised format.16    case inputError = 317    /// No engine converts that source to that destination.18    case unsupported = 419    /// The destination exists and `--on-conflict fail` was given.20    case destinationExists = 521    /// A check found a problem (`doctor`, `workflow validate`).22    case checkFailed = 623    /// Interrupted (Ctrl-C): running jobs were cancelled and temporary folders removed.24    case interrupted = 13025}2627public struct UsageError: Error, Equatable, Sendable {28    public let message: String29    public init(_ message: String) { self.message = message }30}3132/// Raised by a command to end with a message on stderr and an exit status.33public struct CommandFailure: Error, Sendable {34    public let code: ExitCode35    public let message: String36    public init(_ code: ExitCode, _ message: String) { self.code = code; self.message = message }37}3839/// Where the tool reads and writes. Replaced by buffers in tests.40public struct CommandIO: Sendable {41    public var out: @Sendable (String) -> Void42    public var err: @Sendable (String) -> Void43    /// Reads one line from standard input (without its newline); `nil` at end of input.44    public var readLine: @Sendable () -> String?45    public var environment: [String: String]46    /// Standard error is a terminal: live progress lines are drawn there.47    public var progressIsTTY: Bool48    /// Raw writer for the progress line (no newline added).49    public var progress: @Sendable (String) -> Void5051    public init(out: @escaping @Sendable (String) -> Void, err: @escaping @Sendable (String) -> Void,52                readLine: @escaping @Sendable () -> String? = { nil }, environment: [String: String] = [:],53                progressIsTTY: Bool = false, progress: @escaping @Sendable (String) -> Void = { _ in }) {54        self.out = out; self.err = err; self.readLine = readLine; self.environment = environment55        self.progressIsTTY = progressIsTTY; self.progress = progress56    }5758    public static var standard: CommandIO {59        CommandIO(60            out: { line in FileHandle.standardOutput.write(Data((line + "\n").utf8)) },61            err: { line in FileHandle.standardError.write(Data((line + "\n").utf8)) },62            readLine: { Swift.readLine(strippingNewline: true) },63            environment: ProcessInfo.processInfo.environment,64            progressIsTTY: isatty(STDERR_FILENO) == 1,65            progress: { text in FileHandle.standardError.write(Data(text.utf8)) })66    }67}6869/// What a command accepts.70public struct CommandSpec: Sendable {71    public let name: String72    public let summary: String73    public let usage: String74    /// Options without a value (`--json`).75    public let flags: Set<String>76    /// Options with exactly one value (`--to png`).77    public let options: Set<String>78    /// Options that may be given several times (`--option a=1 --option b=2`).79    public let repeated: Set<String>80    public let minPositionals: Int81    public let maxPositionals: Int?82    public let details: [String]8384    public init(_ name: String, summary: String, usage: String, flags: Set<String> = [], options: Set<String> = [],85                repeated: Set<String> = [], positionals: ClosedRange<Int>? = nil, minPositionals: Int = 0, unbounded: Bool = false,86                details: [String] = []) {87        self.name = name; self.summary = summary; self.usage = usage; self.flags = flags.union(["help"]); self.options = options88        self.repeated = repeated89        self.minPositionals = positionals?.lowerBound ?? minPositionals90        self.maxPositionals = unbounded ? nil : (positionals?.upperBound ?? minPositionals)91        self.details = details92    }9394    public var help: String {95        (["\(summary)", "", "Usage: orix-convert \(usage)"] + (details.isEmpty ? [] : [""] + details)).joined(separator: "\n")96    }97}9899public struct ParsedArguments: Sendable, Equatable {100    public var flags: Set<String> = []101    public var values: [String: [String]] = [:]102    public var positionals: [String] = []103104    public func flag(_ name: String) -> Bool { flags.contains(name) }105    public func value(_ name: String) -> String? { values[name]?.last }106    public func all(_ name: String) -> [String] { values[name] ?? [] }107108    public func int(_ name: String, in range: ClosedRange<Int>) throws -> Int? {109        guard let raw = value(name) else { return nil }110        guard let number = Int(raw), range.contains(number) else {111            throw UsageError("--\(name) expects a whole number between \(range.lowerBound) and \(range.upperBound), not '\(raw)'.")112        }113        return number114    }115116    public func double(_ name: String, in range: ClosedRange<Double>) throws -> Double? {117        guard let raw = value(name) else { return nil }118        guard let number = Double(raw), range.contains(number) else {119            throw UsageError("--\(name) expects a number between \(range.lowerBound) and \(range.upperBound), not '\(raw)'.")120        }121        return number122    }123}124125public enum ArgumentParser {126    /// Parses `arguments` (without the command name) against `spec`.127    ///128    /// `--name value` and `--name=value` are both accepted; `--` ends option parsing; a lone `-` is a positional.129    public static func parse(_ arguments: [String], spec: CommandSpec) throws -> ParsedArguments {130        var parsed = ParsedArguments()131        var index = 0132        var optionsEnded = false133        while index < arguments.count {134            let argument = arguments[index]135            index += 1136            if optionsEnded || !argument.hasPrefix("-") || argument == "-" {137                parsed.positionals.append(argument)138                continue139            }140            if argument == "--" { optionsEnded = true; continue }141            if argument == "-h" { parsed.flags.insert("help"); continue }142            guard argument.hasPrefix("--") else {143                throw UsageError("Unknown option '\(argument)'. Options are written --like-this.")144            }145            let body = String(argument.dropFirst(2))146            let name: String147            var inline: String?148            if let equals = body.firstIndex(of: "=") {149                name = String(body[..<equals])150                inline = String(body[body.index(after: equals)...])151            } else {152                name = body153            }154            if spec.flags.contains(name) {155                guard inline == nil else { throw UsageError("--\(name) takes no value.") }156                parsed.flags.insert(name)157            } else if spec.options.contains(name) || spec.repeated.contains(name) {158                let value: String159                if let inline {160                    value = inline161                } else {162                    guard index < arguments.count else { throw UsageError("--\(name) needs a value.") }163                    value = arguments[index]164                    index += 1165                }166                if spec.options.contains(name), parsed.values[name] != nil { throw UsageError("--\(name) was given more than once.") }167                parsed.values[name, default: []].append(value)168            } else {169                throw UsageError("Unknown option '--\(name)' for '\(spec.name)'.")170            }171        }172        if parsed.flag("help") { return parsed }173        if parsed.positionals.count < spec.minPositionals {174            throw UsageError("'\(spec.name)' is missing an argument. Usage: orix-convert \(spec.usage)")175        }176        if let max = spec.maxPositionals, parsed.positionals.count > max {177            throw UsageError("'\(spec.name)' got an unexpected argument '\(parsed.positionals[max])'. Usage: orix-convert \(spec.usage)")178        }179        return parsed180    }181}182
Files main
Menu

Theme