DEV Community

hori,masaki
hori,masaki

Posted on

2 1

Helpers for Process class in Swift.

Process() <<< "/bin/echo" <<< ["Hello, World.\nこんにちは世界。"]
    | Process() <<< "/usr/bin/grep" <<< ["Hello"]
    >>> { output in

    output.string.map { print($0) }    // Hello, World.
}
Enter fullscreen mode Exit fullscreen mode

Helpers below.

/// 出力を簡単に扱うための補助的な型。FileHandleを隠蔽する。
struct Output {

    private let fileHandle: FileHandle

    init(fileHandle: FileHandle) {
        self.fileHandle = fileHandle
    }

    var data: Data {
        return fileHandle.readDataToEndOfFile()
    }

    var string: String? {
        return String(data: data, encoding: .utf8)
    }

    var lines: [String] {
        return string?.components(separatedBy: "\n") ?? []
    }
}

precedencegroup ArgumentPrecedence {

    associativity: left
    higherThan: AdditionPrecedence
}
infix operator <<< : ArgumentPrecedence

/// Processにexecutable pathを設定する。
func <<< (lhs: Process, rhs: String) -> Process {

    lhs.executableURL = URL(fileURLWithPath: rhs)
    return lhs
}

/// Processに引数を設定する。
func <<< (lhs: Process, rhs: [String]) -> Process {

    lhs.arguments = rhs
    return lhs
}

/// Processをパイプする。
func | (lhs: Process, rhs: Process) -> Process {

    let pipe = Pipe()

    lhs.standardOutput = pipe
    rhs.standardInput = pipe
    lhs.launch()

    return rhs
}

precedencegroup RedirectPrecedence {

    associativity: left
    lowerThan: LogicalDisjunctionPrecedence
}
infix operator >>> : RedirectPrecedence

/// Processの出力をOutput型で受け取り加工などができる。
/// ジェネリクスを利用しているのでどのような型にでも変換して返せる。
func >>> <T>(lhs: Process, rhs: (Output) -> T) -> T {

    let pipe = Pipe()
    lhs.standardOutput = pipe
    lhs.launch()

    return rhs(Output(fileHandle: pipe.fileHandleForReading))
}
Enter fullscreen mode Exit fullscreen mode

Sentry mobile image

Improving mobile performance, from slow screens to app start time

Based on our experience working with thousands of mobile developer teams, we developed a mobile monitoring maturity curve.

Read more

Top comments (0)

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay