chimpler/pyhocon

No resolveWith funtion as the java lib

borissmidt opened this issue · 2 comments

I couldn't find any feature that would give me the same behavior as the java resolveWith function.

//application.conf
kafka = ${kafka}

and another config

//services.conf
kafka {
 url = "localhost:9092"
}
val common = ConfigFactory.parseFile(new File("common.conf"))
val application = ConfigFactory.parseFile(new File("application.conf"))
val resolved = application.resolveWith(common).root

println(resolved.render())

//result: 
// kafka.url = localhost:9092

In python i was able to do this but it doesn't really resolve in a 'join' operation and more like a union operation.
Maybe i could take the keys out of the the application and then filter it out of the resolved config.

conf: ConfigTree= ConfigFactory.parse_file("common.conf")
conf2: ConfigTree= ConfigFactory.parse_file("application.conf",resolve=False)
keys = conf2.keys()
resolved = conf2.with_fallback("application.conf")

// result: 
// kafka.url = localhost:9092
// some-other-config = "i should not be here"

a merge type parameter seems to be able to resolve that:

def merge_configs(a, b, copy_trees=False, union_merge = True):
    """Merge config b into a

    :param a: target config
    :type a: ConfigTree
    :param b: source config
    :type b: ConfigTree
    :return: merged config a
    """
    for key, value in b.items():
        if union_merge or key in a:
            # if key is in both a and b and both values are dictionary then merge it otherwise override it
            if key in a and isinstance(a[key], ConfigTree) and isinstance(b[key], ConfigTree):
                if copy_trees:
                    a[key] = a[key].copy()
                merge_configs(a[key], b[key], copy_trees=copy_trees, union_merge = union_merge)
            else:
                if isinstance(value, ConfigValues):
                    value.parent = a
                    value.key = key
                    if key in a:
                        value.overriden_value = a[key]
                a[key] = value
                if a.root:
                    if b.root:
                        a.history[key] = a.history.get(key, []) + b.history.get(key, [value])
                    else:
                        a.history[key] = a.history.get(key, []) + [value]

    return a

fixed by #266