Change dir batch generator using Groovy

Still using my “Use Groovy to create quick change dir scripts” utility on Windows to change current folder in a shell.  Just updated it to take an external properties file to use for the list of destination directories, see listing one below. Source also available here.

Note that original post gave a much simpler approach that generates a temporary batch file and then executes it.

Listing 1

Listing 1, cd batch creator
/**
 * GoGenerator.groovy
 * Copyright  2010 Josef Betancourt 20100312-17:47
 */

/*@Grapes([
@Grab(group='ch.qos.logback', module='logback-core', version='0.9.18'),
@Grab(group='ch.qos.logback', module='logback-classic', version='0.9.18'),
@Grab(group='org.slf4j', module='slf4j-api', version='1.5.10')])

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
*/

/**
 * Command line utility class to generate an OS specific
 * quick change directory script file.
 *
 * Syntax: GoGenerator [<file name>]
 * If target file name is not specified, output goes to std out.
 * Example: groovy GoGenerator.groovy
 * Example: groovy GoGenerator.groovy go.cmd
 *
 * Other utilities of this type are:
 *   Quick Change Directory: http://www.stevemiller.net/qcd/
 *   WCD:  http://www.xs4all.nl/~waterlan/
 *   List of directory changers:  http://www.xs4all.nl/~waterlan/other.htm
 *
 * Currently only Windows builder is implemented below.
 * Tested on Groovy 2.0.0, java version "1.7.7_07", Windows 7 64bit Professional
 *
 * @author jbetancourt
 */
public class GoGenerator {
	// Map of the location targets for the script utility.
	def static winDb = [:]
	def static linuxDb = [:]

	/**
	 * main entry point
	 * @param args
	 */
	static main(args) {
		def fileName
		def pathPropertiesFile 
		
		switch(args.length){
			case 0:
				print """
				*********  ERROR  *********\n
				Syntax: groovy GoGenerator.groovy <properties file path> [output file]
				Example 1:  groovy GoGenerator paths.properties go.cmd
				Example 2:  groovy GoGenerator paths.properties 
				"""
				return				
			case 1:
				pathPropertiesFile = args[0]			
				break				
			case 2:
				pathPropertiesFile = args[0]
				fileName = args[1]			
				break				
		}
		
		def props = new Properties();
		props.load(new File(pathPropertiesFile).newReader())
		props.each{
			winDb.put(it.key,it.value)
		}

		def builder = createBuilder(fileName)
		builder.generate()
	}

	/**
	 * factory method to create an OS specific go builder.
	 *
	 * @param db map of folders
	 * @param fileName target file name or null
	 * @return the builder object
	 */
	static createBuilder(fileName){
		def ant = new AntBuilder()
		ant.condition(property:"winOS"){
			os(family:"windows")
		}
		ant.condition(property:"linuxOS"){
			os(family:"unix")
		}

		def builder
		// get first property entry whose key ends in "OS"
		def entry = ant.project.getProperties().find{ it.key ==~ /.*OS$/}

		switch(entry ? entry.key : "xyz"){
		  case 'winOS':
			builder = new WinGoBuilder(winDb, fileName)
			break
		  case 'linuxOS':
			builder = new LinuxGoBuilder(linuxDb, fileName)
			break
		  case 'xyz' :
			builder = new ErrorGoBuilder()
			break
		}

		return builder
	}

} // end class GoGenerator

/**
 * Creates go scripts.
 * Superclass of OS specific builders
 *
 * @author jbetancourt
 */
class GoBuilder {
    def script = '''echo TODO!''' // template
    def db  // stores the data binding
    def fileName  // the target script file to create

    /**
     * Create the target script file or if
     * no filename send to stdout
     */
    def generate(){
		def engine = new groovy.text.SimpleTemplateEngine()
		def template = engine.createTemplate(script)
		def result = template.make(["db":db])
		if(fileName){
			File file = new File(fileName)
			file.write(result.toString())
		}else{
			println result
		}
    }
} // end class GoBuilder

/**
 * Creates an error message output builder.
 *
 * @author jbetancourt
 */
class ErrorGoBuilder extends GoBuilder {
    def os = System.getProperty("os.name")
} // end class ErrorGoBuilder

/**
 * Creates a Windows specific go script.
 *
 * @author jbetancourt
 *
 */
class WinGoBuilder extends GoBuilder  {
	    def winScript =
'''
@ECHO OFF
rem Go.bat
rem DO NOT EDIT THIS FILE.  It is generated using GoGenerator.groovy script.
rem purpose:   aid rapid directory setting at command line
rem example:  go full
rem if "%OS%"=="Windows_NT" setlocal
if "%1."=="." goto ERROR
<% db.each { %>
if NOT %1==$it.key goto ${it.key.toUpperCase()}-END
<% if(it.value ==~ /^\\S:.*/) {
print(it.value.substring(0,1) + ":")
}%>
cd $it.value
goto FINISH
: ${it.key.toUpperCase()}-END
<% } %>
:ERROR
echo GO.BAT: Huh?  [%1] Syntax is: go keyword
echo Didn't locate keyword: [%1]
echo Targets are
<% db.each { %>
echo <% print("\t" + it.key + "=" + it.value) %>
echo -------------------------------------
<% } %>
:FINISH
rem if "%OS%"=="Windows_NT" endlocal
'''
	    /**
	     * Constructor
	     */
	    WinGoBuilder(db, fileName){
	    	this.db = db
	    	this.fileName = fileName
	    	script = winScript
	    }

} // end class WinGoBuilder

/**
 * Creates a Linux specific go script builder
 *
 * @author jbetancourt
 */
class LinuxGoBuilder  extends GoBuilder {
	def linuxScript = ''''''

    /** Constructor */
    LinuxGoBuilder(fileName){
    	this.fileName = fileName
    }

} // end class LinuxGoBuilder

// end of source GoGenerator.groovy

Further Reading

  1. Use Groovy to create quick change dir scripts

Similar Posts:

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.

One thought on “Change dir batch generator using Groovy”

Leave a Reply

Your email address will not be published. Required fields are marked *