How to merge 2 groovy config files that are in the form of groovy scripts?
I want to combine 2 groovy config files. Is there a way to write to the groovy config file? Suppose I create a temp config file that only contains changes (add / modify) and then add it or modify the target config file (not sure if there is a config script in groovy to change existing entries in the groovy config file.)
Or is there another way? Please, help
Example target groovy config file
config {
name="agnis"
master {
name="Altis"
bitMode = 64
}
slave {
name="Geo"
bitMode = 64
}
}
datastore{
host="localhost"
port=12808
dbname="gcsapp"
users_collection="users"
}
defaultBookmarks{
track_url="http://apps1.alto.com/Scripts/Texcel/track.out"
vmware_url="https://example.com/ControlPanel/Configurations/AllConfigurations.aspx"
}
Example temp config file that contains only changes
config {
master {
name="Ajanta"
bitMode = 32
}
slave {
name="Galileo"
bitMode = 32
}
}
Working code
private boolean mergeFiles(def sourceFile, def targetFile) {
try {
def srcConfig = new ConfigSlurper().parse(new File(sourceFile).toURI().toURL())
def tgtConfig = new ConfigSlurper().parse(new File(targetFile).toURI().toURL())
ConfigObject mergedConfig = (ConfigObject) tgtConfig.merge(srcConfig)
def stringWriter = new StringWriter()
mergedConfig.writeTo(stringWriter)
def file = new File(targetFile)
file.write(stringWriter.toString())
} catch(Exception e) {
println e.printStackTrace()
return false
}
return true
}
+3
source to share
1 answer
Assuming you are already using ConfigSlurper
. The resulting ConfigObject
method merge
. So you can, for example:
def c = new ConfigSlurper().parse("""\
config {
name="agnis"
master {
name="Altis"
bitMode = 64
}
slave {
name="Geo"
bitMode = 64
}
}
""")
assert c.config.master.name=="Altis"
assert c.config.slave.name=="Geo"
def u = new ConfigSlurper().parse("""\
config {
master {
name="Ajanta"
bitMode = 32
}
}
""")
c.merge(u) // XXX
assert c.config.master.name=="Ajanta" // XXX
assert c.config.slave.name=="Geo"
+3
source to share