SPB Git

Repository Public License

Support.swift 9.8 KB 229 lines swift

1// ORIX Convert — Packages/ConvertKit/Sources/ConvertCLI/Support.swift2// Description: Pieces shared by the commands that run conversions: option parsing (types, ranges, secrets), the3//              interrupt centre (Ctrl-C), and the terminal screen that mixes a live progress line with result lines.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation6import ConvertCore78// MARK: - Options910enum OptionParsing {11    struct Raw: Sendable, Equatable {12        let key: String13        let value: String14    }1516    /// Splits `key=value` arguments and resolves secret references. For keys holding a secret (any key containing17    /// `password`), `@env:NAME` reads the environment variable NAME and `@stdin` reads one line from standard input,18    /// so the secret never appears in the process list. A secret is never echoed in a message.19    static func resolve(_ arguments: [String], io: CommandIO) throws -> [Raw] {20        var result: [Raw] = []21        var warnedLiteral = false22        for argument in arguments {23            guard let equals = argument.firstIndex(of: "="), equals != argument.startIndex else {24                throw UsageError("--option expects key=value, not '\(ConversionOptions.isSecretKey(argument) ? "<hidden>" : argument)'.")25            }26            let key = String(argument[..<equals])27            var value = String(argument[argument.index(after: equals)...])28            if ConversionOptions.isSecretKey(key) {29                if value.hasPrefix("@env:") {30                    let name = String(value.dropFirst(5))31                    guard let secret = io.environment[name], !secret.isEmpty else {32                        throw UsageError("--option \(key)=@env:\(name): the environment variable \(name) is not set.")33                    }34                    value = secret35                } else if value == "@stdin" {36                    guard let line = io.readLine(), !line.isEmpty else {37                        throw UsageError("--option \(key)=@stdin: nothing could be read from standard input.")38                    }39                    value = line40                } else if value.hasPrefix("@@") {41                    value = String(value.dropFirst())42                } else if !warnedLiteral {43                    warnedLiteral = true44                    io.err("orix-convert: warning: the value of '\(key)' was given on the command line, where other processes can read it. Prefer \(key)=@env:VARIABLE or \(key)=@stdin.")45                }46            }47            result.append(Raw(key: key, value: value))48        }49        return result50    }5152    /// Types the values against the path's descriptors (range and choice checked). A key the path does not describe53    /// is passed with an inferred type and reported through `unknown`.54    static func typed(_ raws: [Raw], descriptors: [OptionDescriptor], unknown: (String) -> Void = { _ in }) throws -> ConversionOptions {55        var options = ConversionOptions()56        let byKey = Dictionary(descriptors.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })57        for raw in raws {58            let shown = ConversionOptions.isSecretKey(raw.key) ? "<hidden>" : "'\(raw.value)'"59            guard let descriptor = byKey[raw.key] else {60                unknown(raw.key)61                options[raw.key] = ConversionOptions.isSecretKey(raw.key) ? .string(raw.value) : infer(raw.value)62                continue63            }64            switch descriptor.kind {65            case .toggle:66                guard let value = bool(raw.value) else { throw UsageError("--option \(raw.key): expected true or false, not \(shown).") }67                options[raw.key] = .bool(value)68            case .integer(_, let range, _):69                guard let value = Int(raw.value), range.contains(value) else {70                    throw UsageError("--option \(raw.key): expected a whole number between \(range.lowerBound) and \(range.upperBound), not \(shown).")71                }72                options[raw.key] = .int(value)73            case .number(_, let range, _, _):74                guard let value = Double(raw.value), range.contains(value) else {75                    throw UsageError("--option \(raw.key): expected a number between \(range.lowerBound) and \(range.upperBound), not \(shown).")76                }77                options[raw.key] = .double(value)78            case .choice(_, let choices):79                guard choices.contains(where: { $0.value == raw.value }) else {80                    throw UsageError("--option \(raw.key): expected one of \(choices.map(\.value).joined(separator: ", ")), not \(shown).")81                }82                options[raw.key] = .string(raw.value)83            case .text:84                options[raw.key] = .string(raw.value)85            }86        }87        return options88    }8990    static func options(_ arguments: [String], descriptors: [OptionDescriptor], io: CommandIO, strict: Bool) throws -> ConversionOptions {91        try typed(try resolve(arguments, io: io), descriptors: descriptors) { key in92            if strict { io.err("orix-convert: warning: '\(key)' is not a documented setting of this conversion; it is passed as given.") }93        }94    }9596    static func bool(_ text: String) -> Bool? {97        switch text.lowercased() {98        case "true", "yes", "on", "1": true99        case "false", "no", "off", "0": false100        default: nil101        }102    }103104    static func infer(_ text: String) -> OptionValue {105        if text == "true" || text == "false" { return .bool(text == "true") }106        if let value = Int(text) { return .int(value) }107        if let value = Double(text), text.contains(".") { return .double(value) }108        return .string(text)109    }110}111112// MARK: - Interrupts113114/// Turns Ctrl-C (SIGINT) and SIGTERM into a cooperative cancellation: the running command cancels its jobs, which115/// removes their work folders, then exits with status 130.116public final class InterruptCenter: @unchecked Sendable {117    public static let shared = InterruptCenter()118    private let lock = NSLock()119    private var handlers: [UUID: @Sendable () -> Void] = [:]120    private var interrupted = false121    private var sources: [DispatchSourceSignal] = []122123    /// Installs the signal handlers. Called once by the executable; tests use `trigger()` instead.124    public func install() {125        lock.lock(); defer { lock.unlock() }126        guard sources.isEmpty else { return }127        for number in [SIGINT, SIGTERM] {128            signal(number, SIG_IGN)129            let source = DispatchSource.makeSignalSource(signal: number, queue: .global(qos: .userInitiated))130            source.setEventHandler { [weak self] in self?.trigger(fromSignal: true) }131            source.resume()132            sources.append(source)133        }134    }135136    public var isInterrupted: Bool { lock.lock(); defer { lock.unlock() }; return interrupted }137138    /// Clears the interrupted state (tests).139    public func reset() { lock.lock(); interrupted = false; lock.unlock() }140141    public func trigger(fromSignal: Bool = false) {142        lock.lock()143        let second = interrupted144        interrupted = true145        let current = Array(handlers.values)146        lock.unlock()147        if second && fromSignal {148            // A second Ctrl-C while the first is still being honoured: give up waiting.149            FileHandle.standardError.write(Data("\norix-convert: interrupted twice; exiting without waiting for the running jobs.\n".utf8))150            exit(ExitCode.interrupted.rawValue)151        }152        current.forEach { $0() }153    }154155    func register(_ handler: @escaping @Sendable () -> Void) -> UUID {156        let id = UUID()157        lock.lock(); handlers[id] = handler; let already = interrupted; lock.unlock()158        if already { handler() }159        return id160    }161162    func unregister(_ id: UUID) { lock.lock(); handlers[id] = nil; lock.unlock() }163}164165// MARK: - Screen166167/// Serialises output so a live progress line (terminal only) never tears result lines.168final class Screen: @unchecked Sendable {169    private let io: CommandIO170    private let lock = NSLock()171    private var progressShown = false172    private var lastDraw = Date.distantPast173    let showsProgress: Bool174175    init(io: CommandIO, showsProgress: Bool) {176        self.io = io177        self.showsProgress = showsProgress && io.progressIsTTY178    }179180    func line(_ text: String) {181        lock.lock(); defer { lock.unlock() }182        clearLocked()183        io.out(text)184    }185186    func error(_ text: String) {187        lock.lock(); defer { lock.unlock() }188        clearLocked()189        io.err(text)190    }191192    /// Redraws the progress line (at most ten times a second unless `force`).193    func progress(_ text: String, force: Bool = false) {194        guard showsProgress else { return }195        lock.lock(); defer { lock.unlock() }196        let now = Date()197        guard force || now.timeIntervalSince(lastDraw) >= 0.1 else { return }198        lastDraw = now199        io.progress("\r\u{1B}[2K" + String(text.prefix(118)))200        progressShown = true201    }202203    func clear() { lock.lock(); clearLocked(); lock.unlock() }204205    private func clearLocked() {206        if progressShown { io.progress("\r\u{1B}[2K"); progressShown = false }207    }208}209210extension ConversionError {211    /// Stable machine name of the error case, for JSON output.212    var kind: String {213        switch self {214        case .unsupportedPath: "unsupportedPath"215        case .unreadableInput: "unreadableInput"216        case .malformedInput: "malformedInput"217        case .encryptedInput: "encryptedInput"218        case .engineUnavailable: "engineUnavailable"219        case .invalidOption: "invalidOption"220        case .limitExceeded: "limitExceeded"221        case .toolFailed: "toolFailed"222        case .outputInvalid: "outputInvalid"223        case .writeFailed: "writeFailed"224        case .destinationExists: "destinationExists"225        case .internalError: "internalError"226        }227    }228}229
Files main
Menu

Theme