1
|
#!/usr/bin/env python
|
2
|
# Transforms a map spreadsheet to use a different root
|
3
|
|
4
|
import csv
|
5
|
import os.path
|
6
|
import re
|
7
|
import sys
|
8
|
|
9
|
sys.path.append(os.path.dirname(__file__)+"/../lib")
|
10
|
|
11
|
import maps
|
12
|
import opts
|
13
|
|
14
|
def main():
|
15
|
# Get config from env vars
|
16
|
env_names = []
|
17
|
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
|
'Usage: '+opts.env_usage(env_names)+' '+sys.argv[0]+' <in_map >out_map')
|
23
|
|
24
|
# Transform map
|
25
|
reader = csv.reader(sys.stdin)
|
26
|
writer = csv.writer(sys.stdout)
|
27
|
cols = reader.next()
|
28
|
for i in xrange(len(configs)):
|
29
|
config = configs[i]
|
30
|
label, config['root'] = maps.col_info(cols[i], require_root=True)[:2]
|
31
|
cols[i] = label+':'+config['out_root']
|
32
|
config['in_root_re'] = r'^'+re.escape(config['in_root'])+r'(?=\b|\W|$)'
|
33
|
writer.writerow(cols)
|
34
|
for row in reader:
|
35
|
def sub(i):
|
36
|
row[i], n = re.subn(configs[i]['in_root_re'], r'',
|
37
|
configs[i]['root']+row[i])
|
38
|
return n > 0
|
39
|
if row[0] != '' and sub(0):
|
40
|
if row[1] != '' and not sub(1): raise SystemExit('Map error: Root "'
|
41
|
+configs[1]['in_root']+'" is not contained in output mapping: '
|
42
|
+row[1])
|
43
|
writer.writerow(row)
|
44
|
|
45
|
main()
|