Project

General

Profile

1
#!/usr/bin/env python
2
# Transforms a map spreadsheet to use a different root.
3
# Warning: ch_root is usually *not* an idempotent operation.
4

    
5
import csv
6
import os.path
7
import re
8
import sys
9

    
10
sys.path.append(os.path.dirname(__file__)+"/../lib")
11

    
12
import maps
13
import opts
14

    
15
def main():
16
    # Get config from env vars
17
    env_names = []
18
    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
        'Usage: '+opts.env_usage(env_names)+' '+sys.argv[0]+' <in_map >out_map')
24
    
25
    # Transform map
26
    reader = csv.reader(sys.stdin)
27
    writer = csv.writer(sys.stdout)
28
    cols = reader.next()
29
    for i in xrange(len(configs)):
30
        config = configs[i]
31
        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
        config['in_root_re'] = r'^'+re.escape(config['in_root'])+r'(?=\b|\W|$)'
39
    writer.writerow(cols)
40
    for row in reader:
41
        def sub(i):
42
            row[i], n = re.subn(configs[i]['in_root_re'], r'',
43
                configs[i]['root']+row[i])
44
            return n > 0
45
        if row[0] != '' and sub(0) and (row[1] == '' or sub(1)):
46
            writer.writerow(row)
47

    
48
main()
(2-2/53)