Repository Public License
1// ORIX Convert — Packages/ConvertKit/Sources/ConvertCLI/InfoCommands.swift2// Description: Read-only commands of `orix-convert`: formats, paths, detect, inspect, plan, options, presets.3// Author: Simon-Pierre Boucher — contact@spboucher.ai4import Foundation5import ConvertCore6import ConvertKit78// MARK: - formats910enum FormatsCommand: Command {11 static let spec = CommandSpec("formats", summary: "Formats with at least one real conversion path.",12 usage: "formats [--category <category>] [--json]", flags: ["json"], options: ["category"])1314 struct Row: Codable {15 let id: String, name: String, category: String, extensions: [String]16 let readable: Bool, writable: Bool17 let destinations: Int, sources: Int, operations: Int18 }1920 struct Output: Codable { let count: Int; let formats: [Row] }2122 static func rows(registry: FormatRegistry, category: FormatCategory?) -> [Row] {23 let sources = Set(registry.sourceFormats), destinations = Set(registry.destinationFormats)24 return FormatCatalog.all.filter { format in25 (sources.contains(format.id) || destinations.contains(format.id)) && (category == nil || format.category == category)26 }.map { format in27 Row(id: format.id.rawValue, name: format.name, category: format.category.rawValue, extensions: format.extensions,28 readable: sources.contains(format.id), writable: destinations.contains(format.id),29 destinations: registry.destinations(for: format.id, includingOperations: true).count,30 sources: Set(registry.paths(to: format.id).map(\.source)).count,31 operations: Set(registry.operations(for: format.id).compactMap(\.operation)).count)32 }33 }3435 static func run(_ arguments: ParsedArguments, io: CommandIO) async throws -> ExitCode {36 let category = try arguments.value("category").map(Shared.category)37 let rows = rows(registry: Shared.registry(), category: category)38 if arguments.flag("json") {39 io.out(try Shared.json(Output(count: rows.count, formats: rows)))40 } else {41 let table = Shared.table(["FORMAT", "NAME", "CATEGORY", "EXTENSIONS", "READ", "WRITE", "TO", "FROM", "OPS"], rows.map {42 [$0.id, $0.name, $0.category, $0.extensions.joined(separator: " "), $0.readable ? "yes" : "—", $0.writable ? "yes" : "—",43 String($0.destinations), String($0.sources), String($0.operations)]44 })45 table.forEach(io.out)46 io.out("")47 io.out("\(rows.count) format(s) with at least one path. TO = destinations reachable from the format, FROM = sources that can become it.")48 }49 return .success50 }51}5253// MARK: - paths5455enum PathsCommand: Command {56 static let spec = CommandSpec("paths", summary: "The capability matrix: every declared conversion path.",57 usage: "paths [--from <format>] [--to <format>] [--engine <id>] [--operation <op>] [--json]",58 flags: ["json"], options: ["from", "to", "engine", "operation"])5960 struct Row: Codable {61 let source: String, destination: String, operation: String?, title: String?, engine: String, status: String62 let fidelity: String, preserves: [String], limitations: [String], acceptsMultipleSources: Bool63 }6465 struct Output: Codable { let count: Int; let paths: [Row]; let unavailable: [Unavailable] }66 struct Unavailable: Codable { let engine: String; let reason: String; let paths: Int }6768 static func row(_ path: ConversionPath) -> Row {69 Row(source: path.source.rawValue, destination: path.destination.rawValue, operation: path.operation, title: path.title,70 engine: path.engine, status: path.status.rawValue, fidelity: path.fidelity.rawValue,71 preserves: path.preserves.map(\.rawValue).sorted(), limitations: path.limitations, acceptsMultipleSources: path.acceptsMultipleSources)72 }7374 static func run(_ arguments: ParsedArguments, io: CommandIO) async throws -> ExitCode {75 let registry = Shared.registry()76 let from = try arguments.value("from").map { try Shared.format($0, option: "--from") }77 let to = try arguments.value("to").map { try Shared.format($0, option: "--to") }78 if let engine = arguments.value("engine"), registry.engine(id: engine) == nil {79 throw UsageError("--engine: no engine '\(engine)'. Engines: \(registry.engines.map(\.id).joined(separator: ", ")).")80 }81 var paths = registry.paths(from: from, to: to, engine: arguments.value("engine"))82 if let operation = arguments.value("operation") { paths = paths.filter { $0.operation == operation } }83 if arguments.flag("json") {84 let missing = registry.unavailableEngines.map { Unavailable(engine: $0.id, reason: $0.reason, paths: $0.paths.count) }85 io.out(try Shared.json(Output(count: paths.count, paths: paths.map(row), unavailable: missing)))86 } else {87 Shared.table(["SOURCE", "DESTINATION", "OPERATION", "ENGINE", "STATUS", "FIDELITY", "PRESERVES"], paths.map {88 [$0.source.rawValue, $0.destination.rawValue, $0.operation ?? "—", $0.engine, $0.status.rawValue, $0.fidelity.rawValue,89 $0.preserves.isEmpty ? "—" : $0.preserves.map(\.rawValue).sorted().joined(separator: ",")]90 }).forEach(io.out)91 io.out("")92 io.out("\(paths.count) path(s).")93 for engine in registry.unavailableEngines {94 io.out("Engine '\(engine.id)' is unavailable (\(engine.reason)): \(engine.paths.count) path(s) not listed.")95 }96 }97 return .success98 }99}100101// MARK: - detect102103enum DetectCommand: Command {104 static let spec = CommandSpec("detect", summary: "Identify files from their content.", usage: "detect <files…> [--json]",105 flags: ["json"], minPositionals: 1, unbounded: true)106107 struct Row: Codable {108 let path: String109 let format: String?, formatName: String?, category: String?110 let confidence: String, evidence: String, mismatch: Bool111 let fileExtension: String, extensionFormats: [String], textEncoding: String?, isDirectory: Bool112 }113114 static func row(_ url: URL) -> Row {115 let d = FileTypeDetector.detect(url)116 return Row(path: url.path, format: d.format?.rawValue, formatName: d.fileFormat?.name, category: d.category?.rawValue,117 confidence: d.confidence.rawValue, evidence: d.evidence, mismatch: d.mismatch, fileExtension: d.fileExtension,118 extensionFormats: d.extensionFormats.map(\.rawValue), textEncoding: d.textEncoding?.rawValue, isDirectory: d.isDirectory)119 }120121 static func run(_ arguments: ParsedArguments, io: CommandIO) async throws -> ExitCode {122 let urls = arguments.positionals.map(Shared.fileURL)123 let rows = urls.map(row)124 let missing = urls.filter { !FileManager.default.fileExists(atPath: $0.path) }125 if arguments.flag("json") {126 io.out(try Shared.json(rows))127 } else {128 for row in rows {129 let name = (row.path as NSString).lastPathComponent130 let what = row.format.map { "\($0) (\(row.formatName ?? $0))" } ?? "unknown"131 io.out("\(name): \(what) — \(row.confidence) — \(row.evidence)" + (row.mismatch ? " — MISMATCH: the name says .\(row.fileExtension)" : ""))132 }133 }134 for url in missing { io.err("orix-convert: \(url.path) does not exist.") }135 if !missing.isEmpty { return .inputError }136 return rows.contains { $0.format == nil } ? .inputError : .success137 }138}139140// MARK: - inspect141142enum InspectCommand: Command {143 static let spec = CommandSpec("inspect", summary: "Metadata of a file, read by the engine that knows its format.",144 usage: "inspect <file> [--json]", flags: ["json"], positionals: 1...1)145146 struct Output: Codable {147 let path: String148 let detection: DetectCommand.Row149 let engine: String?150 let engineError: String?151 let inspection: FileInspection152 }153154 static func run(_ arguments: ParsedArguments, io: CommandIO) async throws -> ExitCode {155 let url = Shared.fileURL(arguments.positionals[0])156 guard FileManager.default.fileExists(atPath: url.path) else { throw CommandFailure(.inputError, "\(url.path) does not exist.") }157 let inspected = await FileInspector(registry: Shared.registry()).inspect(url)158 if arguments.flag("json") {159 io.out(try Shared.json(Output(path: url.path, detection: DetectCommand.row(url), engine: inspected.engineID,160 engineError: inspected.engineError, inspection: inspected.inspection)))161 } else {162 io.out(url.lastPathComponent)163 var group = ""164 for field in inspected.inspection.fields {165 if field.group != group { group = field.group; io.out(""); io.out(group) }166 io.out(" " + field.key.padding(toLength: 26, withPad: " ", startingAt: 0) + " " + field.value)167 }168 if !inspected.inspection.notes.isEmpty {169 io.out(""); io.out("Notes")170 inspected.inspection.notes.forEach { io.out(" " + $0) }171 }172 io.out("")173 if let engine = inspected.engineID {174 io.out("Read by engine '\(engine)'.")175 } else if let error = inspected.engineError {176 io.out("The engine could not read the file: \(error)")177 } else {178 io.out("No engine inspects this format; only the generic file facts are shown.")179 }180 }181 if inspected.detection.format == nil { return .inputError }182 return inspected.engineError == nil ? .success : .conversionFailed183 }184}185186// MARK: - plan187188enum PlanCommand: Command {189 static let spec = CommandSpec("plan", summary: "Show how a file would be converted, before converting it.",190 usage: "plan <file> --to <format> [--operation <op>] [--engine <id>] [--option key=value …] [--json]",191 flags: ["json"], options: ["to", "operation", "engine"], repeated: ["option"], positionals: 1...1)192193 struct Step: Codable {194 let source: String, destination: String, operation: String?, engine: String, status: String, fidelity: String195 }196197 struct Output: Codable {198 let path: String199 let sourceFormat: String200 let detection: DetectCommand.Row201 let destinationFormat: String202 let operation: String?203 let chained: Bool204 let steps: [Step]205 let status: String, fidelity: String206 let preserves: [String]207 let limitations: [String]208 let warnings: [ConversionWarning]209 let heavy: Bool210 }211212 static func run(_ arguments: ParsedArguments, io: CommandIO) async throws -> ExitCode {213 guard let toRaw = arguments.value("to") else { throw UsageError("plan needs --to <format>.") }214 let destination = try Shared.format(toRaw, option: "--to")215 let url = Shared.fileURL(arguments.positionals[0])216 guard FileManager.default.fileExists(atPath: url.path) else { throw CommandFailure(.inputError, "\(url.path) does not exist.") }217 let registry = Shared.registry()218 let detection = FileTypeDetector.detect(url)219 guard let source = detection.format else {220 throw CommandFailure(.inputError, "The format of \(url.lastPathComponent) could not be recognised (\(detection.evidence)).")221 }222 let operation = arguments.value("operation")223 let plan: ConversionPlan224 do {225 plan = try ConversionPlanner(registry: registry).plan(from: source, to: destination, operation: operation, engine: arguments.value("engine"))226 } catch let error as ConversionError {227 throw CommandFailure(.unsupported, CLI.describe(error) + Self.hint(registry: registry, source: source, destination: destination, operation: operation))228 }229 var warnings: [ConversionWarning] = []230 if detection.mismatch {231 warnings.append(ConversionWarning(.caution, code: "extension-mismatch",232 "The name says .\(detection.fileExtension) but the content is \(source.rawValue.uppercased()); it is converted as \(source.rawValue.uppercased())."))233 }234 var inspection: FileInspection?235 if let inspector = registry.inspector(for: source) { inspection = try? await inspector.inspect(url, format: source) }236 if let first = plan.steps.first, let engine = registry.engine(id: first.engine) {237 let isLast = plan.steps.count == 1238 let options = isLast ? try OptionParsing.options(arguments.all("option"), descriptors: engine.options(for: first), io: io, strict: false) : ConversionOptions()239 let request = ConversionRequest(source: url, sourceFormat: first.source, destinationFormat: first.destination, operation: first.operation, options: options)240 warnings += engine.preflight(request, inspection: inspection)241 }242 let heavy = plan.engines.contains(where: ORIXEngines.heavyEngineIDs.contains)243 || [source, destination].contains { FormatCatalog.format($0)?.category == .video }244 if arguments.flag("json") {245 io.out(try Shared.json(Output(246 path: url.path, sourceFormat: source.rawValue, detection: DetectCommand.row(url), destinationFormat: destination.rawValue,247 operation: operation, chained: plan.isChained,248 steps: plan.steps.map { Step(source: $0.source.rawValue, destination: $0.destination.rawValue, operation: $0.operation, engine: $0.engine, status: $0.status.rawValue, fidelity: $0.fidelity.rawValue) },249 status: plan.status.rawValue, fidelity: plan.fidelity.rawValue, preserves: plan.preserves.map(\.rawValue).sorted(),250 limitations: plan.limitations, warnings: warnings, heavy: heavy)))251 return .success252 }253 io.out("\(url.lastPathComponent): \(source.rawValue) (\(detection.confidence.rawValue): \(detection.evidence))")254 let route = ([plan.source] + plan.steps.map(\.destination)).map(\.rawValue).joined(separator: " → ")255 io.out("Plan: \(route)\(operation.map { " [\($0)]" } ?? "") — \(plan.isChained ? "chained, \(plan.steps.count) steps through an intermediate file" : "direct")")256 for (index, step) in plan.steps.enumerated() {257 io.out(" \(index + 1). \(step.source.rawValue) → \(step.destination.rawValue) with engine '\(step.engine)' — \(step.status.rawValue), \(step.fidelity.rawValue)")258 }259 io.out("Fidelity: \(plan.fidelity.rawValue) Status: \(plan.status.rawValue)" + (heavy ? " Heavy job (limited concurrency)" : ""))260 io.out("Preserves: " + (plan.preserves.isEmpty ? "—" : plan.preserves.map(\.rawValue).sorted().joined(separator: ", ")))261 if plan.limitations.isEmpty {262 io.out("Limitations: none declared.")263 } else {264 io.out("Limitations:")265 plan.limitations.forEach { io.out(" - \($0)") }266 }267 if warnings.isEmpty {268 io.out("Preflight warnings for this file: none.")269 } else {270 io.out("Preflight warnings for this file:")271 warnings.forEach { io.out(" - [\($0.severity.rawValue)] \($0.code): \($0.message)") }272 }273 return .success274 }275276 /// What is possible instead, when the asked conversion is not.277 static func hint(registry: FormatRegistry, source: FormatID, destination: FormatID, operation: String?) -> String {278 let capabilities = ConversionCapabilityResolver(registry: registry).capabilities(for: source)279 if !capabilities.isSupported { return " No engine reads \(source.rawValue)." }280 if let operation, !capabilities.operations.contains(where: { $0.operation == operation }) {281 let known = Set(capabilities.operations.compactMap(\.operation)).sorted()282 return known.isEmpty ? " \(source.rawValue) has no named operation." : " Operations for \(source.rawValue): \(known.joined(separator: ", "))."283 }284 let direct = capabilities.targets.map(\.destination.rawValue)285 return " \(source.rawValue) converts to: \(direct.isEmpty ? "nothing directly" : direct.joined(separator: ", "))."286 }287}288289// MARK: - options290291enum OptionsCommand: Command {292 static let spec = CommandSpec("options", summary: "Settings offered by a conversion path.",293 usage: "options --from <format> --to <format> [--operation <op>] [--engine <id>] [--json]",294 flags: ["json"], options: ["from", "to", "operation", "engine"])295296 struct Choice: Codable { let value: String; let label: String }297298 struct Row: Codable {299 let key: String, label: String, group: String, type: String300 let defaultValue: String301 let minimum: Double?, maximum: Double?, step: Double?, unit: String?302 let choices: [Choice]?303 let placeholder: String?304 let help: String?305 let advanced: Bool, secret: Bool306 }307308 struct Output: Codable {309 let source: String, destination: String, operation: String?, engine: String310 let chained: Bool311 let note: String?312 let options: [Row]313 }314315 static func row(_ d: OptionDescriptor) -> Row {316 var type = "", minimum: Double?, maximum: Double?, step: Double?, unit: String?, choices: [Choice]?, placeholder: String?317 switch d.kind {318 case .toggle: type = "bool"319 case .integer(_, let range, let u): type = "integer"; minimum = Double(range.lowerBound); maximum = Double(range.upperBound); unit = u320 case .number(_, let range, let s, let u): type = "number"; minimum = range.lowerBound; maximum = range.upperBound; step = s; unit = u321 case .choice(_, let list): type = "choice"; choices = list.map { Choice(value: $0.value, label: $0.label) }322 case .text(_, let p): type = "text"; placeholder = p.isEmpty ? nil : p323 }324 return Row(key: d.id, label: d.label, group: d.group, type: type, defaultValue: Shared.optionValueText(d.defaultValue),325 minimum: minimum, maximum: maximum, step: step, unit: unit, choices: choices, placeholder: placeholder, help: d.help,326 advanced: d.advanced, secret: ConversionOptions.isSecretKey(d.id))327 }328329 static func run(_ arguments: ParsedArguments, io: CommandIO) async throws -> ExitCode {330 guard let fromRaw = arguments.value("from"), let toRaw = arguments.value("to") else { throw UsageError("options needs --from <format> and --to <format>.") }331 let source = try Shared.format(fromRaw, option: "--from"), destination = try Shared.format(toRaw, option: "--to")332 let registry = Shared.registry()333 let plan: ConversionPlan334 do {335 plan = try ConversionPlanner(registry: registry).plan(from: source, to: destination, operation: arguments.value("operation"), engine: arguments.value("engine"))336 } catch let error as ConversionError {337 throw CommandFailure(.unsupported, CLI.describe(error) + PlanCommand.hint(registry: registry, source: source, destination: destination, operation: arguments.value("operation")))338 }339 guard let last = plan.steps.last, let engine = registry.engine(id: last.engine) else { throw CommandFailure(.unsupported, "No engine for this path.") }340 let rows = engine.options(for: last).map(row)341 let note = plan.isChained342 ? "Chained plan (\(([plan.source] + plan.steps.map(\.destination)).map(\.rawValue).joined(separator: " → "))): options apply to the last step; the first step runs with its defaults."343 : nil344 if arguments.flag("json") {345 io.out(try Shared.json(Output(source: source.rawValue, destination: destination.rawValue, operation: last.operation, engine: engine.id,346 chained: plan.isChained, note: note, options: rows)))347 return .success348 }349 io.out("\(last.source.rawValue) → \(last.destination.rawValue)\(last.operation.map { " [\($0)]" } ?? "") — engine '\(engine.id)'")350 if let note { io.out(note) }351 if rows.isEmpty { io.out("This path has no setting."); return .success }352 io.out("")353 for row in rows {354 var range = ""355 if let lo = row.minimum, let hi = row.maximum {356 let f: (Double) -> String = { row.type == "integer" ? String(Int($0)) : String($0) }357 range = " \(f(lo))…\(f(hi))" + (row.unit.map { " \($0)" } ?? "")358 }359 if let choices = row.choices { range = " {" + choices.map(\.value).joined(separator: "|") + "}" }360 io.out("--option \(row.key)=<\(row.type)\(range)> default: \(row.defaultValue.isEmpty ? "(empty)" : row.defaultValue)" + (row.advanced ? " [advanced]" : "") + (row.secret ? " [secret: use @env:VAR or @stdin]" : ""))361 io.out(" \(row.group) · \(row.label)" + (row.help.map { " — \($0)" } ?? ""))362 }363 return .success364 }365}366367// MARK: - presets368369enum PresetsCommand: Command {370 static let spec = CommandSpec("presets", summary: "Saved presets (the file shared with the app).", usage: "presets list [--json]",371 flags: ["json"], positionals: 1...1)372373 struct Row: Codable {374 let id: String, name: String, summary: String, appliesTo: String, destination: String, operation: String?375 let options: [String: String]376 let builtIn: Bool377 }378379 struct Output: Codable { let file: String; let loadError: String?; let presets: [Row] }380381 static func run(_ arguments: ParsedArguments, io: CommandIO) async throws -> ExitCode {382 guard arguments.positionals[0] == "list" else { throw UsageError("presets: unknown action '\(arguments.positionals[0])'. Usage: orix-convert presets list") }383 let store = PresetStore()384 let all = await store.all385 let loadError = await store.loadError386 let rows = all.map { preset -> Row in387 let scope: String388 switch preset.source {389 case .any: scope = "any"390 case .category(let c): scope = "category:\(c.rawValue)"391 case .format(let f): scope = f.rawValue392 }393 return Row(id: preset.id.uuidString, name: preset.name, summary: preset.summary, appliesTo: scope, destination: preset.destinationFormat.rawValue,394 operation: preset.operation, options: preset.options.redactingSecrets().values.mapValues(Shared.optionValueText), builtIn: preset.isBuiltIn)395 }396 if arguments.flag("json") {397 io.out(try Shared.json(Output(file: store.fileURL.path, loadError: loadError, presets: rows)))398 } else {399 if rows.isEmpty {400 io.out("No preset saved in \(store.fileURL.path).")401 io.out("Built-in presets belong to the app (it registers them at start-up); the command-line tool lists the user's saved presets.")402 } else {403 Shared.table(["NAME", "APPLIES TO", "DESTINATION", "OPERATION", "OPTIONS"], rows.map {404 [$0.name, $0.appliesTo, $0.destination, $0.operation ?? "—", $0.options.sorted { $0.key < $1.key }.map { "\($0.key)=\($0.value)" }.joined(separator: " ")]405 }).forEach(io.out)406 }407 if let loadError { io.err("orix-convert: the preset file could not be read: \(loadError)") }408 }409 return loadError == nil ? .success : .checkFailed410 }411}412