Project

General

Profile

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 1123 aaronmk
def col_label(col_name): return col_name.partition(':')[0]
14
15 1125 aaronmk
def overlaps(str0, str1): return str0.find(str1) >= 0 or str1.find(str0) >= 0
16
17 187 aaronmk
def main():
18 1123 aaronmk
    ignore = opts.env_flag('ignore')
19 187 aaronmk
    try: _prog_name, map_1_path = sys.argv
20
    except ValueError:
21 1123 aaronmk
        raise SystemExit('Usage: env [ignore=1] '+sys.argv[0]
22
            +' <map_0 map_1 [| '+sys.argv[0]+' map_2]... >union_map')
23 187 aaronmk
24 1125 aaronmk
    headers = [None]*2
25 187 aaronmk
26 1125 aaronmk
    # Open map 0
27
    map_0_reader = csv.reader(sys.stdin)
28
    headers[0] = map_0_reader.next()
29
30
    # Open map 1
31 187 aaronmk
    stream = open(map_1_path, 'rb')
32 1125 aaronmk
    map_1_reader = csv.reader(stream)
33
    headers[1] = map_1_reader.next()
34 187 aaronmk
35 1125 aaronmk
    # Check col labels
36
    combinable = overlaps(*[col_label(header[0]) for header in headers])
37
    if not combinable and not ignore: raise SystemExit('Map error: '
38
        'Map 0 column 0 label doesn\'t contain map 1 column 0 label')
39 187 aaronmk
40 1125 aaronmk
    # Pass through map 0, storing which inputs it defines
41 187 aaronmk
    writer = csv.writer(sys.stdout)
42 1125 aaronmk
    writer.writerow(headers[0])
43
    inputs = set()
44
    for row in map_0_reader:
45
        if row[0] != '': inputs.add(row[0])
46
        writer.writerow(row)
47
48
    if combinable:
49
        # Add entries in map 1 that weren't already defined
50
        for row in map_1_reader:
51
            if row[0] != '' and row[0] not in inputs: writer.writerow(row)
52
53
    stream.close()
54 187 aaronmk
55
main()