gocog
Jan 25, 2013I recently got very enamored with Go, and decided that I needed to write a real program with it to properly get up to speed. One thing came to mind after reading a lot on the Go mailing list: a code generator.
I had worked with Ned Batchelder at a now-defunct startup, where he developed cog.py. I figured I could do something pretty similar with Go, except, I could do one better - Go generates native executables, which means you can run it without needing any specific programming framework installed, and you can run it on any major operating system. Also, I could construct it so that gocog supports any programming language embedded in the file, so long as it can be run via command line.
Thus was born gocog - https://github.com/natefinch/gocog
Gocog runs very similarly to cog.py - you give it files to look at, and it reads the files looking for specially tagged embedded code (generally in comments of the actual text). Gocog extracts the code, runs it, and rewrites the file with the output of the code embedded.
Thus you can do something like this in a file called test.html:
<html>
<body>
<!– [[[gocog
print “<b>Hello World!</b>“
gocog]]] –>
<!– [[[end]]] –>
</body>
</html>
if you run gocog over the file, specifying python as the command to run:
gocog test.html -cmd python -args %s -ext .py
This tells gocog to extract the code from test.html into a file with the .py extension, and then run python <filename> and pipe the output back into the file.
This is what test.html looks like after running gocog:
<html>
<body>
<!– [[[gocog
print “<b>Hello World!</b>“
gocog]]] –>
<b>Hello World!</b>
<!– [[[end]]] –>
</body>
</html>