mas/MasKit/ExternalCommands/ExternalCommand.swift

71 lines
1.6 KiB
Swift
Raw Normal View History

2019-01-02 22:53:21 -08:00
//
// ExternalCommand.swift
// MasKit
//
// Created by Ben Chatelain on 1/1/19.
// Copyright © 2019 mas-cli. All rights reserved.
//
import Foundation
2019-01-02 22:53:21 -08:00
/// CLI command
public protocol ExternalCommand {
var binaryPath: String { get set }
var process: Process { get }
var stdout: String { get }
var stderr: String { get }
2019-01-02 22:53:21 -08:00
var stdoutPipe: Pipe { get }
var stderrPipe: Pipe { get }
2021-04-14 15:03:10 -07:00
var exitCode: Int32 { get }
2019-01-02 22:53:21 -08:00
var succeeded: Bool { get }
var failed: Bool { get }
/// Runs the command.
func run(arguments: String...) throws
2019-01-02 22:53:21 -08:00
}
/// Common implementation
extension ExternalCommand {
2019-01-11 18:06:02 -07:00
public var stdout: String {
2019-01-02 22:53:21 -08:00
let data = stdoutPipe.fileHandleForReading.readDataToEndOfFile()
return String(data: data, encoding: .utf8) ?? ""
2019-01-11 18:06:02 -07:00
}
2019-01-02 22:53:21 -08:00
2019-01-11 18:06:02 -07:00
public var stderr: String {
2019-01-02 22:53:21 -08:00
let data = stderrPipe.fileHandleForReading.readDataToEndOfFile()
return String(data: data, encoding: .utf8) ?? ""
2019-01-11 18:06:02 -07:00
}
2019-01-02 22:53:21 -08:00
2021-04-14 15:03:10 -07:00
public var exitCode: Int32 {
process.terminationStatus
2019-01-11 18:06:02 -07:00
}
2019-01-02 22:53:21 -08:00
2019-01-11 18:06:02 -07:00
public var succeeded: Bool {
2021-04-14 15:03:10 -07:00
process.terminationReason == .exit && exitCode == 0
2019-01-11 18:06:02 -07:00
}
2019-01-02 22:53:21 -08:00
2019-01-11 18:06:02 -07:00
public var failed: Bool {
2021-03-21 22:46:17 -07:00
!succeeded
2019-01-11 18:06:02 -07:00
}
2019-01-02 22:53:21 -08:00
/// Runs the command.
public func run(arguments: String...) throws {
2019-01-02 22:53:21 -08:00
process.standardOutput = stdoutPipe
process.standardError = stderrPipe
process.arguments = arguments
2021-04-14 15:03:10 -07:00
if #available(macOS 10.13, *) {
2019-01-02 22:53:21 -08:00
process.executableURL = URL(fileURLWithPath: binaryPath)
2021-04-14 15:03:10 -07:00
try process.run()
2019-01-02 22:53:21 -08:00
} else {
process.launchPath = binaryPath
process.launch()
}
process.waitUntilExit()
}
}