forked from muggenhor/noweb.py
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbootstrap.py
executable file
·89 lines (64 loc) · 2.39 KB
/
bootstrap.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2010 Jonathan Aquino ([email protected])
# Copyright (c) 2014 Javier Escalada Gómez ([email protected])
import re
import codecs
OPEN = "<<"
CLOSE = ">>"
CHUNK = "(?:.*:)?([^>]+)"
def read(infile, encoding):
assert(infile)
assert(encoding)
chunks = {}
chunkName = None
with codecs.open(infile, "r", encoding=encoding) as f:
for line in f:
match = re.match(OPEN + CHUNK + CLOSE + "=", line)
if match:
chunkName = match.group(1)
chunks[chunkName] = []
else:
match = re.match("@", line)
if match:
chunkName = None
elif chunkName:
chunks[chunkName].append(line)
return chunks
def tangle(chunkName, chunks, indent):
assert(chunkName)
assert(chunks)
assert(indent != None)
chunkLines = chunks[chunkName]
expandedChunkLines = []
for line in chunkLines:
match = re.match("(\s*)" + OPEN + CHUNK + CLOSE + "\s*$", line)
if match:
expandedChunkLines.extend(tangle(match.group(2), chunks, indent + match.group(1)))
else:
expandedChunkLines.append(indent + line)
return expandedChunkLines
def write(lines, chunkName, output, encoding):
assert(lines)
assert(chunkName)
assert(output)
with codecs.open(output, "w", encoding=encoding) as f:
for line in lines:
f.write(line)
def main():
import argparse
cmd_line_parser = argparse.ArgumentParser('Bootstrap NoWeb command line options.')
cmd_line_parser.add_argument('infile', metavar='FILE',
help='input file to process, "-" for stdin')
cmd_line_parser.add_argument('-o', '--output', metavar='FILE', default='-',
help='file to output to, "-" for stdout (default: %(default)s)')
cmd_line_parser.add_argument('-e', '--encoding', metavar='ENCODING', default='utf-8',
help='Input and output encoding (default: %(default)s)')
cmd_line_parser.add_argument('-R', '--chunk', metavar='CHUNK',
help='name of chunk to write to stdout')
args = cmd_line_parser.parse_args()
chunks = read(args.infile, args.encoding)
lines = tangle(args.chunk, chunks, "")
write(lines, args.chunk, args.output, args.encoding)
if __name__ == "__main__":
exit(main())