codes_configurator.py 2.38 KB
Newer Older
1 2 3 4
#!/usr/bin/python2.7

import os
import argparse
5
import configurator as conf
6 7 8 9 10 11 12 13

def main():
    args = parse_args()
    
    # load the template file
    tstr = open(args.template).read()

    # load the module
14
    mod = conf.import_from(args.substitute_py)
15

16
    # checks - make sure cfields is set and is the correct type 
17
    conf.check_cfields(mod)
18

19
    # check that pairs are actually pairs
20 21
    if len(args.token_pairs) % 2 != 0:
        raise ValueError("token pairs must come in twos")
22 23 24

    # intitialize the configuration object 
    cfg = conf.configurator(mod, args.token_pairs)
25

26 27 28 29 30
    # print the header to the log
    if args.log != None:
        flog = open(args.log, "w")
    else:
        flog = open(os.devnull, "w")
31 32
    
    cfg.write_header(flog)
33

34 35 36 37 38
    # main loop (cfg iterator returns nothing, eval'd for side effects)
    for i,_ in enumerate(cfg):
        new_config = conf.replace_many(tstr, cfg.replace_map)
        fname = template+"."+str(i) if args.output_prefix==None else \
            args.output_prefix+"."+str(i)
39 40
        with open(fname, "w") as fout:
            fout.write(new_config)
41 42 43
        
        # write this config to the log 
        cfg.write_config_line(i, flog)
44

45
    flog.close()
46 47

def parse_args():
48 49 50 51
    parser = argparse.ArgumentParser(\
            description="generate set of configuration files based on template "
                        "file and replacement tokens")
    parser.add_argument("template",
52
            help="template file with replace tokens")
53 54 55 56
    parser.add_argument("substitute_py",
            help='python file defining "cfields" variable consisting of '
                 'elements of the form '
                 '( replacement_token, [replacements...])')
57
    parser.add_argument("token_pairs", nargs='*',
58 59 60 61 62 63 64
            help="a list of whitespace-separated token, replace pairs for "
                 "command-line-driven replacement (useful in shell scripts "
                 "for generating sets of configuration files with a distinct "
                 "parameter or for special casing fields)")
    parser.add_argument("-l", "--log",
            help="log file to write parameterizations to")
    parser.add_argument("-o", "--output_prefix",
65 66 67 68 69 70
            help="prefix to output generated configuration files to "
                 "(default: the configuration index appended to the template name)")
    return parser.parse_args()

if __name__ == "__main__":
    main()