Friday, January 20, 2017

But first, a word on Pipes

I was planning on this next article being about processing plist output from system_profiler but I decided to do a quick side trip to talk just a little bit about Pipes.
Swift's Pipe class is very similar to the '|' you would see in a bash script. In the previous article we hooked one end of the Pipe to a Process' stdout and our program read from it. Swift Pipes can also be used to connect running Processes together.
Consider the following code:
In lines 3 and 5 we create a pipe called lsStdout and hook it up to the stdout of the ls process. In line 12 we hook that same pipe to the stdin of the wc process. This feeds the list of files being generated by ls directly into the stdin of the wc command. By default, ls outputs one file name per line if it detects that it is not connected to a console so if we tell wc to count the lines of its stdin, we get a file count.
So the above code is basically the equivalent of this:
ls | wc -l

Or this in plain swift
let fm = try FileManager.default.contentsOfDirectory(atPath: "./") print(fm.count)

But that's not the point. The point is that pipes can be used to chain together processes much the same way as you can in bash. Maybe this is useful to you. Maybe it isn't. But I think it's sort of cool.
Next time I will take a look at generating and dealing with plist output from system_profiler.