Skip to content

Instantly share code, notes, and snippets.

@VaslD
Created March 9, 2023 02:29
Show Gist options
  • Save VaslD/1f0602a7811768a3138ddd6a39e7779d to your computer and use it in GitHub Desktop.
Save VaslD/1f0602a7811768a3138ddd6a39e7779d to your computer and use it in GitHub Desktop.
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