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 operator
10
import os.path
11
import sys
12

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

    
15
import maps
16
import opts
17
import util
18

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

    
72
main()
(42-42/48)