codes_filter_configs.py 1.82 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
#!/usr/bin/python2.7

import configurator as conf
from sys import stdout
import argparse

def main():
    args = parse_args()

    # load and check the module
    mod = conf.import_from(args.substitute_py)
    conf.check_cfields(mod)

    # check that pairs are actually pairs
    tp = args.token_pairs
    if len(tp) % 2 != 0:
        raise ValueError("token pairs must come in twos")

    # intitialize the configuration object 
    cfg = conf.configurator(mod, [])

    # build a lookup structure for the pairs, converting to numbers if 
    # possible
    tdict = { }
    for i in range(0, len(tp), 2):
        v = conf.try_num(tp[i+1])
        if v == None:
            v = tp[i+1]
        tdict[tp[i]] = v

    # quick check - make sure pairs are actually in the config
    for k in tdict:
        if k not in cfg.replace_map:
            raise ValueError("key " + k + " not in original config")

    # filter out the files
    # (cfg iterator returns nothing, eval'd for side effects)
    for i,_ in enumerate(cfg):
        for k in tdict:
            if tdict[k] != cfg.replace_map[k]:
                break
        else:
            stdout.write(args.output_prefix + "." + str(i) + "\n")

def parse_args():
    parser = argparse.ArgumentParser(\
            description="emit configuration files to stdout matching given "
            "token values")
    parser.add_argument("output_prefix", help="prefix of output config files")
    parser.add_argument("substitute_py", 
            help="input python file given to codes_configurator.py - see "
            "codes_configurator.py for details")
    parser.add_argument("token_pairs", nargs='*',
            help="a list of whitespace-separated token, replace pairs to "
            "filter the set of generated configuration files by")
    return parser.parse_args()

if __name__ == "__main__":
    main()