mas/Sources/MasKit/ExternalCommands/ExternalCommand.swift

65 lines
1.4 KiB
Swift
Raw Normal View History

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.
//
import Foundation
2019-01-03 06:53:21 +00:00
/// CLI command
protocol ExternalCommand {
2019-01-03 06:53:21 +00:00
var binaryPath: String { get set }
var process: Process { get }
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.
func run(arguments: String...) throws
2019-01-03 06:53:21 +00:00
}
/// Common implementation
extension ExternalCommand {
var stderr: String {
2019-01-03 06:53:21 +00:00
let data = stderrPipe.fileHandleForReading.readDataToEndOfFile()
return String(data: data, encoding: .utf8) ?? ""
2019-01-12 01:06:02 +00:00
}
2019-01-03 06:53:21 +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
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
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.
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()
}
}