From dc00d87a32cd7ca9992b626faf4bb94edac50641 Mon Sep 17 00:00:00 2001 From: Sven Weidauer Date: Sat, 8 Oct 2022 11:20:00 +0200 Subject: [PATCH] Add option to select importer. --- .../LibMakeColors/Importers/Importer.swift | 8 +++++ Sources/LibMakeColors/MakeColors.swift | 34 ++++++++++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/Sources/LibMakeColors/Importers/Importer.swift b/Sources/LibMakeColors/Importers/Importer.swift index 7528edb..3fb9da2 100644 --- a/Sources/LibMakeColors/Importers/Importer.swift +++ b/Sources/LibMakeColors/Importers/Importer.swift @@ -2,4 +2,12 @@ protocol Importer { init(source: String) throws func read() throws -> [String: ColorDef] + + static var option: String { get } +} + +extension Importer { + static var option: String { + String(String(describing: self).droppingSuffix("Importer")) + } } diff --git a/Sources/LibMakeColors/MakeColors.swift b/Sources/LibMakeColors/MakeColors.swift index 810a7c8..cfe0fea 100644 --- a/Sources/LibMakeColors/MakeColors.swift +++ b/Sources/LibMakeColors/MakeColors.swift @@ -19,6 +19,35 @@ private struct GeneratorOption: EnumerableFlag, CustomStringConvertible { } } +private struct ImporterOption: CaseIterable, ExpressibleByArgument, CustomStringConvertible { + static let allCases: [ImporterOption] = [ + .list, + ] + + static let list = ImporterOption(type: ListImporter.self) + + let type: Importer.Type + + init(type: Importer.Type) { + self.type = type + } + + init?(argument: String) { + guard let found = Self.allCases.first(where: { $0.description.caseInsensitiveCompare(argument) == .orderedSame }) else { + return nil + } + self = found + } + + var description: String { + type.option + } + + static func == (lhs: ImporterOption, rhs: ImporterOption) -> Bool { + lhs.type == rhs.type + } +} + enum Errors: Error { case syntaxError case duplicateColor(String) @@ -54,6 +83,9 @@ public final class MakeColors: ParsableCommand, Context { @Flag(help: "The formatter to use.") private var formatter = GeneratorOption.allCases[0] + @Option(help: "The importer to use.") + private var importer = ImporterOption.list + @Option(help: "Prefix for color names.") var prefix: String? @@ -66,7 +98,7 @@ public final class MakeColors: ParsableCommand, Context { public init() {} public func run() throws { - let importer = ListImporter(source: input) + let importer = try importer.type.init(source: input) let data = try importer.read() if dump {