user801116
user801116

Reputation:

How to merge 2 groovy configuration files which are in the form of groovy scripts?

I want to merge 2 groovy configuration files. Is there a way to write back to groovy's configuration file? Suppose I create a temp config file which contains only the changes (addition/modification) and then append it or alter the target configuration file (Not sure if there is a config writer in groovy to change existing entries in groovy config file.)

Or is there any other way? Please help

Example target groovy configuration 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 configuration file which contains only the 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
}

Upvotes: 3

Views: 1668

Answers (1)

cfrick
cfrick

Reputation: 37063

Assuming, that you allready use a ConfigSlurper. The resulting ConfigObject has a merge method. So you can e.g.:

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"

Upvotes: 3

Related Questions