Project

General

Profile

1 68 aaronmk
#!/usr/bin/env python
2 69 aaronmk
# Transforms a map spreadsheet to use a different root
3 68 aaronmk
4
import csv
5
import os.path
6 72 aaronmk
import re
7 68 aaronmk
import sys
8
9
sys.path.append(os.path.dirname(__file__)+"/../lib")
10
11 1705 aaronmk
import maps
12 68 aaronmk
import opts
13
14
def main():
15 69 aaronmk
    # Get config from env vars
16 68 aaronmk
    env_names = []
17 933 aaronmk
    print_usage_ref = [False]
18
    def on_unset(e): print_usage_ref[0] = True
19
    configs = [opts.get_env_vars(['in_root', 'out_root'], col, env_names,
20
        on_unset) for col in ['left', 'right']]
21
    if print_usage_ref[0]: raise SystemExit(
22 69 aaronmk
        'Usage: '+opts.env_usage(env_names)+' '+sys.argv[0]+' <in_map >out_map')
23 68 aaronmk
24
    # Transform map
25
    reader = csv.reader(sys.stdin)
26
    writer = csv.writer(sys.stdout)
27 69 aaronmk
    cols = reader.next()
28 70 aaronmk
    for i in xrange(len(configs)):
29 69 aaronmk
        config = configs[i]
30 3757 aaronmk
        cols[i], config['root'] = maps.col_info(cols[i])[:2]
31
32
        if config['root'] != None: cols[i] += ':'+config['out_root']
33
        else:
34
            assert config['out_root'] == ''
35
            config['root'] = ''
36
37 503 aaronmk
        config['in_root_re'] = r'^'+re.escape(config['in_root'])+r'(?=\b|\W|$)'
38 69 aaronmk
    writer.writerow(cols)
39 68 aaronmk
    for row in reader:
40 72 aaronmk
        def sub(i):
41 928 aaronmk
            row[i], n = re.subn(configs[i]['in_root_re'], r'',
42
                configs[i]['root']+row[i])
43 72 aaronmk
            return n > 0
44 3723 aaronmk
        if row[0] != '' and sub(0) and (row[1] == '' or sub(1)):
45 68 aaronmk
            writer.writerow(row)
46
47
main()