Project

General

Profile

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