spaCy/website/create_code_samples

66 lines
1.8 KiB
Plaintext
Raw Normal View History

2015-09-25 12:52:14 +03:00
#!/usr/bin/env python
import sys
import re
import os
import ast
2015-09-28 03:39:14 +03:00
# cgi.escape is deprecated since py32
try:
from html import escape
except ImportError:
from cgi import escape
2015-09-25 12:52:14 +03:00
src_dirname = sys.argv[1]
dst_dirname = sys.argv[2]
prefix = "test_"
for filename in os.listdir(src_dirname):
2015-09-28 15:22:13 +03:00
match = re.match(re.escape(prefix) + r"(.+)\.py$", filename)
2015-09-25 12:52:14 +03:00
if not match:
continue
name = match.group(1)
source = open(os.path.join(src_dirname, filename)).readlines()
tree = ast.parse("".join(source))
2015-09-28 15:22:13 +03:00
for root in tree.body:
if isinstance(root, ast.FunctionDef) and root.name.startswith(prefix):
2015-09-25 12:52:14 +03:00
# only ast.expr and ast.stmt have line numbers, see:
# https://docs.python.org/2/library/ast.html#ast.AST.lineno
2015-09-28 03:39:14 +03:00
line_numbers = []
2015-09-28 15:22:13 +03:00
for node in ast.walk(root):
if hasattr(node, "lineno"):
line_numbers.append(node.lineno)
2015-09-28 03:39:14 +03:00
2015-09-25 12:52:14 +03:00
body = source[min(line_numbers)-1:max(line_numbers)]
2015-09-28 15:22:13 +03:00
while not body[0][0].isspace():
body = body[1:]
2015-09-25 12:52:14 +03:00
# make sure we are inside an indented function body
2015-09-28 15:22:13 +03:00
assert all([l[0].isspace() for l in body])
2015-09-25 12:52:14 +03:00
offset = 0
for line in body:
match = re.search(r"[^\s]", line)
if match:
offset = match.start(0)
2015-09-28 03:39:14 +03:00
break
2015-09-25 12:52:14 +03:00
# remove indentation
assert offset > 0
for i in range(len(body)):
body[i] = body[i][offset:] if len(body[i]) > offset else "\n"
# make sure empty lines contain a newline
assert all([l[-1] == "\n" for l in body])
2015-09-28 15:22:13 +03:00
code_filename = "%s.%s" % (name, root.name[len(prefix):])
2015-09-25 12:52:14 +03:00
with open(os.path.join(dst_dirname, code_filename), "w") as f:
2015-09-28 03:39:14 +03:00
f.write(escape("".join(body)))