-
Notifications
You must be signed in to change notification settings - Fork 0
/
fix_generated.py
executable file
·72 lines (60 loc) · 2.43 KB
/
fix_generated.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import re
GENERATED_FILES_DIR = 'generated/cowboy'
PATHS_INDEX_FILE = 'paths/index.yaml'
OPERATIONS_RE = re.compile(r'(?<=(\[|,)\n)'
r'(?P<operation>\s+%%.+?\{<<"(?P<path>.+?)">>.+?\},?\n)'
r'(?=\s*(%%|\]))', flags=re.DOTALL)
REST_API_RE = re.compile(r'^(?P<header>.*?\[\n).*\n(?P<footer>\s*]\..*)$',
flags=re.DOTALL)
with open(PATHS_INDEX_FILE, "r") as f:
ordered_paths = [re.sub(r'{(.*?)}', ':\g<1>', line.rstrip(':\n'))
for line in f
if line.startswith('/') and line.endswith(':\n')]
for n in os.listdir(GENERATED_FILES_DIR):
if n.startswith('.'):
continue
with open(os.path.join(GENERATED_FILES_DIR, n), "r+") as f:
# Fix multiline comments.
lines = f.readlines()
new_lines = []
for line in lines:
if '\\n' in line.rstrip():
pos = line.find('%%')
if pos >= 0:
parts = filter(lambda p: p, line[pos + 3:].rstrip().split('\\n'))
parts = map(lambda p: ' ' * pos + '%% ' + p + '\n', parts)
new_lines.extend(parts)
else:
new_lines.append(line)
else:
new_lines.append(line)
lines = ''.join(new_lines)
# Fix paths ordering
header, footer = REST_API_RE.match(lines).groups()
rest_routes = {}
for rest_route in OPERATIONS_RE.finditer(lines):
path = rest_route.group('path')
operation = rest_route.group('operation')
try:
val = rest_routes[path]
except KeyError:
rest_routes[path] = operation
else:
rest_routes[path] = val + operation
else:
operations = ''.join(rest_routes[path]
for path in ordered_paths
if path in rest_routes)
lines = header + operations + footer
# Fix syntax and substitute invalid character sequences.
lines = re.sub(r',(\s*[}\]\)])', '\g<1>', lines)
lines = re.sub('\\&\\#39\\;', '\'', lines)
lines = re.sub('\\&\\#x3D\\;\\>\\;', '=>', lines)
lines = re.sub('\\&\\#x60\\;', '`', lines)
# Write new file.
f.seek(0)
f.truncate()
f.write(lines)