Project

General

Profile

1
#!/usr/bin/env python
2
# Subtracts map spreadsheet A1->C from A0->B to produce A->B.
3
# Other A0 entries are subtracted as well:
4
# - Empty entries without a comment documenting why they are empty, if there is
5
#   a matching entry in A1.
6
# - Entries whose input and output maps to the same non-empty value in A1
7

    
8
import csv
9
import os.path
10
import sys
11

    
12
sys.path.append(os.path.dirname(__file__)+"/../lib")
13

    
14
import maps
15
import opts
16
import util
17

    
18
def main():
19
    ignore = opts.env_flag('ignore')
20
    try: _prog_name, map_1_path = sys.argv[:2]
21
    except ValueError:
22
        raise SystemExit('Usage: env [ignore=1] '+sys.argv[0]+' <from_map '
23
            'subtract_map [compare_col_num...] [| '+sys.argv[0]
24
            +' subtract_map_2]... >difference_map')
25
    compare_col_nums = map(int, sys.argv[2:]) # 0-based
26
    if compare_col_nums == []:
27
        compare_col_nums = None # list_subset() value for all columns
28
    
29
    def compare_on(row): return tuple(util.list_subset(row, compare_col_nums))
30
    
31
    headers = [None]*2
32
    
33
    # Get map 1
34
    input_cols = set()
35
    compare_cols = set()
36
    map_ = dict()
37
    stream = open(map_1_path, 'rb')
38
    reader = csv.reader(stream)
39
    headers[1] = reader.next()
40
    for row in reader:
41
        if row[0] != '':
42
            input_cols.add(row[0])
43
            compare_cols.add(compare_on(row))
44
            if row[1] != '': map_[row[0]] = row[1]
45
    stream.close()
46
    
47
    # Open map 0
48
    reader = csv.reader(sys.stdin)
49
    headers[0] = reader.next()
50
    
51
    # Check col labels
52
    combinable = maps.combinable(*headers)
53
    if not combinable and not ignore:
54
        raise SystemExit('Map error: '
55
        'Map 0 column 0 label doesn\'t contain map 1 column 0 label')
56
    
57
    # Subtract map 1 from map 0
58
    writer = csv.writer(sys.stdout)
59
    writer.writerow(headers[0])
60
    for row in reader:
61
        if not combinable or not (
62
            (maps.is_nonexplicit_empty_mapping(row) and row[0] in input_cols)
63
            or compare_on(row) in compare_cols
64
            or util.have_same_value(map_, row[0], row[1]) # map to same place
65
            ):
66
            # not combinable or not in map 1
67
            writer.writerow(row)
68

    
69
main()
(41-41/47)