summaryrefslogtreecommitdiff
path: root/extra/update_comments_from_spec.py
blob: f4d470cdf61c0d886708210af6ad1d6a7cfd70ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import os
import sys
import re

default_source_file = os.path.join(
    os.path.dirname(__file__),
    '../amqp/channel.py',
)

RE_COMMENTS = re.compile(
    r'(?P<methodsig>def\s+(?P<mname>[a-zA-Z0-9_]+)\(.*?\)'
    ':\n+\\s+""")(?P<comment>.*?)(?=""")',
    re.MULTILINE | re.DOTALL
)

USAGE = """\
Usage: %s <comments-file> <output-file> [<source-file>]\
"""


def update_comments(comments_file, impl_file, result_file):
    text_file = open(impl_file)
    source = text_file.read()

    comments = get_comments(comments_file)
    for def_name, comment in comments.items():
        source = replace_comment_per_def(
            source, result_file, def_name, comment
        )

    new_file = open(result_file, 'w+')
    new_file.write(source)


def get_comments(filename):
    text_file = open(filename)
    whole_source = text_file.read()
    comments = {}

    all_matches = RE_COMMENTS.finditer(whole_source)
    for match in all_matches:
        comments[match.group('mname')] = match.group('comment')
        #  print('method: %s \ncomment: %s' % (
        #        match.group('mname'), match.group('comment')))

    return comments


def replace_comment_per_def(source, result_file, def_name, new_comment):
    regex = (r'(?P<methodsig>def\s+' +
             def_name +
             '\\(.*?\\):\n+\\s+""".*?\n).*?(?=""")')
    #  print('method and comment:' + def_name + new_comment)
    result = re.sub(regex, r'\g<methodsig>' + new_comment, source, 0,
                    re.MULTILINE | re.DOTALL)
    return result


def main(argv=None):
    if argv is None:
        argv = sys.argv

    if len(argv) < 3:
        print(USAGE % argv[0])
        return 1

    impl_file = default_source_file
    if len(argv) >= 4:
        impl_file = argv[3]

    update_comments(argv[1], impl_file, argv[2])

if __name__ == '__main__':
    sys.exit(main())