Created
May 15, 2016 05:09
-
-
Save loganwright/899acec46512a966653206f5dcc27d2a to your computer and use it in GitHub Desktop.
Template for setting up swift scripts
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
#!/usr/bin/env swift | |
#if os(OSX) | |
import Darwin | |
#else | |
import Glibc | |
#endif | |
import Foundation | |
// MARK: Failure | |
@noreturn func fail(_ msg: String) { | |
print("Error: \(msg)") | |
exit(1) | |
} | |
func run(_ command: String, allowFailure: Bool = false) { | |
let result = system(command) | |
if allowFailure { return } | |
else if result != 0 { | |
fail("error code \(result)") | |
} | |
} | |
func passes(_ command: String) -> Bool { | |
return system(command) == 0 | |
} | |
func getInput() -> String { | |
return readLine(strippingNewline: true) ?? "" | |
} | |
func commandExists(_ command: String) -> Bool { | |
return system("hash \(command) 2>/dev/null") == 0 | |
} | |
// MARK: Command | |
protocol Command { | |
static var description: String { get } | |
static func execute(with args: [String], in directory: String) | |
} | |
extension Command { | |
static var description: String { | |
return "" | |
} | |
} | |
// MARK: Tree | |
var commandTree: [String : Command.Type] = [:] | |
// MARK: Help | |
struct Help: Command { | |
static func execute(with args: [String], in directory: String) { | |
var help = "Available Commands:\n\n" | |
help += commandTree | |
.map { key, val in "\t\(key): \(val.description)"} | |
.joined(separator: "\n") | |
help += "\n" | |
print(help) | |
} | |
} | |
commandTree["help"] = Help.self | |
// MARK: Custom Commands | |
// ... define custom Command types and add to commandTree here | |
// MARK: Execution | |
var iterator = Process.arguments.makeIterator() | |
guard let directory = iterator.next() else { | |
fail("no directory") | |
} | |
guard let commandKey = iterator.next() else { | |
fail("no command") | |
} | |
guard let command = commandTree[commandKey] else { | |
fail("command \(commandKey) doesn't exist") | |
} | |
let arguments = Array(iterator) | |
command.execute(with: arguments, in: directory) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment