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
# Multi-safe (supports an input appearing multiple times). Note that if there is
8
# *any* mapping for an input in subtract_map, all mappings for that input in
9
# from_map will be excluded.
10

    
11
import csv
12
import operator
13
import os.path
14
import sys
15

    
16
sys.path.append(os.path.dirname(__file__)+"/../lib")
17

    
18
import maps
19
import opts
20
import util
21

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

    
75
main()
(48-48/54)