|
| 1 | +// |
| 2 | +// CommandsENV.swift |
| 3 | +// |
| 4 | +// |
| 5 | +// Created by zhifei qiu on 2021/8/2. |
| 6 | +// |
| 7 | + |
| 8 | +import Foundation |
| 9 | + |
| 10 | +public protocol CommandsENV { |
| 11 | + var executableURL: String { get } |
| 12 | + var dashc: String { get } |
| 13 | + |
| 14 | + func env() |
| 15 | + |
| 16 | + func run(_ command: String) -> Commands.Result |
| 17 | + func system(_ command: String) |
| 18 | +} |
| 19 | + |
| 20 | +public extension CommandsENV { |
| 21 | + func env() { |
| 22 | + let desc = """ |
| 23 | + ExecutableURL: \(executableURL) |
| 24 | + Dashc: \(dashc) |
| 25 | + """ |
| 26 | + print(desc) |
| 27 | + } |
| 28 | + |
| 29 | + @discardableResult |
| 30 | + func run(_ command: String) -> Commands.Result { |
| 31 | + let process = prepare(command) |
| 32 | + |
| 33 | + let output = Pipe() |
| 34 | + process.standardOutput = output |
| 35 | + |
| 36 | + let error = Pipe() |
| 37 | + process.standardError = error |
| 38 | + |
| 39 | + run(process) |
| 40 | + |
| 41 | + let outputData = output.fileHandleForReading.readDataToEndOfFile() |
| 42 | + let outputActual = String(data: outputData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines) |
| 43 | + |
| 44 | + let errorData = error.fileHandleForReading.readDataToEndOfFile() |
| 45 | + let errorActual = String(data: errorData, encoding: .utf8)!.trimmingCharacters(in: .whitespacesAndNewlines) |
| 46 | + |
| 47 | + if process.terminationStatus == EXIT_SUCCESS { |
| 48 | + return Commands.Result.Success(output: outputActual) |
| 49 | + } |
| 50 | + |
| 51 | + return Commands.Result.Failure(code: process.terminationStatus, output: errorActual) |
| 52 | + } |
| 53 | + |
| 54 | + func system(_ command: String) { |
| 55 | + let process = prepare(command) |
| 56 | + run(process) |
| 57 | + } |
| 58 | +} |
| 59 | + |
| 60 | +private extension CommandsENV { |
| 61 | + func prepare(_ command: String) -> Process { |
| 62 | + let process = Process() |
| 63 | + if #available(macOS 10.13, *) { |
| 64 | + process.executableURL = URL(fileURLWithPath: executableURL) |
| 65 | + } else { |
| 66 | + process.launchPath = executableURL |
| 67 | + } |
| 68 | + process.arguments = [dashc, command] |
| 69 | + return process |
| 70 | + } |
| 71 | + |
| 72 | + func run(_ process: Process) { |
| 73 | + if #available(macOS 10.13, *) { |
| 74 | + try? process.run() |
| 75 | + } else { |
| 76 | + process.launch() |
| 77 | + } |
| 78 | + process.waitUntilExit() |
| 79 | + } |
| 80 | +} |
0 commit comments