summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorAndrew Gallant <jamslam@gmail.com>2018-09-07 12:27:48 -0400
committerAndrew Gallant <jamslam@gmail.com>2018-09-07 12:27:48 -0400
commiteeaa42ecafbc4bad933bb0b12729eab9c60b63ce (patch)
treed06a1ca47d587dd95369a0306ddbb04adbd75871
parent3797a2a5cb2bd92cb6940d83fa3e61b2b570a473 (diff)
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.
-rwxr-xr-xscripts/copy-examples33
1 files changed, 33 insertions, 0 deletions
diff --git a/scripts/copy-examples b/scripts/copy-examples
new file mode 100755
index 00000000..e8eb2f24
--- /dev/null
+++ b/scripts/copy-examples
@@ -0,0 +1,33 @@
+#!/usr/bin/env python
+
+from __future__ import absolute_import, division, print_function
+import argparse
+import codecs
+import os.path
+import re
+
+RE_EACH_CODE_BLOCK = re.compile(
+ r'(?s)(?:```|\{\{< high rust[^>]+>\}\})[^\n]*\n(.*?)(?:```|\{\{< /high >\}\})' # noqa
+)
+RE_MARKER = re.compile(r'^(?:# )?//([^/].*)$')
+RE_STRIP_COMMENT = re.compile(r'^# ?')
+
+if __name__ == '__main__':
+ p = argparse.ArgumentParser()
+ p.add_argument('--rust-file', default='src/cookbook.rs')
+ p.add_argument('--example-dir', default='grep/examples')
+ args = p.parse_args()
+
+ with codecs.open(args.rust_file, encoding='utf-8') as f:
+ rustcode = f.read()
+ for m in RE_EACH_CODE_BLOCK.finditer(rustcode):
+ lines = m.group(1).splitlines()
+ marker, codelines = lines[0], lines[1:]
+ m = RE_MARKER.search(marker)
+ if m is None:
+ continue
+
+ code = '\n'.join(RE_STRIP_COMMENT.sub('', line) for line in codelines)
+ fpath = os.path.join(args.example_dir, m.group(1))
+ with codecs.open(fpath, mode='w+', encoding='utf-8') as f:
+ print(code, file=f)