Project

General

Profile

1
#!/usr/bin/env python
2
# Translates a data dictionary spreadsheet to Redmine formatting
3

    
4
import csv
5
import re
6
import sys
7

    
8
# Spreadsheet format
9
source_sep = ', '
10

    
11
##### URLs
12

    
13
url_comment_re = r'(?:\([^)]*\))'
14

    
15
def simplify_url(url): return re.sub(r'\(.*?\)', r'', url)
16

    
17
def url_comment_text(comment):
18
    if not comment: return comment
19
    
20
    match = re.match(r'^\(\d*:?(.*?)\)$', comment)
21
    assert match
22
    text, = match.groups()
23
    return text
24

    
25
def url_term(url):
26
    '''Prefixes any provider in the URL to the term name, to create a namespace.
27
    Each hierarchical component of the provider is stored in a URL comment.
28
    '''
29
    match = re.match(r'^('+url_comment_re+r'*).*?([\w:-]+)$', url)
30
    assert match
31
    provider_str, term = match.groups()
32
    provider = filter(bool, map(url_comment_text,
33
        re.findall(url_comment_re, provider_str)))
34
    
35
    return ':'.join(provider+[term])
36

    
37
##### Redmine
38

    
39
def redmine_bold(text): return '*'+text+'*'
40

    
41
def redmine_url(text, url):
42
    if url: return '"'+text+'":'+url
43
    else: return text
44

    
45
def source2redmine_url(url):
46
    if url: return redmine_url(url_term(url), simplify_url(url))
47
    else: return ''
48

    
49
class RedmineTableWriter:
50
    '''Formats rows as a Redmine table'''
51
    
52
    def __init__(self, stream):
53
        self.stream = stream
54
    
55
    def writerow(self, row):
56
        self.stream.write(('|'.join(['']+row+['']))+'\n')
57

    
58

    
59
def main():
60
    try: _prog_name, term_col, sources_col = sys.argv
61
    except ValueError: raise SystemExit('Usage: '+sys.argv[0]
62
        +' <spreadsheet term_col# sources_col# >redmine')
63
    term_col, sources_col = map(int, [term_col, sources_col])
64
    
65
    # Translate input
66
    reader = csv.reader(sys.stdin)
67
    writer = RedmineTableWriter(sys.stdout)
68
    writer.writerow(map(redmine_bold, reader.next())) # header
69
    for row in reader:
70
        term = row[term_col]
71
        sources = row[sources_col].split(source_sep)
72
        
73
        row[term_col] = redmine_url(term, simplify_url(sources[0]))
74
        row[sources_col] = source_sep.join(map(source2redmine_url, sources))
75
        
76
        writer.writerow(row)
77

    
78
main()
(13-13/69)