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