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 3759 aaronmk
# Multi-safe (supports an input appearing multiple times). Note that if there is
4
# *any* mapping for an input in map_0, all mappings for that input in map_1 will
5
# be excluded.
6 187 aaronmk
7
import csv
8 738 aaronmk
import os.path
9 187 aaronmk
import sys
10
11 738 aaronmk
sys.path.append(os.path.dirname(__file__)+"/../lib")
12
13
import maps
14 1123 aaronmk
import opts
15 1769 aaronmk
import util
16 738 aaronmk
17 187 aaronmk
def main():
18 1123 aaronmk
    ignore = opts.env_flag('ignore')
19 1769 aaronmk
    header_num = util.cast(int, opts.get_env_var('header_num'))
20 1127 aaronmk
        # selects which map's header to use as the output header
21 187 aaronmk
    try: _prog_name, map_1_path = sys.argv
22
    except ValueError:
23 1127 aaronmk
        raise SystemExit('Usage: env [ignore=1] [header_num={0|1}] '+sys.argv[0]
24 1123 aaronmk
            +' <map_0 map_1 [| '+sys.argv[0]+' map_2]... >union_map')
25 187 aaronmk
26 1125 aaronmk
    headers = [None]*2
27 187 aaronmk
28 1125 aaronmk
    # Open map 0
29
    map_0_reader = csv.reader(sys.stdin)
30
    headers[0] = map_0_reader.next()
31
32
    # Open map 1
33 187 aaronmk
    stream = open(map_1_path, 'rb')
34 1125 aaronmk
    map_1_reader = csv.reader(stream)
35
    headers[1] = map_1_reader.next()
36 187 aaronmk
37 1125 aaronmk
    # Check col labels
38 1507 aaronmk
    combinable = maps.combinable(*headers)
39
    if not combinable and not ignore:
40 1502 aaronmk
        raise SystemExit('Map error: '
41 1125 aaronmk
        'Map 0 column 0 label doesn\'t contain map 1 column 0 label')
42 187 aaronmk
43 2023 aaronmk
    # Pass through map 0, storing which mappings it defines
44 187 aaronmk
    writer = csv.writer(sys.stdout)
45 1796 aaronmk
    writer.writerow(maps.merge_headers(*headers, **dict(prefer=header_num)))
46 2023 aaronmk
    mappings = set()
47 1125 aaronmk
    for row in map_0_reader:
48 2023 aaronmk
        if row[0] != '':
49
            mappings.add(row[0])
50
            if row[1] != '': mappings.add(row[1])
51 1125 aaronmk
        writer.writerow(row)
52
53
    if combinable:
54 2023 aaronmk
        # Add mappings in map 1 that weren't already defined or mapped to
55 1125 aaronmk
        for row in map_1_reader:
56 2023 aaronmk
            if row[0] != '' and row[0] not in mappings: writer.writerow(row)
57 1125 aaronmk
58
    stream.close()
59 187 aaronmk
60
main()