Files
narya/src/java/com/threerings/presents/tools/GenTask.java
T
Michael Bayne 4b443fe148 Last night, I read about the Mustache templating library (a derivative of
Google's CTemplate) and got all hot and bothered, because it seemed like it
would be sufficiently powerful to replace Velocity for our Narya templating
needs.

I then sought out a Java implementation and found one, and quickly discovered
that it lacked the right level of awesome for my needs. So I foolishly decided
to write my own, because Mustache seemed simple enough that I could reimplement
it in a few hours.

A few hours later, I had a neat and tidy reimplementation of Mustache and then
set about to converting Narya to using it. Then the fun began.

I discovered that Mustache wants everything in a hash, but sometimes you just
want to iterate over the elements of a list, and print them into the template
whole-hog. So I extended Mustache with the special "this" variable for printing
the whole context instead of pulling values out of it by name.

Then I remembered that Velocity allows you to do a deep dive into objects,
calling methods and calling methods on the return values of those methods.
Velocity even allows you to pass constants as arguments to those methods (true,
strings, integers). Well, I reimplemented the compound keys, so that you can
call foo.bar.baz, but I didn't go so far as to support constant arguments. That
seemed a step too far into complexity land and to be the sort of thing that
Mustache tries to avoid. So with compound keys, I just had to add a few
alternative versions of methods we were already calling, since we only ever
passed true/false as an argument.

Then I realized that Mustache doesn't do any smart trimming of newlines, so if
you have:

{{#stuff}}
blah blah
{{/stuff}}

You get the annoying newline after the open-tag and after the close-tag. So I
modified my implementation to trim newlines in those circumstances, so that
template authors don't have to do a bunch of template-weirding whitespace
jockeying.

Then I discovered that Mustache doesn't support any notion of scope. So when
you're inside a so-called section, the only variables visible are those bound
by that section. The stuff outside the section is totally invisible. Well,
that's not how Velocity works, you can reference things outside your loop
iterations. It seemed no terribly affront to Mustache to make things work that
way as well, so I did that.

Then I discovered a problem with the fact that Mustache implicitly binds the
loop object to the root of the namespace, so if you have {{name}} outside the
loop and then your loop object also contains a {{name}} field, then you can't
see the outside {{name}} anymore because it's shadowed. Tough titties, in this
case, I just changed our code to not shadow the name.

Then I encountered a bunch of uses of $vidx to put a space before all but the
first element of a list. So I added two more special variables -first and -last
which allow you to do just that sort of thing (and more) in a more template
friendly way because you don't need a Turing complete language just to decide
whether or not you need to mind the gap.

Then I encoutered some uses of $vidx directly, where we were using it to assign
constants in invocation service related classes. So I added another special
variable -index which resolves to basically the same thing that $vidx resolves
to (a 1-based counter indicating which element you're on in your list
iteration). I rationalized to myself that if you wanted to automatically number
laundry lists in your templates, having -index would be nice.

Finally, I have Narya's templating stuff producing character-for-character
replicas of what it used to do with Velocity. Well, actually there's one
newline in a place where there didn't used to be one, but I think that newline
makes sense and it was maybe some sort of Velocity bug that caused it not to
exist.

I've tested the gendobj, genservice and genreceiver tasks. I have no tested
whatever uses streamable_as.tmpl, but I'm pretty confident that it will work
exactly as before because I modified hundreds of lines of other templates in
exactly the same ways and they all work just fine.

So the world gets yet another templating library:

http://code.google.com/p/jmustache/


git-svn-id: svn+ssh://src.earth.threerings.net/narya/trunk@6218 542714f4-19e9-0310-aa3c-eee0fc999fb1
2010-10-22 06:42:47 +00:00

165 lines
5.5 KiB
Java

//
// $Id$
//
// Narya library - tools for developing networked games
// Copyright (C) 2002-2010 Three Rings Design, Inc., All Rights Reserved
// http://code.google.com/p/narya/
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.presents.tools;
import java.util.List;
import java.util.Map;
import java.io.File;
import java.io.InputStreamReader;
import java.io.StringWriter;
import org.apache.tools.ant.AntClassLoader;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.FileSet;
import org.apache.tools.ant.types.Reference;
import org.apache.tools.ant.util.ClasspathUtils;
import com.google.common.collect.Maps;
import com.google.common.collect.Lists;
import com.samskivert.mustache.Mustache;
public abstract class GenTask extends Task
{
/**
* Adds a nested <fileset> element which enumerates service declaration source files.
*/
public void addFileset (FileSet set)
{
_filesets.add(set);
}
/**
* Configures to output extra information when generating code.
*/
public void setVerbose (boolean verbose)
{
_verbose = verbose;
}
/** Configures our classpath which we'll use to load service classes. */
public void setClasspathref (Reference pathref)
{
_cloader = ClasspathUtils.getClassLoaderForPath(getProject(), pathref);
// set the parent of the classloader to be the classloader used to load this task, rather
// than the classloader used to load Ant, so that we have access to Narya classes like
// TransportHint
((AntClassLoader)_cloader).setParent(getClass().getClassLoader());
}
/**
* Performs the actual work of the task.
*/
@Override
public void execute ()
{
for (FileSet fs : _filesets) {
DirectoryScanner ds = fs.getDirectoryScanner(getProject());
File fromDir = fs.getDir(getProject());
String[] srcFiles = ds.getIncludedFiles();
for (String srcFile : srcFiles) {
File source = new File(fromDir, srcFile);
try {
processClass(source, loadClass(source));
} catch (Exception e) {
throw new BuildException(e);
}
}
}
}
/**
* Merges the specified template using the supplied mapping of keys to objects.
*
* @param data a series of key, value pairs where the keys must be strings and the values can
* be any object.
*/
protected String mergeTemplate (String template, Object... data)
throws Exception
{
Map<String, Object> ctx = Maps.newHashMap();
for (int ii = 0; ii < data.length; ii += 2) {
ctx.put((String)data[ii], data[ii+1]);
}
return mergeTemplate(template, ctx);
}
/**
* Merges the specified template using the supplied mapping of string keys to objects.
*
* @return a string containing the merged text.
*/
protected String mergeTemplate (String template, Map<String, Object> data)
throws Exception
{
return Mustache.compiler().escapeHTML(false).compile(new InputStreamReader(
getClass().getClassLoader().getResourceAsStream(template), "UTF-8")).execute(data);
}
/**
* Process a class found from the given source file that was on the filesets given to this
* task.
*/
protected abstract void processClass (File source, Class<?> klass)
throws Exception;
protected Class<?> loadClass (File source)
{
// load up the file and determine it's package and classname
String name;
try {
name = GenUtil.readClassName(source);
} catch (Exception e) {
throw new BuildException("Failed to parse " + source + ": " + e.getMessage());
}
return loadClass(name);
}
protected Class<?> loadClass (String name)
{
if (_cloader == null) {
throw new BuildException("This task requires a 'classpathref' attribute " +
"to be set to the project's classpath.");
}
try {
return _cloader.loadClass(name);
} catch (ClassNotFoundException cnfe) {
throw new BuildException(
"Failed to load " + name + ". Be sure to set the 'classpathref' attribute to a " +
"classpath that contains your project's presents classes.", cnfe);
}
}
/** A list of filesets that contain java source to be processed. */
protected List<FileSet> _filesets = Lists.newArrayList();
/** Show extra output if set. */
protected boolean _verbose;
/** Used to do our own classpath business. */
protected ClassLoader _cloader;
}