Project

General

Profile

1
#!/usr/bin/env python
2
# Combines two map spreadsheets A0->B and A1->C to A->B, with B overwriting C
3

    
4
import csv
5
import os.path
6
import sys
7

    
8
sys.path.append(os.path.dirname(__file__)+"/../lib")
9

    
10
import maps
11
import opts
12
import util
13

    
14
def main():
15
    ignore = opts.env_flag('ignore')
16
    header_num = util.cast(int, opts.get_env_var('header_num'))
17
        # selects which map's header to use as the output header
18
    try: _prog_name, map_1_path = sys.argv
19
    except ValueError:
20
        raise SystemExit('Usage: env [ignore=1] [header_num={0|1}] '+sys.argv[0]
21
            +' <map_0 map_1 [| '+sys.argv[0]+' map_2]... >union_map')
22
    
23
    headers = [None]*2
24
    
25
    # Open map 0
26
    map_0_reader = csv.reader(sys.stdin)
27
    headers[0] = map_0_reader.next()
28
    
29
    # Open map 1
30
    stream = open(map_1_path, 'rb')
31
    map_1_reader = csv.reader(stream)
32
    headers[1] = map_1_reader.next()
33
    
34
    # Check col labels
35
    combinable = maps.combinable(*headers)
36
    if not combinable and not ignore:
37
        raise SystemExit('Map error: '
38
        'Map 0 column 0 label doesn\'t contain map 1 column 0 label')
39
    
40
    # Pass through map 0, storing which inputs it defines
41
    writer = csv.writer(sys.stdout)
42
    writer.writerow(maps.merge_headers(*headers, **dict(prefer=header_num)))
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

    
55
main()
(42-42/46)