Groovy Java File Prepender
applying common comment blocks to java files
A friend of mine is getting ready to release an open source project and needed a quick way to put a common comment block at the beginning of every java file. I thought this would be a good chance for me to brush up on Groovy's slick File tricks and support. Yes, I know this has been done before and probably in Groovy as well, but it was a fun exercise. I would like some suggestions on how to make it better/leaner?
if (args.length < 2) {
println 'Usage:'
println 'groovy ClassLicenseAppender.groovy /src/path /license/file/path'
} else {
def src = args[0]
def licenseFile = args[1]
def licenseText = new StringBuilder();
new File(licenseFile).eachLine {line ->
licenseText.append(line + "\n");
}
new File(src).eachFileRecurse {file ->
if (file.isFile() && file.name.endsWith(".java")) {
def tempFile = new File("tempFileToStoreFileToWrite");
tempFile.append(licenseText.toString())
file.eachLine {line -> tempFile.append(line + "\n") }
file.delete()
tempFile.renameTo(new File(file.getAbsolutePath()))
}
}
}
Re: Groovy Java File Prepender
I got it down to:
if (args.length != 2) {
println 'Usage:'
println 'groovy ClassLicenseAppender.groovy /license/file/path /src/path'
} else {
def licenseText = new File( args[0] ).text
new File( args[ 1 ] ).eachFileRecurse { file ->
if( file.isFile() && file.name.endsWith( ".java" ) ) {
tempFile = new File( "tempFileToStoreFileToWrite" )
tempFile.withWriter { w ->
w.writeLine( licenseText )
w.writeLine( file.text )
}
file.delete()
tempFile.renameTo( new File( file.getAbsolutePath() ) )
}
}
}
Re: Groovy Java File Prepender
I think you could revise it to this, which is even shorter:
if (args.length != 2) { println 'Usage:' println 'groovy ClassLicenseAppender.groovy /license/file/path /src/path' } else { def licenseText = new File( args[0] ).text new File( args[ 1 ] ).eachFileRecurse { file -> if( file.isFile() && file.name.endsWith( ".java" ) ) { file.text = liscenseText + file.text } } }