Skip to content

Commit eeaa42e

Browse files
committed
scripts: add copy-examples
This is a preliminary script to copy example code from a Markdown file into a crate's example directory. This is intended to be used for the upcoming libripgrep guide, but we don't commit any examples yet.
1 parent 3797a2a commit eeaa42e

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

scripts/copy-examples

+33
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#!/usr/bin/env python
2+
3+
from __future__ import absolute_import, division, print_function
4+
import argparse
5+
import codecs
6+
import os.path
7+
import re
8+
9+
RE_EACH_CODE_BLOCK = re.compile(
10+
r'(?s)(?:```|\{\{< high rust[^>]+>\}\})[^\n]*\n(.*?)(?:```|\{\{< /high >\}\})' # noqa
11+
)
12+
RE_MARKER = re.compile(r'^(?:# )?//([^/].*)$')
13+
RE_STRIP_COMMENT = re.compile(r'^# ?')
14+
15+
if __name__ == '__main__':
16+
p = argparse.ArgumentParser()
17+
p.add_argument('--rust-file', default='src/cookbook.rs')
18+
p.add_argument('--example-dir', default='grep/examples')
19+
args = p.parse_args()
20+
21+
with codecs.open(args.rust_file, encoding='utf-8') as f:
22+
rustcode = f.read()
23+
for m in RE_EACH_CODE_BLOCK.finditer(rustcode):
24+
lines = m.group(1).splitlines()
25+
marker, codelines = lines[0], lines[1:]
26+
m = RE_MARKER.search(marker)
27+
if m is None:
28+
continue
29+
30+
code = '\n'.join(RE_STRIP_COMMENT.sub('', line) for line in codelines)
31+
fpath = os.path.join(args.example_dir, m.group(1))
32+
with codecs.open(fpath, mode='w+', encoding='utf-8') as f:
33+
print(code, file=f)

0 commit comments

Comments
 (0)