]> git.lizzy.rs Git - rust.git/blob - src/etc/extract-tests.py
e95c6680f999bc3ca4fb327ed38657cef89e8b3b
[rust.git] / src / etc / extract-tests.py
1 # Script for extracting compilable fragments from markdown
2 # documentation. See prep.js for a description of the format
3 # recognized by this tool. Expects a directory fragements/ to exist
4 # under the current directory, and writes the fragments in there as
5 # individual .rs files.
6
7 import sys, re;
8
9 if len(sys.argv) < 3:
10     print("Please provide an input filename")
11     sys.exit(1)
12
13 filename = sys.argv[1]
14 dest = sys.argv[2]
15 f = open(filename)
16 lines = f.readlines()
17 f.close()
18
19 cur = 0
20 line = ""
21 chapter = ""
22 chapter_n = 0
23
24 while cur < len(lines):
25     line = lines[cur]
26     cur += 1
27     chap = re.match("# (.*)", line);
28     if chap:
29         chapter = re.sub(r"\W", "_", chap.group(1)).lower()
30         chapter_n = 1
31     elif re.match("~~~", line):
32         # Parse the tags that open a code block in the pandoc format:
33         # ~~~ {.tag1 .tag2}
34         tags = re.findall("\.([\w-]*)", line)
35         block = ""
36         ignore = "notrust" in tags or "ignore" in tags
37         xfail = "xfail-test" in tags
38         while cur < len(lines):
39             line = lines[cur]
40             cur += 1
41             if re.match("~~~", line):
42                 break
43             else:
44                 block += re.sub("^# ", "", line)
45         if not ignore:
46             if not re.search(r"\bfn main\b", block):
47                 if re.search(
48                     r"(^|\n) *(native|use|mod|import|export)\b", block):
49                     block += "\nfn main() {}\n"
50                 else:
51                     block = "fn main() {\n" + block + "\n}\n"
52             if not re.search(r"\buse std\b", block):
53                 block = "use std;\n" + block;
54             if xfail:
55                 block = "// xfail-test\n" + block
56             filename = (dest + "/" + str(chapter)
57                         + "_" + str(chapter_n) + ".rs")
58             chapter_n += 1
59             f = open(filename, 'w')
60             f.write(block)
61             f.close()