15. May 2015
While adding SSH key validation to Buildasaur, I encountered an interesting problem. It was relatively difficult to find advice on how to run simple Terminal scripts from your Mac app written in Swift.
Technically, it’s not difficult, but I couldn’t find a simple wrapper that’d just need something like…
Script.run("say \"I'm alive\""). So I wrote one, and I use it in Buildasaur now. Find the gist below.
The idea is that you spin off an
NSTask and pipe the output into an in-memory file, so that you can turn the result into a string after the script has finished. Plus, you need to block the calling thread until the script has returned (which matched my requirement, but might not be the best solution for longer running scripts).
I added an option to call the binary by just name (e.g.
git and it will automatically resolve to the right path with
which git) or you can just pass in the whole path (such as
/usr/bin/git). Also, there are two APIs. One for simple one-script call, with arguments and environment passed in nicely as an array and a dictionary, respectively. The other one is a “free-for-all”, where you pass in the full string of the script (such as
say "Kittens are fuzzy!") and the
Script class will dump it into a temporary script file, run it with
bash and clean up afterwards.
Now, nothing is standing in the way of you making your Mac app talk :)