sphinks
sphinks

Reputation: 3128

How to iterate over all config entries on Groovy?

I have a groovy scipt which play a config role in my app. It is structure will be such:

a{
     b=val1
     c{
          d=val2
     }
 }
e{
     f=val3
 }

How can I iterate over enties in this config to separate setting of one root from setting of another root? I mean such way of iteration where I will be able to determine root positions, something like this:

 a (root)
 b
 c (subroot)
 d
 e (root)
 f

And config level not limited by 2 level, so iterate using simple inner 'for' cycles is not suitable, cause I don't how many level will be on compilation.

Upvotes: 0

Views: 870

Answers (1)

tim_yates
tim_yates

Reputation: 171114

You mean like this?

Given a configuration:

def cfg = '''
a {
    b = 'val1'
    c {
        d = 'val2'
    }
}
e {
    f = 'val3'
}'''

You can define a recursive walk method like so:

def walk( map, root=true ) {
    map.each { key, value ->
        if( value instanceof Map ) {
            println "$key (${root?'root':'subroot'})"
            walk( value, false )
        }
        else {
            println "$key"
        }
    }
}

Then call the function, passing in the slurped config:

walk( new ConfigSlurper().parse( cfg ) )

This prints:

a (root)
b
c (subroot)
d
e (root)
f

You can also have your config in a file (in this example, Config.groovy)

Then, you can change the walk call to:

walk( new ConfigSlurper().parse( Config ) )

And it will output the same

Upvotes: 2

Related Questions