Hazel powered mogenerator

May 01, 2012

Having recently started using the excellent mogenerator by Jonathan ‘Wolf’ Rentzsch for a project, I wanted a way to have it automatically run whenever I edit the .xcdatamodeld file. The solution to this used to be the Xmo’d tool that is part of the mogenerator project. Unfortunately, Xcode 4 isn’t supported at the moment, so I needed an alternative.

A common approach seems to be the use of a Run Script Build Phase in Xcode. But I’d rather automatically run mogenerator to create and/or update my model files immediately without having to do a build first. I turned to Noodlesoft’s fantastic Hazel, a utility that watches any folder you tell it to and applies custom conditional rules when something changes in that folder.

I added a new set of rules to point to my project’s Sources/Models folder where the .xcdatamodeld is located. I then created a rule with the following conditions (best illustrated with a screenshot):

Hazel rule conditions

The Run shell script action runs the following bash script to perform the actual invocation of mogenerator:

filename=$(basename $1)
outputdir=$(dirname $1)

/usr/local/bin/mogenerator --model $1/${filename%.*}.xcdatamodel --output-dir $outputdir --template-var arc=true

For convenience, I have posted the above Hazel rules file (which includes the shell script) here for download.

Using this setup, Hazel now watches the folder in my Xcode project that contains my Core Data model file. Whenever any changes happen within that folder, Hazel runs the rule I created above and looks for any .xcdatamodeld files that have been modified since the last time Hazel took a look at them. If it finds any modified files, it executes the shell script on them. This in turn causes mogenerator to do its magic.

I find this to work nicely for my needs, though it does have a few limitations. The first is that you have to manually add a duplicate set of the above Hazel rule for every Xcode project with which you want this to happen. The second is that it doesn’t automatically add the files to your Xcode project, but until Xmo’d works with Xcode 4 this will do at least half the job.