-
Notifications
You must be signed in to change notification settings - Fork 4
/
build_rawrst.py
executable file
·66 lines (53 loc) · 2.06 KB
/
build_rawrst.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
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
"""Build RST files to display raw files in Sphinx"""
import os
import os.path
import sys
# Templates
RAWRST_HEADER = """``{dirpath}/{filename}``
{underline}
:download:`Download file<{filename}>`
"""
def build_rawrst_file(dirpath, filename):
"""Build the corresponding raw RST file for filename in dirpath"""
if '/' in filename or '\\' in filename:
raise ValueError("Invalid filename: {}".format(filename))
content = RAWRST_HEADER
if filename.endswith(('.ico', '.jpg', '.png')):
content += '.. image:: {filename}\n :alt: {dirpath}/{filename}\n'
else:
content += '.. literalinclude:: {filename}\n'
if filename.endswith(('.htm', '.html')):
content += ' :language: html\n'
elif filename.endswith(('.ini', '.inf')):
content += ' :language: ini\n'
elif 'apache' in filename:
content += ' :language: apache\n'
elif 'lighttpd' in filename:
content += ' :language: lighttpd\n'
elif 'nginx' in filename:
content += ' :language: nginx\n'
else:
content += ' :language: sh\n'
content = content.format(
dirpath=dirpath,
filename=filename,
underline='=' * (len(dirpath) + len(filename) + 5))
with open(os.path.join(dirpath, filename + '.raw.rst'), 'w') as rstfd:
rstfd.write(content)
def build_rawrst_dir(dirpath):
"""Build all needed raw RST files under dirpath"""
for root, dirs, files in os.walk(dirpath):
# Filter-out hidden directories such as .vagrant
dirs[:] = [d for d in dirs if not d.startswith('.')]
for filename in files:
if filename.lower().endswith(('~', '.bak', '.rst')):
continue
# Ignore files already associated with a .rst
if os.path.exists(os.path.join(root, filename + '.rst')):
continue
build_rawrst_file(root, filename)
if __name__ == '__main__':
for directory in sys.argv:
build_rawrst_dir(directory)