Skip to main content

Using jrunscript to create a build script

Posted by forax on September 13, 2006 at 6:00 AM EDT

The JDK6 provides a new command jrunscript that enables to execute script shell in Java environment. By default, jrunscript uses javascript as scripting language and provides some useful default functions like cp, cd, cat, etc.

These global functions seem designed to ease the creation of build scripts, so i propose to show the basics of how to write such scripts.

First, the script must create the directory that will contain classes :

 // project properties
 srcDir='src'
 classDir='classes'

 // target init
 mkdirs(classDir);

To run the script, just type jrunscript yourScriptFileName.js in your shell
Then the script must compile the sources...
Weark, there is not function named javac that compiles sources to classes !!

But this function is easy to write using the package javax.tools introduced by the JSR199 and available in mustangjdk6.
In addition to javac, we need another function that gather all the source files of some directory, i've named it fileset in reference to the <fileset> of Ant.

So compiling a source tree is done with the following lines in javascript :

 function fileset(path,pattern) {
   var set=new Array()
   function callback(file) {
     set.push(file)
   }
   find(path,pattern,callback)
   return set 
 }

 // target compile
 echo('compile')
 javac(fileset(srcDir,'.*\.java'),classDir)

you can notice that callback is some kind of closure in javascript :)
The function javac is just a copy/paste of one example that you can find in the comment of the class javax.tools.JavaCompilerTool :

function javac(fileset,destDir) {
  compiler=javax.tools.ToolProvider.getSystemJavaCompiler()
  fileManager=compiler.getStandardFileManager(null,null,null)
  fileManager.setLocation(
    javax.tools.StandardLocation.CLASS_OUTPUT,
    java.util.Arrays.asList([new java.io.File(destDir)].valueOf()))

  compilationUnit=fileManager.getJavaFileObjectsFromFiles(
    java.util.Arrays.asList(fileset.valueOf()));
    task=compiler.getTask(null,fileManager,
                          null,null,null,compilationUnit)
  task.call()
  
  fileManager.close()
}

We now have a basic script that compiles a java project, ok, it doesn't have by example a way to declare dependency between target like Ant but that's a good starting point.
The whole script is available here and if you want to know more about scripting and Java, you can read the A. Sundararajan's Weblog.

Rémi Forax
Related Topics >>