Skip to content

Instantly share code, notes, and snippets.

@doozMen
Last active September 6, 2023 07:20
Show Gist options
  • Save doozMen/b86714398f2c85b8c501cfea6f48dbf1 to your computer and use it in GitHub Desktop.
Save doozMen/b86714398f2c85b8c501cfea6f48dbf1 to your computer and use it in GitHub Desktop.
Run a simple bash command or run an executable with arguments both async
// MARK: - Functions
/// Until the spm proposal to import things in swift scripts we have to copy this
/// [SwiftPM support for Swift scripts - Evolution / Pitches - Swift Forums](https://forums.swift.org/t/swiftpm-support-for-swift-scripts/33126)
extension Process {
func runAsync() async throws {
let command = "\(executableURL?.lastPathComponent ?? "") \(arguments?.joined(separator: " ") ?? "")"
print(command)
try run()
try await Task {
waitUntilExit()
guard terminationStatus == 0 else {
throw Error.command(command, code: terminationStatus)
}
}.value
}
func run(command: String) async throws {
do {
executableURL = URL(fileURLWithPath: "/bin/bash")
arguments = ["-c", command]
print("\(command)")
try run()
try await Task {
waitUntilExit()
guard terminationStatus == 0 else {
throw Error.command(command, code: terminationStatus)
}
}.value
} catch {
throw Error.setup(error)
}
}
enum Error: Swift.Error {
case command(String, code: Int32)
case setup(Swift.Error)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment