All Downloads are FREE. Search and download functionalities are using the official Maven repository.

li.rudin.mavenjs.compiler.cs.CoffeeScriptCompiler Maven / Gradle / Ivy

The newest version!
package li.rudin.mavenjs.compiler.cs;

import li.rudin.mavenjs.api.Compiler;
import li.rudin.mavenjs.core.JavascriptContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class CoffeeScriptCompiler implements Compiler
{

	/**
	 * Local logger
	 */
	private static final Logger logger = LoggerFactory.getLogger(CoffeeScriptCompiler.class);


	private final ThreadLocal threadlocalCtx = new ThreadLocal(){

		@Override
		protected JavascriptContext initialValue() {
			try
			{
				JavascriptContext ctx = new JavascriptContext();
				ctx.eval( CoffeeScriptCompiler.class.getResourceAsStream("/js/coffee-script.js") );
				return ctx;
			}
			catch (Exception e)
			{
				logger.error("init", e);
				return null;
			}
		}
	};

	@Override
	public String getSourceExtension()
	{
		return "coffee";
	}

	@Override
	public String getTargetExtension()
	{
		return "js";
	}

	@Override
	public String compile(String fileName, String input) throws Exception
	{
		logger.debug("compiling: {}", fileName);

		long start = System.currentTimeMillis();

		JavascriptContext ctx = threadlocalCtx.get();

		String escapedInput = 
				input
				.replace("\r", "\\r")
				.replace("\n", "\\n")
				.replace("'", "\\'");


		String js = (String)ctx.eval("CoffeeScript.compile('"+escapedInput+"');");

		long diff = System.currentTimeMillis() - start;
		logger.debug("Compiled '{}' in {} ms (size before: {}, after: {})", fileName, diff, input.length(), js.length());

		return js;


	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy