2019-01-03 06:53:21 +00:00
|
|
|
//
|
|
|
|
// ExternalCommand.swift
|
|
|
|
// MasKit
|
|
|
|
//
|
|
|
|
// Created by Ben Chatelain on 1/1/19.
|
|
|
|
// Copyright © 2019 mas-cli. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
/// CLI command
|
|
|
|
public protocol ExternalCommand {
|
|
|
|
var binaryPath: String { get set }
|
|
|
|
|
|
|
|
var process: Process { get }
|
|
|
|
|
2019-01-03 07:16:45 +00:00
|
|
|
var stdout: String { get }
|
|
|
|
var stderr: String { get }
|
2019-01-03 06:53:21 +00:00
|
|
|
var stdoutPipe: Pipe { get }
|
|
|
|
var stderrPipe: Pipe { get }
|
|
|
|
|
|
|
|
var exitCode: Int? { get }
|
|
|
|
var succeeded: Bool { get }
|
|
|
|
var failed: Bool { get }
|
|
|
|
|
|
|
|
/// Runs the command.
|
2019-01-04 00:30:56 +00:00
|
|
|
func run(arguments: String...) throws
|
2019-01-03 06:53:21 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// Common implementation
|
|
|
|
extension ExternalCommand {
|
2019-01-03 07:16:45 +00:00
|
|
|
public var stdout: String { get {
|
2019-01-03 06:53:21 +00:00
|
|
|
let data = stdoutPipe.fileHandleForReading.readDataToEndOfFile()
|
2019-01-03 07:16:45 +00:00
|
|
|
return String(data: data, encoding: .utf8) ?? ""
|
2019-01-03 06:53:21 +00:00
|
|
|
}}
|
|
|
|
|
2019-01-03 07:16:45 +00:00
|
|
|
public var stderr: String { get {
|
2019-01-03 06:53:21 +00:00
|
|
|
let data = stderrPipe.fileHandleForReading.readDataToEndOfFile()
|
2019-01-03 07:16:45 +00:00
|
|
|
return String(data: data, encoding: .utf8) ?? ""
|
2019-01-03 06:53:21 +00:00
|
|
|
}}
|
|
|
|
|
|
|
|
public var exitCode: Int? { get {
|
|
|
|
return Int(process.terminationStatus)
|
|
|
|
}}
|
|
|
|
|
|
|
|
public var succeeded: Bool { get {
|
|
|
|
return exitCode == 0
|
|
|
|
}}
|
|
|
|
|
|
|
|
public var failed: Bool { get {
|
|
|
|
return !succeeded
|
|
|
|
}}
|
|
|
|
|
|
|
|
/// Runs the command.
|
2019-01-04 00:30:56 +00:00
|
|
|
public func run(arguments: String...) throws {
|
2019-01-03 06:53:21 +00:00
|
|
|
process.standardOutput = stdoutPipe
|
|
|
|
process.standardError = stderrPipe
|
|
|
|
process.arguments = arguments
|
|
|
|
|
|
|
|
if #available(OSX 10.13, *) {
|
|
|
|
process.executableURL = URL(fileURLWithPath: binaryPath)
|
|
|
|
do {
|
|
|
|
try process.run()
|
|
|
|
} catch {
|
|
|
|
printError("Unable to launch command")
|
|
|
|
//return throw Error()
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
process.launchPath = binaryPath
|
|
|
|
process.launch()
|
|
|
|
}
|
|
|
|
|
|
|
|
process.waitUntilExit()
|
|
|
|
}
|
|
|
|
}
|