Skip to content

Commit

Permalink
Enhance I18nGenerator
Browse files Browse the repository at this point in the history
Add an option `lang`, you can choose which properties file to create or update,

```bash
$ grace generate i18n --lang zh_CN
```

Closes gh-814
  • Loading branch information
rainboyan committed Dec 19, 2024
1 parent fd87de8 commit 49dfe19
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 18 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -30,29 +30,42 @@ class I18nGenerator extends AbstractGenerator {
@Override
boolean generate() {
String[] args = commandLine.remainingArgs.toArray(new String[0])
if (args.size() < 2) {
return
}

String className = args[1].capitalize()
String propertyName = className.uncapitalize()
Map<String, String> classAttributes = new LinkedHashMap<>()
String[] attributes = (args.size() >= 3 ? args[2..-1] : []) as String[]
attributes.each { String item ->
String[] attr = (item.contains(':') ? item.split(':') : [item, 'String']) as String[]
classAttributes[attr[0]] = attr[1]
}
boolean overwrite = commandLine.hasOption('force') || commandLine.hasOption('f')
String lang = commandLine.optionValue('lang')

StringBuilder messages = new StringBuilder()
if (args.size() > 1) {
String className = args[1].capitalize()
String propertyName = className.uncapitalize()
Map<String, String> classAttributes = new LinkedHashMap<>()
String[] attributes = (args.size() >= 3 ? args[2..-1] : []) as String[]
attributes.each { String item ->
String[] attr = (item.contains(':') ? item.split(':') : [item, 'String']) as String[]
classAttributes[attr[0]] = attr[1]
}

StringBuilder text = new StringBuilder()
text.append('\n# ' + className + '\n')
classAttributes.each { attr ->
String label = propertyName + '.' + attr.key + '.label'
String value = GrailsNameUtils.getNaturalName(attr.key)
messages.append('\n# ' + className + '\n')
messages.append(propertyName + '.label=' + className + '\n')
classAttributes.each { attr ->
String label = propertyName + '.' + attr.key + '.label'
String value = GrailsNameUtils.getNaturalName(attr.key)

text.append(label + '=' + value + '\n')
messages.append(label + '=' + value + '\n')
}
}

prependToFile('app/i18n/messages.properties', text.toString())
String messagesFileName = 'app/i18n/messages' + (lang?.trim() ? '_' + lang?.trim() + '.properties' : '.properties')
File messagesFile = new File(getBaseDir(), messagesFileName)
if (messagesFile.exists() && !overwrite && messages.size() > 0) {
prependToFile(messagesFileName, messages.toString())
}
else {
createFile('messages.properties.tpl', messagesFileName, [:], overwrite)
if (messages.size() > 0) {
prependToFile(messagesFileName, messages.toString())
}
}

true
}
Expand Down
Empty file.

0 comments on commit 49dfe19

Please sign in to comment.