Project

General

Profile

1
# Map spreadsheet manipulation
2

    
3
import re
4

    
5
import Parser
6
import strings
7
import util
8

    
9
def col_info(col_name, require_root=False):
10
    '''@return tuple (label, root, prefixes)'''
11
    def syntax_err(): raise Parser.SyntaxException('Column name must have '
12
        'syntax "datasrc[format,...]:root" (formats optional): '+col_name)
13
    
14
    match = re.match(r'^([^\[:]*)(?:\[([^\]]*?)\])?(?::(.*))?$', col_name)
15
    if not match: syntax_err()
16
    label, prefixes, root = match.groups()
17
    if require_root and root == None: syntax_err()
18
    return label, root, strings.split(',', util.coalesce(prefixes, ''))
19

    
20
def col_formats(col_name):
21
    label, root, prefixes = col_info(col_name)
22
    return [label]+prefixes
23

    
24
def combinable(*headers):
25
    return strings.overlaps(*[','.join(col_formats(h[0])) for h in headers])
26

    
27
def is_nonexplicit_empty_mapping(row):
28
    return reduce(util.and_, (v == '' for v in row[1:]))
29

    
30
def merge_values(*vals):
31
    new = []
32
    for val in vals:
33
        if val != '' and val not in new: new.append(val)
34
    return '; '.join(new)
35

    
36
def merge_rows(*rows):
37
    '''e.g. ['a','b'] + ['','y','z'] = ['a','b; y','z']'''
38
    def get(row, i):
39
        try: return row[i]
40
        except IndexError: return ''
41
    return [merge_values(*[get(row, i) for row in rows])
42
        for i in xrange(max(map(len, rows)))]
43

    
44
def merge_mappings(in_, out):
45
    '''e.g. ['in','join','in_comments'] + ['join','out','out_comments'] =
46
    ['in','out','in_comments; out_comments']'''
47
    new = [in_[0], out[1]] # mapping
48
    new[2:] = merge_rows(in_[2:], out[2:]) # comments
49
    return new
(11-11/25)