Skip to content

Instantly share code, notes, and snippets.

@sebersole
Created October 18, 2016 23:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sebersole/cefdffe5b6569880f31ecb97425d957e to your computer and use it in GitHub Desktop.
Save sebersole/cefdffe5b6569880f31ecb97425d957e to your computer and use it in GitHub Desktop.
class Antlr4Plugin implements Plugin<Project> {
void apply(Project project) {
project.with {
apply plugin : 'java'
configurations.maybeCreate 'antlr'
Antlr4GenerationTask genTask = tasks.create 'generateGrammarSource', Antlr4GenerationTask
genTask.group = 'Build'
genTask.description = 'Generate source code from ANTLR grammar'
tasks.getByName('compileJava').dependsOn genTask
SourceSet mainSourceSet = project.convention.getPlugin( JavaPluginConvention ).sourceSets.getByName( SourceSet.MAIN_SOURCE_SET_NAME );
mainSourceSet.compileClasspath += configurations.antlr
SourceSet testSourceSet = project.convention.getPlugin( JavaPluginConvention ).sourceSets.getByName( SourceSet.TEST_SOURCE_SET_NAME );
testSourceSet.compileClasspath += configurations.antlr
project.afterEvaluate({
mainSourceSet.java.srcDir( genTask.outputDirectory )
})
}
}
}
class Antlr4GenerationTask extends DefaultTask {
def String baseInputDirectory = 'src/main/antlr'
def String packageName = 'org.hibernate.sqm.parser.hql.internal.antlr'
def List<String> grammarNames = ['HqlLexer.g4', 'HqlParser.g4']
def String outputDirectoryPath = "generated-src/antlr/main"
@InputFiles
@SkipWhenEmpty
public FileCollection getSource() {
return this.getProject().files(
grammarNames.collect( {name-> baseInputDirectory + '/' + packageName.replace( '.', '/' ) + '/' + name } )
);
}
@OutputDirectory
File getOutputDirectory() {
return project.file( "${project.buildDir}/${outputDirectoryPath}" )
}
@TaskAction
void antlrGeneration() {
File packagedOutputDirectory = new File( outputDirectory, packageName.replace( '.', '/' ) )
packagedOutputDirectory.mkdirs()
source.forEach({File grammarFile->
project.javaexec {
main 'org.antlr.v4.Tool'
classpath project.configurations.antlr
args '-o', packagedOutputDirectory.absolutePath
args '-lib', grammarFile.parentFile.absolutePath
args '-long-messages'
args '-listener'
args '-visitor'
args grammarFile.absolutePath
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment