Last active
December 25, 2022 14:58
-
-
Save kean/d0c102aa6cfd06b25cf16c09923de1e9 to your computer and use it in GitHub Desktop.
Converts UIColor init to a color literal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
/// Input: | |
/// | |
/// public static let purple = UIColor(red: 74/255, green: 21/255, blue: 153/255, alpha: 1.0) | |
/// | |
/// Output: | |
/// | |
/// #4A1599 (74, 21, 153) | |
/// public static let purple = #colorLiteral(red: 0.2901960784, green: 0.0823529412, blue: 0.6, alpha: 1) | |
for argument in CommandLine.arguments.dropFirst() { | |
for line in argument.split(separator: "\n") where !line.isEmpty { | |
print(try convert(String(line))) | |
} | |
} | |
func convert(_ input: String) throws -> String { | |
let regex = /public static let (\w+) = UIColor\(red: (\d+).*?, green: (\d+).*?, blue: (\d+).*?\)/ | |
guard let (_, name, red, green, blue) = try regex.firstMatch(in: input)?.output else { | |
fatalError("Failed to match input") | |
} | |
guard let red = Int(red), let green = Int(green), let blue = Int(blue) else { | |
fatalError("Failed to parse color") | |
} | |
func render(_ color: Int) -> String { | |
(Double(color) / 255).formatted(.number.precision( | |
.integerAndFractionLength(integerLimits: 1...1, fractionLimits: 1...10) | |
)) | |
} | |
func hex(from value: Int) -> String { | |
String(format: "%02X", value) | |
} | |
let hex = "#\(hex(from: red))\(hex(from: green))\(hex(from: blue))" | |
return """ | |
/// \(hex) (\(red), \(green), \(blue)) | |
public static let \(name) = #colorLiteral(red: \(render(red)), green: \(render(green)), blue: \(render(blue)), alpha: 1) | |
""" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment