Skip to content

Instantly share code, notes, and snippets.

@eahrold
Last active October 24, 2020 17:12
Show Gist options
  • Save eahrold/b5c5fd455225a8726e1cc31708e139db to your computer and use it in GitHub Desktop.
Save eahrold/b5c5fd455225a8726e1cc31708e139db to your computer and use it in GitHub Desktop.
pipe Process (NSTask) in swift
//
// ProcessPipe.swift
//
// Created by Eldon on 8/10/18.
// Copyright © 2018 Big Club Digital. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
/**
## Pipeable Process
### Usage Examples:
#### Example 1
```
let ls = Process("/bin/ls", ["-al"])
let grep = Process("/usr/bin/grep", ["com"])
let cut = Process("/usr/bin/awk", ["{print $3}"])
ls.pipe(grep).pipe(cut).complete {
message, status in
print("P1 \(message) \(status)")
}
ls.launch()
```
#### Example 2, the | infix operator (Very Shell)
```
let ls = Process("/bin/ls", ["-al"])
let grep = Process("/usr/bin/grep", ["com"])
let cut = Process("/usr/bin/awk", ["{print $1}"])
ls | grep | cut.complete {
message, status in
print("P2 \(message) \(status)")
}
ls.launch()
```
*/
import Foundation
public typealias PipeProcessTerminationHandler = ((_ out: String, _ status: OSStatus) -> Void)
typealias ProcessTerminationHandler = ((_ process: Process) -> Void)
protocol Pipeable {
func pipe(_ process: Self, _ complete:PipeProcessTerminationHandler) -> Self
}
infix operator |
/// Shorthand For Piping one process to another, very shell
///
/// - Parameters:
/// - left: One Process
/// - right: The Other Process
/// - Returns: The Other Process (To Further chain)
func | ( left: Process, right: Process) -> Process {
return left.pipe(right)
}
// MARK: - Process Extension For Piping
public extension Process {
/// Initalize a process with the command and some args
///
/// - Parameters:
/// - launchPath: Sets the receiver’s executable.
/// - arguments: Sets the command arguments that should be used to launch the executable.
convenience init(_ launchPath: String, _ arguments: [String]?=nil) {
self.init()
self.launchPath = launchPath
self.arguments = arguments
}
/// Handler for converting the pipable processs termination handler to one that returns the text
///
/// - Parameter complete: ((_ process: Process) -> Void)
/// - Returns: ((_ out: String, _ status: OSStatus) -> Void)
internal func pipeTerminationAdapter( _ complete: PipeProcessTerminationHandler?)->ProcessTerminationHandler {
return {
task in
guard
let data = (task.standardOutput as? Pipe)?.fileHandleForReading.availableData,
let string = String(data: data, encoding: .utf8)
else {
complete?("", task.terminationStatus)
return
}
complete?(string, task.terminationStatus)
}
}
/// Called When The Pipeable task finishes
///
/// - Parameter complete: ((_ out: String, _ status: OSStatus) -> Void)
/// - Returns: Self
func complete( _ complete:@escaping PipeProcessTerminationHandler) -> Process {
self.terminationHandler = pipeTerminationAdapter(complete)
return self
}
/// Create a process pipe
///
/// - Parameters:
/// - launchPath: Sets the receiver’s executable.
/// - arguments: Sets the command arguments that should be used to launch the executable.
/// - complete: ((_ process: Process) -> Void) called when the chained process completes _NOTE: this should only be on the final process in the pipe_
/// - Returns: The chained process
func pipe(_ launchPath: String, _ arguments: [String]?=nil, _ complete:PipeProcessTerminationHandler?=nil) -> Process {
let process = Process(launchPath, arguments)
return self.pipe(process, complete)
}
/// Create a process pipe
///
/// - Parameters:
/// - process: Process the process to chain
/// - complete: ((_ process: Process) -> Void) called when the chained process completes _NOTE: this should only be on the final process in the pipe_
/// - Returns: the process to chain
func pipe(_ process: Process, _ complete:PipeProcessTerminationHandler?=nil) -> Process {
let command = Pipe()
let target = Pipe()
self.standardOutput = command
process.standardInput = command
process.standardOutput = target
self.terminationHandler = {
_ in
process.launch()
}
if let _ = complete {
process.terminationHandler = self.pipeTerminationAdapter(complete)
}
return process
}
}
@caobug
Copy link

caobug commented Apr 26, 2019

Good job. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment