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 |
|
|
import opts
|
12 |
|
|
|
13 |
|
|
def main():
|
14 |
69
|
aaronmk
|
# Get config from env vars
|
15 |
68
|
aaronmk
|
env_names = []
|
16 |
933
|
aaronmk
|
print_usage_ref = [False]
|
17 |
|
|
def on_unset(e): print_usage_ref[0] = True
|
18 |
|
|
configs = [opts.get_env_vars(['in_root', 'out_root'], col, env_names,
|
19 |
|
|
on_unset) for col in ['left', 'right']]
|
20 |
|
|
if print_usage_ref[0]: raise SystemExit(
|
21 |
69
|
aaronmk
|
'Usage: '+opts.env_usage(env_names)+' '+sys.argv[0]+' <in_map >out_map')
|
22 |
68
|
aaronmk
|
|
23 |
|
|
# Transform map
|
24 |
|
|
reader = csv.reader(sys.stdin)
|
25 |
|
|
writer = csv.writer(sys.stdout)
|
26 |
69
|
aaronmk
|
cols = reader.next()
|
27 |
70
|
aaronmk
|
for i in xrange(len(configs)):
|
28 |
69
|
aaronmk
|
config = configs[i]
|
29 |
72
|
aaronmk
|
label, sep, config['root'] = cols[i].partition(':')
|
30 |
|
|
cols[i] = label+sep+config['out_root']
|
31 |
503
|
aaronmk
|
config['in_root_re'] = r'^'+re.escape(config['in_root'])+r'(?=\b|\W|$)'
|
32 |
69
|
aaronmk
|
writer.writerow(cols)
|
33 |
68
|
aaronmk
|
for row in reader:
|
34 |
72
|
aaronmk
|
def sub(i):
|
35 |
928
|
aaronmk
|
row[i], n = re.subn(configs[i]['in_root_re'], r'',
|
36 |
|
|
configs[i]['root']+row[i])
|
37 |
72
|
aaronmk
|
return n > 0
|
38 |
928
|
aaronmk
|
if row[0] != '' and sub(0):
|
39 |
|
|
if row[1] != '' and not sub(1): raise SystemExit('Map error: Root "'
|
40 |
72
|
aaronmk
|
+configs[1]['in_root']+'" is not contained in output mapping: '
|
41 |
|
|
+row[1])
|
42 |
68
|
aaronmk
|
writer.writerow(row)
|
43 |
|
|
|
44 |
|
|
main()
|