Skip to content

Instantly share code, notes, and snippets.

@tyama
Last active July 28, 2016 04:34
Show Gist options
  • Save tyama/402921 to your computer and use it in GitHub Desktop.
Save tyama/402921 to your computer and use it in GitHub Desktop.
import org.codehaus.groovy.groovydoc.GroovyRootDoc
import org.codehaus.groovy.tools.groovydoc.GroovyDocTool
import static groovy.io.FileType.FILES
/**
* Generate i18n messages.properties from the domain class comments
*
* grails generate-i18n-labels
* grails generate-i18n-labels {target lang}
* grails generate-i18n-labels {lang} {target package}
*/
description "Generate i18n messages.properties from the domain class comments", "grails generate-i18n-labels {lang} {package}"
String lang = args[0]?args[0]:''
String targetPackage = args[1]?args[1]:null
File domainDir = new File('grails-app/domain')
if(targetPackage){
targetPackage = targetPackage.replaceAll(/\./,'/')
domainDir = new File(domainDir,targetPackage)
}
if(!domainDir.exists()){
println "${domainDir.absoluteFile} not found."
return
}
List srcFiles =[]
String domainSrcPath = domainDir.absolutePath+'/'
domainDir.eachFileRecurse FILES,{ srcFiles<<(it.absolutePath - domainSrcPath) }
def docTool = new GroovyDocTool([domainSrcPath] as String[])
docTool.add(srcFiles)
GroovyRootDoc root = docTool.getRootDoc()
def classes = root.classes()
def excludeProp = ['constraints','hasMany','belongsTo','mapping']
def generateI18nPropLabelFor = {d,propFile->
def comment = d.getRawCommentText()
if(!comment) return
def classLabel = comment.find(/@label(.*)/){it[1].trim()}?:d.firstSentenceCommentText()
def className = d.name()
def propName = className[0].toLowerCase() + className[1..-1]
StringBuilder sb = new StringBuilder()
sb.append "${propName}.label=${classLabel}\n"
d.properties().each{p->
if(!excludeProp.contains(p.name())){
sb.append "${propName}.${p.name()}.label=${p.commentText().trim()?:p.name()}\n"
}
}
propFile.append sb.toString() + '\n'
}
String propertiesFilePath = "grails-app/i18n/messages${'_'+lang}.properties"
File propertiesFile = new File(propertiesFilePath)
propertiesFile.append '#---- generated by command ----\n'
classes.each {
generateI18nPropLabelFor it, propertiesFile
}
propertiesFile.append '#---- generated by command /----'
println ">>> Added i18n to ${propertiesFilePath} file."
@tyama
Copy link
Author

tyama commented Jul 28, 2016

Updated to Grails3 version.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment