#!/usr/bin/python

import argparse
import xml.dom.minidom

def argument_parser():
    parser = argparse.ArgumentParser(
        description="merge GObject Introspection repository information.")
    parser.add_argument('files', nargs='+', type=str,
        help=".gir files to be merged")
    return parser


def main():
    args = argument_parser().parse_args()

    with open(args.files[0]) as f:
        gir = xml.dom.minidom.parse(f)

    namespaces = dict()
    for namespace in gir.getElementsByTagName('namespace'):
        namespaces[namespace.getAttribute('name')] = namespace

    for filename in args.files[1:]:
        with open(filename) as f:
            to_merge = xml.dom.minidom.parse(f)

            for namespace in to_merge.getElementsByTagName('namespace'):
                name = namespace.getAttribute('name')
                if namespace in namespaces:
                    for node in namespace.childNodes:
                        namespaces[name].insertBefore(node, None)
                else:
                    namespaces[name] = namespace

    print(gir.toxml())


main()
