SPB Git

Repository Public License

CLI.swift 7.1 KB 154 lines swift

1// ORIX Convert — Packages/ConvertKit/Sources/ConvertCLI/CLI.swift2// Description: Entry point and command dispatch of `orix-convert`, plus the helpers every command shares (JSON3//              output, text tables, format name resolution).4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Foundation6import ConvertCore7import ConvertKit89public enum CLI {10    public static let version = "1.0.0"1112    /// Commands in help order.13    static let commands: [any Command.Type] = [14        FormatsCommand.self, PathsCommand.self, DetectCommand.self, InspectCommand.self, PlanCommand.self, OptionsCommand.self,15        ConvertCommand.self, WorkflowCommand.self, PresetsCommand.self, DoctorCommand.self, MatrixCommand.self, DevCommand.self,16    ]1718    /// Runs the tool. `arguments` excludes the executable name. Returns the exit status.19    public static func run(_ arguments: [String], io: CommandIO = .standard) async -> Int32 {20        ToolEnvironment.bootstrap()21        guard let name = arguments.first else {22            io.out(overview())23            return ExitCode.usage.rawValue24        }25        if name == "help" || name == "--help" || name == "-h" {26            if arguments.count > 1, let command = commands.first(where: { $0.spec.name == arguments[1] }) {27                io.out(command.spec.help)28            } else {29                io.out(overview())30            }31            return ExitCode.success.rawValue32        }33        if name == "version" || name == "--version" {34            io.out("orix-convert \(version)")35            return ExitCode.success.rawValue36        }37        guard let command = commands.first(where: { $0.spec.name == name }) else {38            io.err("orix-convert: unknown command '\(name)'. Run 'orix-convert help'.")39            return ExitCode.usage.rawValue40        }41        do {42            let parsed = try ArgumentParser.parse(Array(arguments.dropFirst()), spec: command.spec)43            if parsed.flag("help") {44                io.out(command.spec.help)45                return ExitCode.success.rawValue46            }47            return try await command.run(parsed, io: io).rawValue48        } catch let error as UsageError {49            io.err("orix-convert: \(error.message)")50            return ExitCode.usage.rawValue51        } catch let failure as CommandFailure {52            io.err("orix-convert: \(failure.message)")53            return failure.code.rawValue54        } catch {55            io.err("orix-convert: \(describe(error))")56            return ExitCode.conversionFailed.rawValue57        }58    }5960    static func overview() -> String {61        var lines = ["orix-convert \(version) — the ORIX Convert engines on the command line. Everything runs on this Mac.", "",62                     "Usage: orix-convert <command> [options]", "", "Commands:"]63        for command in commands where !command.hidden {64            lines.append("  " + command.spec.name.padding(toLength: 10, withPad: " ", startingAt: 0) + command.spec.summary)65        }66        lines += ["", "Run 'orix-convert help <command>' for the options of a command.",67                  "Exit status: 0 done · 1 a conversion failed · 2 usage · 3 input missing or unrecognised · 4 unsupported conversion ·",68                  "             5 destination exists (--on-conflict fail) · 6 a check failed · 130 interrupted."]69        return lines.joined(separator: "\n")70    }7172    static func describe(_ error: Error) -> String {73        (error as? LocalizedError)?.errorDescription ?? String(describing: error)74    }75}7677protocol Command {78    static var spec: CommandSpec { get }79    static var hidden: Bool { get }80    static func run(_ arguments: ParsedArguments, io: CommandIO) async throws -> ExitCode81}8283extension Command {84    static var hidden: Bool { false }85}8687// MARK: - Shared helpers8889enum Shared {90    /// The registry of this build. Building it instantiates every engine and reads its availability once.91    static func registry() -> FormatRegistry { FormatRegistry(engines: ORIXEngines.all()) }9293    static func json<T: Encodable>(_ value: T) throws -> String {94        let encoder = JSONEncoder()95        encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]96        encoder.dateEncodingStrategy = .iso860197        return String(decoding: try encoder.encode(value), as: UTF8.self)98    }99100    /// Resolves what the user typed (`jpg`, `JPEG`, `.tar.gz`, `folder`) to a catalog format.101    static func format(_ raw: String, option: String) throws -> FormatID {102        let cleaned = raw.trimmingCharacters(in: .whitespaces).lowercased().trimmingCharacters(in: CharacterSet(charactersIn: "."))103        guard !cleaned.isEmpty else { throw UsageError("\(option) needs a format name.") }104        let id = FormatID(cleaned)105        if FormatCatalog.format(id) != nil { return id }106        if let byExtension = FormatCatalog.formats(forExtension: cleaned).first { return byExtension.id }107        let byName = FormatCatalog.all.filter { $0.name.lowercased() == cleaned }108        if let match = byName.first { return match.id }109        throw UsageError("\(option): '\(raw)' is not a known format. Run 'orix-convert formats'.")110    }111112    static func category(_ raw: String) throws -> FormatCategory {113        let wanted = raw.lowercased()114        if let match = FormatCategory.allCases.first(where: { $0.rawValue.lowercased() == wanted }) { return match }115        throw UsageError("--category: '\(raw)' is not a category. Categories: \(FormatCategory.allCases.map(\.rawValue).joined(separator: ", ")).")116    }117118    /// Plain-text table with padded columns. The last column is not padded.119    static func table(_ headers: [String], _ rows: [[String]]) -> [String] {120        var widths = headers.map(\.count)121        for row in rows { for (index, cell) in row.enumerated() where index < widths.count { widths[index] = max(widths[index], cell.count) } }122        func line(_ cells: [String]) -> String {123            cells.enumerated().map { index, cell in124                index == cells.count - 1 ? cell : cell.padding(toLength: widths[index], withPad: " ", startingAt: 0)125            }.joined(separator: "  ").trimmingCharacters(in: CharacterSet(charactersIn: " "))126        }127        return [line(headers), line(widths.map { String(repeating: "-", count: $0) })] + rows.map(line)128    }129130    static func bytes(_ count: Int64) -> String {131        let units = ["bytes", "KB", "MB", "GB", "TB"]132        var value = Double(count), unit = 0133        while value >= 1000, unit < units.count - 1 { value /= 1000; unit += 1 }134        return unit == 0 ? "\(count) bytes" : String(format: "%.1f %@", locale: Locale(identifier: "en_US_POSIX"), value, units[unit])135    }136137    static func seconds(_ value: Double) -> String {138        String(format: value < 10 ? "%.2f s" : "%.1f s", locale: Locale(identifier: "en_US_POSIX"), value)139    }140141    static func fileURL(_ path: String) -> URL {142        URL(fileURLWithPath: (path as NSString).expandingTildeInPath).standardizedFileURL143    }144145    static func optionValueText(_ value: OptionValue) -> String {146        switch value {147        case .bool(let v): String(v)148        case .int(let v): String(v)149        case .double(let v): String(v)150        case .string(let v): v151        }152    }153}154
Files main
Menu

Theme