//#!/usr/bin/env swift
import Foundation
struct ProcessRunResult{
let isSuccess: Bool
let stdError: String
let stdOutput: String
}
func cmd(_ launchPath: String, arguments: [String], currentDir: URL? = nil) -> ProcessRunResult{
let process = Process()
process.launchPath = launchPath
process.arguments = arguments
if let url = currentDir {
process.currentDirectoryPath = url.path
}
let errPipe = Pipe()
let outputPipe = Pipe()
process.standardError = errPipe
process.standardOutput = outputPipe
process.launch()
process.waitUntilExit()
let error = String(data: errPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
let output = String(data: outputPipe.fileHandleForReading.readDataToEndOfFile(), encoding: .utf8) ?? ""
return ProcessRunResult(isSuccess: process.terminationStatus == 0,
stdError: error.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines),
stdOutput: output.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))
}
func which(_ command: String) -> String {
let result = cmd("/usr/bin/which", arguments: [command])
return result.stdOutput.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
}
func shell(_ command: String, currentDir: URL? = nil) -> String {
var args = command.components(separatedBy: CharacterSet.whitespacesAndNewlines)
let cmdName = which(args.first!)
args.removeFirst()
let result = cmd(cmdName, arguments: args, currentDir: currentDir)
print(result.isSuccess ? result.stdOutput : result.stdError)
return result.stdOutput
}
网友评论