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.
|
|
|
|
//
|
|
|
|
|
2021-04-14 19:08:55 +00:00
|
|
|
import Foundation
|
|
|
|
|
2019-01-03 06:53:21 +00:00
|
|
|
/// CLI command
|
2021-04-22 01:05:36 +00:00
|
|
|
protocol ExternalCommand {
|
2019-01-03 06:53:21 +00:00
|
|
|
var binaryPath: String { get set }
|
|
|
|
|
|
|
|
var process: Process { get }
|
|
|
|
|
2019-01-03 07:16:45 +00:00
|
|
|
var stderr: String { get }
|
2019-01-03 06:53:21 +00:00
|
|
|
var stdoutPipe: Pipe { get }
|
|
|
|
var stderrPipe: Pipe { get }
|
|
|
|
|
2021-04-14 22:03:10 +00:00
|
|
|
var exitCode: Int32 { get }
|
2019-01-03 06:53:21 +00:00
|
|
|
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 {
|
2021-04-22 01:05:36 +00:00
|
|
|
var stderr: String {
|
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-12 01:06:02 +00:00
|
|
|
}
|
2019-01-03 06:53:21 +00:00
|
|
|
|
2021-04-22 01:05:36 +00:00
|
|
|
var exitCode: Int32 {
|
2021-04-14 22:03:10 +00:00
|
|
|
process.terminationStatus
|
2019-01-12 01:06:02 +00:00
|
|
|
}
|
2019-01-03 06:53:21 +00:00
|
|
|
|
2021-04-22 01:05:36 +00:00
|
|
|
var succeeded: Bool {
|
2021-04-14 22:03:10 +00:00
|
|
|
process.terminationReason == .exit && exitCode == 0
|
2019-01-12 01:06:02 +00:00
|
|
|
}
|
2019-01-03 06:53:21 +00:00
|
|
|
|
2021-04-22 01:05:36 +00:00
|
|
|
var failed: Bool {
|
2021-03-22 05:46:17 +00:00
|
|
|
!succeeded
|
2019-01-12 01:06:02 +00:00
|
|
|
}
|
2019-01-03 06:53:21 +00:00
|
|
|
|
|
|
|
/// Runs the command.
|
2021-04-22 01:05:36 +00:00
|
|
|
func run(arguments: String...) throws {
|
2019-01-03 06:53:21 +00:00
|
|
|
process.standardOutput = stdoutPipe
|
|
|
|
process.standardError = stderrPipe
|
|
|
|
process.arguments = arguments
|
|
|
|
|
2021-04-14 22:03:10 +00:00
|
|
|
if #available(macOS 10.13, *) {
|
2019-01-03 06:53:21 +00:00
|
|
|
process.executableURL = URL(fileURLWithPath: binaryPath)
|
2021-04-14 22:03:10 +00:00
|
|
|
try process.run()
|
2019-01-03 06:53:21 +00:00
|
|
|
} else {
|
|
|
|
process.launchPath = binaryPath
|
|
|
|
process.launch()
|
|
|
|
}
|
|
|
|
|
|
|
|
process.waitUntilExit()
|
|
|
|
}
|
|
|
|
}
|