Skip to content

Commit

Permalink
Themes with colors generated by clrex
Browse files Browse the repository at this point in the history
  • Loading branch information
ilyapuchka committed Jan 2, 2016
1 parent f1ffbd5 commit 705dc3a
Show file tree
Hide file tree
Showing 7 changed files with 388 additions and 33 deletions.
302 changes: 302 additions & 0 deletions Scripts/clrex.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,302 @@
#!/usr/bin/env swift

/*
The MIT License (MIT)
Copyright (c) 2016 Ilya Puchka
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

import Cocoa
import AppKit.NSColor

let description = "clrex generates UIColor factory methods from clr files. By default will lookup ~/Library/Colors folder and will generate file Colors.generated.swift in current folder."
let usage = "Usage: clrex [-i PATH_TO_CLR_FILES_DIR] [-o PATH_TO_OUTPUT_FILE] [-p ios|osx]"
let example = "Example: clrex -i ~/Library/Colors/ -o ./Colors.swift -p osx"
let note = "// This is a generated file, do not edit!\n// Generated by clrex, see https://github.com/ilyapuchka/clrex"

print(description, usage, example, separator: "\n")

//MARK: - Code generation

class NamedColor {
let name: String
let color: NSColor

init(name: String, color: NSColor) {
self.name = name
self.color = color
}

init(key: String, color: NSColor) {
self.name = colorNameForKey(key)
self.color = color
}

func toTemplate(platform: Platform) -> String {
return String(format: platform.methodTemplate, name, color.toTemplate(platform))
}

}

extension NSColor {

func toTemplate(platform: Platform) -> String {
return String(format: platform.valueTemplate, redComponent, greenComponent, blueComponent, alphaComponent)
}

}

extension NSColorList {

func toTemplate(platform: Platform) -> String {
return String(format: platform.namespaceTemplate, name!, allNamedColors.toTemplate(platform))
}

}

extension Array where Element: NSColorList {

func toTemplate(platform: Platform) -> String {
return note + self
.map({ $0.toTemplate(platform) })
.reduce(platform.importTemplate, combine: +)
}

}

extension Array where Element: NamedColor {
func toTemplate(platform: Platform) -> String {
return self
.map({ $0.toTemplate(platform) })
.reduce("", combine: +)
}
}

//MARK: - Helpers

extension NSColor {

var rgbColor: NSColor? {
return colorUsingColorSpaceName(NSCalibratedRGBColorSpace)
}

}

extension NSColorList {

var allNamedColors: [NamedColor] {
return allKeys.flatMap(self.namedColorWithKey)
}

func namedColorWithKey(key: String) -> NamedColor? {
return colorWithKey(key)?.rgbColor.map({ NamedColor(key: key, color: $0) })
}

convenience init?(filePath: String) {
guard isColorListFile(filePath) else { return nil }

let listName = filePath.nsString.lastPathComponent.nsString.stringByDeletingPathExtension
self.init(name: listName, fromFile: filePath)
}

}

func colorNameForKey(key: String) -> String {
let suffix = "Color"
var name = key
.stringByReplacingOccurrencesOfString(" ", withString: "")
.firstLetterLowercasedString
.stringByReplacingOccurrencesOfString("color", withString: suffix)

if !name.hasSuffix(suffix) {
name += suffix
}
return name
}

func isColorListFile(fileName: String) -> Bool {
return fileName.nsString.pathExtension.lowercaseString == "clr"
}

extension NSFileManager {

func fullContentsPathsOfDirectoryAtPath(path: String) throws -> [String] {
return try contentsOfDirectoryAtPath(path).map(path.nsString.stringByAppendingPathComponent)
}

func colorListsAtPath(path: String) throws -> [NSColorList] {
return try fullContentsPathsOfDirectoryAtPath(path).flatMap(NSColorList.init)
}

}

extension CollectionType where Index: Comparable {
subscript(safe index: Index) -> Generator.Element? {
guard index >= startIndex && index < endIndex else { return nil }
return self[index]
}

}

extension CollectionType where Generator.Element: Equatable, Index: Comparable {
subscript(next element: Generator.Element) -> Generator.Element? {
guard let index = self.indexOf(element) else { return nil }
return self[safe: index.advancedBy(1)]
}
}

extension String {
var nsString: NSString { return self as NSString }

var firstLetterLowercasedString: String {
guard !isEmpty else { return self }
return String(self[startIndex]).lowercaseString + self[startIndex.advancedBy(1)..<endIndex]
}
}

//MARK: - Templates

protocol Template {
var module: String { get }
var type: String { get }
var value: String { get }
}

struct OSX: Template {
let module = "AppKit"
let type = "NSColor"
let value = "NSColor(calibratedRed: %f, green: %f, blue: %f, alpha: %f)"
}

struct iOS: Template {
let module = "UIKit"
let type = "UIColor"
let value = "UIColor(red: %f, green: %f, blue: %f, alpha: %f)"
}

enum Platform: String {
case osx
case ios

var template: Template {
switch self {
case .osx: return OSX()
case .ios: return iOS()
}
}

var importTemplate: String {
return "\n\nimport \(template.module)\n\n"
}

var methodTemplate: String {
return " static func %@() -> \(template.type) {\n return %@\n }\n\n"
}

var valueTemplate: String {
return template.value
}

var namespaceTemplate: String {
return "enum %@ {\n\n%@}\n"
}
}

//MARK: - Input arguments

extension Process {

static var info: NSProcessInfo {
return NSProcessInfo.processInfo()
}

static var scriptInputFilesCount: Int {
return info.environment["SCRIPT_INPUT_FILE_COUNT"].flatMap({Int($0)}) ?? 0
}

static var scriptInputFiles: [String] {
return (0..<scriptInputFilesCount).flatMap(scriptInputFile)
}

static func scriptInputFile(i: Int) -> String? {
return info.environment["SCRIPT_INPUT_FILE_\(i)"]
}

static var scriptOutputFilesCount: Int {
return info.environment["SCRIPT_OUTPUT_FILE_COUNT"].flatMap({Int($0)}) ?? 0
}

static var scriptOutputFiles: [String] {
return (0..<scriptOutputFilesCount).flatMap(scriptOutputFile)
}

static func scriptOutputFile(i: Int) -> String? {
return info.environment["SCRIPT_OUTPUT_FILE_\(i)"]
}

static func platform() -> Platform {
return info.environment["PLATFORM_NAME"] == "macosx" ? .osx : .ios
}

static var argInput: String? {
return Process.arguments[next: "-i"]
}

static var argOutput: String? {
return Process.arguments[next: "-o"]
}

static var argPlatform: String? {
return Process.arguments[next: "-p"]
}

}

//MARK: - Main

func systemColorsPath() -> String {
guard let libraryDir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.LibraryDirectory, NSSearchPathDomainMask.UserDomainMask, true).first else {
fatalError("Failed to locate ~/Library")
}

return libraryDir.nsString.stringByAppendingPathComponent("Colors")
}

let colorsPath = Process.argInput ?? Process.scriptInputFiles.first ?? systemColorsPath()
let destinationPath = Process.argOutput ?? Process.scriptOutputFiles.first ?? "Colors.generated.swift"
let platform = Process.argPlatform.flatMap(Platform.init) ?? Process.platform() ?? Platform.ios

do {
let fm = NSFileManager.defaultManager()
print("Reading from \(colorsPath)")
let lists = try fm.colorListsAtPath(colorsPath)
print("Found palettes: \(lists.count)")
if !lists.isEmpty {
let content = lists.toTemplate(platform)
print("Writing to \(destinationPath)")
try content.writeToFile(destinationPath, atomically: true, encoding: NSUTF8StringEncoding)
}
}
catch {
fatalError(String(error))
}


Loading

0 comments on commit 705dc3a

Please sign in to comment.