1 |
187
|
aaronmk
|
#!/usr/bin/env python
|
2 |
926
|
aaronmk
|
# Combines two map spreadsheets A0->B and A1->C to A->B, with B overwriting C
|
3 |
187
|
aaronmk
|
|
4 |
|
|
import csv
|
5 |
738
|
aaronmk
|
import os.path
|
6 |
187
|
aaronmk
|
import sys
|
7 |
|
|
|
8 |
738
|
aaronmk
|
sys.path.append(os.path.dirname(__file__)+"/../lib")
|
9 |
|
|
|
10 |
|
|
import maps
|
11 |
1123
|
aaronmk
|
import opts
|
12 |
738
|
aaronmk
|
|
13 |
187
|
aaronmk
|
def main():
|
14 |
1123
|
aaronmk
|
ignore = opts.env_flag('ignore')
|
15 |
1127
|
aaronmk
|
header_num = int(opts.get_env_var('header_num', 0))
|
16 |
|
|
# selects which map's header to use as the output header
|
17 |
187
|
aaronmk
|
try: _prog_name, map_1_path = sys.argv
|
18 |
|
|
except ValueError:
|
19 |
1127
|
aaronmk
|
raise SystemExit('Usage: env [ignore=1] [header_num={0|1}] '+sys.argv[0]
|
20 |
1123
|
aaronmk
|
+' <map_0 map_1 [| '+sys.argv[0]+' map_2]... >union_map')
|
21 |
187
|
aaronmk
|
|
22 |
1125
|
aaronmk
|
headers = [None]*2
|
23 |
187
|
aaronmk
|
|
24 |
1125
|
aaronmk
|
# Open map 0
|
25 |
|
|
map_0_reader = csv.reader(sys.stdin)
|
26 |
|
|
headers[0] = map_0_reader.next()
|
27 |
|
|
|
28 |
|
|
# Open map 1
|
29 |
187
|
aaronmk
|
stream = open(map_1_path, 'rb')
|
30 |
1125
|
aaronmk
|
map_1_reader = csv.reader(stream)
|
31 |
|
|
headers[1] = map_1_reader.next()
|
32 |
187
|
aaronmk
|
|
33 |
1125
|
aaronmk
|
# Check col labels
|
34 |
1507
|
aaronmk
|
combinable = maps.combinable(*headers)
|
35 |
|
|
if not combinable and not ignore:
|
36 |
1502
|
aaronmk
|
raise SystemExit('Map error: '
|
37 |
1125
|
aaronmk
|
'Map 0 column 0 label doesn\'t contain map 1 column 0 label')
|
38 |
187
|
aaronmk
|
|
39 |
1125
|
aaronmk
|
# Pass through map 0, storing which inputs it defines
|
40 |
187
|
aaronmk
|
writer = csv.writer(sys.stdout)
|
41 |
1127
|
aaronmk
|
writer.writerow(headers[header_num])
|
42 |
1125
|
aaronmk
|
inputs = set()
|
43 |
|
|
for row in map_0_reader:
|
44 |
|
|
if row[0] != '': inputs.add(row[0])
|
45 |
|
|
writer.writerow(row)
|
46 |
|
|
|
47 |
|
|
if combinable:
|
48 |
|
|
# Add entries in map 1 that weren't already defined
|
49 |
|
|
for row in map_1_reader:
|
50 |
|
|
if row[0] != '' and row[0] not in inputs: writer.writerow(row)
|
51 |
|
|
|
52 |
|
|
stream.close()
|
53 |
187
|
aaronmk
|
|
54 |
|
|
main()
|