Skip to content

Instantly share code, notes, and snippets.

@yu-tang
Last active October 29, 2015 17:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save yu-tang/3b0347a8ec1f6bd6e42a to your computer and use it in GitHub Desktop.
Traverse each descendant file in the directory tree and replaces all occurrences.
/**
* Usage : Put this script in <ScriptsDir>/project_changed folder. Create a folder if it doesn't exists.
*
* @author Yu Tang
* @version 0.2
*/
import static org.omegat.core.events.IProjectEventListener.PROJECT_CHANGE_TYPE.*
// prepare
String dir
def replacePair
def skipTraverse(eventType) {
if (!eventType.metaClass.hasProperty(eventType, 'skipTraverse')) {
eventType.metaClass.skipTraverse = false
}
eventType.skipTraverse
}
switch (eventType) {
case LOAD:
// Skip traverse
if (skipTraverse(LOAD)) {
LOAD.skipTraverse = false // reset the flag
return
}
dir = project.projectProperties.sourceRoot
replacePair = [
[find: /"eng-USA"/, replacement: /"en-US"/],
[find: /"fra-FRA"/, replacement: /"fr-FR"/]
]
break
case COMPILE:
dir = project.projectProperties.targetRoot
replacePair = [
[find: /"en-US"/, replacement: /"eng-USA"/],
[find: /"fr-FR"/, replacement: /"fra-FRA"/],
]
break
default:
return null // No output
}
String ENCODING = 'UTF-8'
File rootDir = new File(dir)
int modifiedFiles = 0
// options as map
def options = [
type : groovy.io.FileType.FILES,
nameFilter : ~/.*\.xlf/
]
// replacer as closure
def replacer = {file ->
String text = file.getText ENCODING
String replaced = text
replacePair.each {replaced = replaced.replaceAll it.find, it.replacement}
if (text != replaced) {
file.setText replaced, ENCODING
console.println "modified: $file"
modifiedFiles++
}
}
def reloadProjectOnetime = {
LOAD.skipTraverse = true // avoid potentially infinity reloading loop
javax.swing.SwingUtilities.invokeLater({
org.omegat.gui.main.ProjectUICommands.projectReload()
} as Runnable)
}
// do replace
rootDir.traverse options, replacer
if (modifiedFiles > 0 && eventType == LOAD) {
console.println "$modifiedFiles file(s) modified."
reloadProjectOnetime()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment