Make importer protocol.

This commit is contained in:
Sven Weidauer 2022-10-08 11:03:28 +02:00
parent e6f44f5be2
commit e28bee804f
4 changed files with 45 additions and 26 deletions

View file

@ -0,0 +1,5 @@
protocol Importer {
init(source: String) throws
func read() throws -> [String: ColorDef]
}

View file

@ -0,0 +1,36 @@
import Foundation
struct ListImporter: Importer {
let input: String
init(source: String) {
input = source
}
func read() throws -> [String: ColorDef] {
let scanner = Scanner(string: try readInput())
scanner.charactersToBeSkipped = .whitespaces
return try scanner.colorList()
}
func readInput() throws -> String {
if input == "-" {
return try readStdin()
}
let url = URL(fileURLWithPath: input)
return try String(contentsOf: url)
}
func readStdin() throws -> String {
guard
let data = try FileHandle.standardInput.readToEnd(),
let input = String(data: data, encoding: .utf8)
else {
throw Errors.cannotReadStdin
}
return input
}
}

View file

@ -110,7 +110,7 @@ extension Scanner {
func colorLine() -> (String, ColorDef)? { func colorLine() -> (String, ColorDef)? {
guard guard
let name = self.name(), let name = name(),
let def = colorDef(), let def = colorDef(),
endOfLine() endOfLine()
else { else {
@ -168,7 +168,7 @@ extension Scanner {
func commaSeparated() -> [UInt8]? { func commaSeparated() -> [UInt8]? {
var result: [UInt8] = [] var result: [UInt8] = []
repeat { repeat {
guard let component = self.component() else { guard let component = component() else {
return nil return nil
} }
result.append(component) result.append(component)

View file

@ -66,10 +66,8 @@ public final class MakeColors: ParsableCommand, Context {
public init() {} public init() {}
public func run() throws { public func run() throws {
let scanner = Scanner(string: try readInput()) let importer = ListImporter(source: input)
scanner.charactersToBeSkipped = .whitespaces let data = try importer.read()
let data = try scanner.colorList()
if dump { if dump {
try dump(data: data) try dump(data: data)
@ -81,26 +79,6 @@ public final class MakeColors: ParsableCommand, Context {
try writeOutput(fileWrapper) try writeOutput(fileWrapper)
} }
func readInput() throws -> String {
if input == "-" {
return try readStdin()
}
let url = URL(fileURLWithPath: input)
return try String(contentsOf: url)
}
func readStdin() throws -> String {
guard
let data = try FileHandle.standardInput.readToEnd(),
let input = String(data: data, encoding: .utf8)
else {
throw Errors.cannotReadStdin
}
return input
}
func dump(data: [String: ColorDef]) throws { func dump(data: [String: ColorDef]) throws {
for (key, color) in data.sorted() { for (key, color) in data.sorted() {
let resolved = try data.resolve(key) let resolved = try data.resolve(key)