Project

General

Profile

1 6620 aaronmk
#!/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
def simplify_url(url): return re.sub(r'\(.*?\)', r'', url)
14
15 6635 aaronmk
def url_comment_text(comment):
16
    if not comment: return comment
17
18
    match = re.match(r'^\((?:\d+:)?(.*?)\)$', comment)
19
    assert match
20
    text, = match.groups()
21
    return text
22
23 6620 aaronmk
def url_term(url):
24 6625 aaronmk
    match = re.search(r'[\w:-]+$', url)
25 6620 aaronmk
    assert match
26 6622 aaronmk
    return match.group(0)
27 6620 aaronmk
28
##### Redmine
29
30 6632 aaronmk
def redmine_bold(text): return '*'+text+'*'
31
32 6620 aaronmk
def redmine_url(text, url):
33
    if url: return '"'+text+'":'+url
34
    else: return text
35
36
def source2redmine_url(url):
37 6623 aaronmk
    if url: return redmine_url(url_term(url), simplify_url(url))
38
    else: return ''
39 6620 aaronmk
40
class RedmineTableWriter:
41
    '''Formats rows as a Redmine table'''
42
43
    def __init__(self, stream):
44
        self.stream = stream
45
46
    def writerow(self, row):
47
        self.stream.write(('|'.join(['']+row+['']))+'\n')
48
49
50
def main():
51 6633 aaronmk
    try: _prog_name, term_col, sources_col = sys.argv
52 6626 aaronmk
    except ValueError: raise SystemExit('Usage: '+sys.argv[0]
53 6633 aaronmk
        +' <spreadsheet term_col# sources_col# >redmine')
54
    term_col, sources_col = map(int, [term_col, sources_col])
55 6626 aaronmk
56 6632 aaronmk
    # Translate input
57 6620 aaronmk
    reader = csv.reader(sys.stdin)
58
    writer = RedmineTableWriter(sys.stdout)
59 6632 aaronmk
    writer.writerow(map(redmine_bold, reader.next())) # header
60 6620 aaronmk
    for row in reader:
61
        term = row[term_col]
62 6634 aaronmk
        sources = row[sources_col].split(source_sep)
63 6620 aaronmk
64 6634 aaronmk
        row[term_col] = redmine_url(term, simplify_url(sources[0]))
65 6632 aaronmk
        row[sources_col] = source_sep.join(map(source2redmine_url, sources))
66 6628 aaronmk
67 6632 aaronmk
        writer.writerow(row)
68 6620 aaronmk
69
main()