Created
March 9, 2023 02:29
-
-
Save VaslD/1f0602a7811768a3138ddd6a39e7779d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import ArgumentParser | |
public enum Path { | |
static let path = ProcessInfo.processInfo.environment["PATH"]!.components(separatedBy: ":") | |
public static func find(_ command: String) throws -> URL { | |
let files = FileManager.default | |
for path in Self.path { | |
let executable = URL(fileURLWithPath: path).appendingPathComponent(command, isDirectory: false) | |
guard files.fileExists(atPath: executable.path) else { | |
continue | |
} | |
let metadata = try executable.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, | |
.isExecutableKey]) | |
if metadata.isRegularFile! || metadata.isSymbolicLink!, metadata.isExecutable! { | |
return executable | |
} | |
} | |
throw POSIXError(.ENOENT) | |
} | |
public static func run(_ command: String, _ arguments: String...) throws -> String { | |
let process = Process() | |
process.executableURL = try Self.find(command) | |
process.arguments = arguments | |
let pipe = Pipe() | |
process.standardOutput = pipe | |
try process.run() | |
process.waitUntilExit() | |
guard process.terminationStatus == EX_OK else { | |
throw ExitCode(process.terminationStatus) | |
} | |
return try pipe.fileHandleForReading.readToEnd().flatMap { | |
String(data: $0, encoding: .utf8) | |
} ?? String() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment