I recently discovered a neat little extra automation tool on top of the familiar ones of AppleScript, Automator, and script runners like FastScripts and Keyboard Maestro. Meet Hammerspoon, which differs significantly in not using Apple Events to do many of its automation tasks. Instead, Hammerspoon bridges directly to Apple APIs using the lua scripting language, and that allows you to do some interesting things.
Here’s a good example. One of the ‘danger zones’ on your mac – by which I mean one of the favourite places for adware, malware and other assorted badwares to infect – is your LaunchAgents folders. Apps like my DetectX and FastTasks 2 keep an eye on these areas by design, warning you in the Changes and History logs when files have been added or removed from them – but Hammerspoon can add an extra little ‘canary’ warning for you too. With only a few lines of code in Hammerspoon’s config file, you can set up an alert that will fire whenever the LaunchAgents folder is modified.
It has been possible to rig up something similar for a long time with Apple’s built-in Folder Actions, but there’s a couple of reasons why I prefer Hammerspoon for this task. One, despite Apple’s attempt to improve Folder Actions’ reliability, I’m still not convinced. I get inconsistent reports when asking System Events to check whether Folder Actions is enabled even on 10.11 and 10.12. Second, Folder Actions is limited in what it will respond to. By default, only if an item is added. With a bit of effort, you can rig it up to watch for items deleted, too, but that’s pretty much it. With Hammerspoon, it’ll alert you whenever the folder or its contents are modified in any way whatsoever. The final reason for preferring Hammerspoon for this particular task is ease of use. It really is as simple as pasting this code into the config file:
hs.alert.show("Launch Agents folder was modified")
hs.alert.show("Canary folder was modified")
local aWatcher = hs.pathwatcher.new(os.getenv("HOME") .. "/Library/LaunchAgents/", myFolderWatch):start()
local bWatcher = hs.pathwatcher.new(os.getenv("HOME") .. "/_Acanary/", canaryFolderWatch):start()
And what’s the config file you ask? Nothing complicated! Just launch Hammerspoon, click its icon and choose ‘open config’.
That will launch your default text editor, and all you do is paste your code into there, save it (no need to tell it where, Hammerspoon already knows) and then go back to the Hammerspoon icon and click ‘Reload config’. That’s it. Less than a minute’s work!
There’s a lot, lot more you can do with Hammerspoon, so if you’re interested head off and check out the Getting Started guide. One of the nice things is that you can even call AppleScripts with it, so you really do have a world of automation options to choose from!