1+ #! /usr/bin/env bash
2+ set -eo pipefail
3+ #
4+ # Extract code snippets from example files.
5+ #
6+ # Snippets are delimited by <doc:name> and </doc:name> tags.
7+ # Output: one file per snippet in the output directory.
8+ #
9+ # Usage:
10+ # ./extract-snippets.sh rust/src/main.rs snippets/rust
11+ # ./extract-snippets.sh js/index.mjs snippets/js
12+ #
13+
14+ INPUT=" ${1:? Usage: extract-snippets.sh <input-file> <output-dir>} "
15+ OUTDIR=" ${2:? Usage: extract-snippets.sh <input-file> <output-dir>} "
16+
17+ mkdir -p " $OUTDIR "
18+
19+ # Detect language from file extension
20+ EXT=" txt"
21+
22+ # Extract each <doc:name> ... </doc:name> block
23+ current_tag=" "
24+ current_file=" "
25+
26+ while IFS= read -r line; do
27+ # Check for opening tag
28+ if [[ " $line " =~ \< doc:([a-zA-Z0-9_-]+)\> ]]; then
29+ current_tag=" ${BASH_REMATCH[1]} "
30+ current_file=" $OUTDIR /${current_tag} .${EXT} "
31+ > " $current_file " # truncate
32+ continue
33+ fi
34+
35+ # Check for closing tag
36+ if [[ " $line " =~ \< /doc: ]]; then
37+ if [ -n " $current_file " ]; then
38+ echo " extracted: $current_tag -> $current_file "
39+ fi
40+ current_tag=" "
41+ current_file=" "
42+ continue
43+ fi
44+
45+ # Write line to current snippet (strip common leading whitespace)
46+ if [ -n " $current_file " ]; then
47+ echo " $line " >> " $current_file "
48+ fi
49+ done < " $INPUT "
50+
51+ # Clean up: strip common leading whitespace from each snippet
52+ for f in " $OUTDIR " /* ." $EXT " ; do
53+ [ -f " $f " ] || continue
54+ # Find minimum indentation (ignoring blank lines)
55+ min_indent=$( sed -n ' /[^ ]/{ s/^\( *\).*/\1/; p; }' " $f " | awk ' { print length }' | sort -n | head -1)
56+ if [ -n " $min_indent " ] && [ " $min_indent " -gt 0 ]; then
57+ if sed -i ' ' " s/^ \{1,$min_indent \}//" " $f " 2> /dev/null; then
58+ : # macOS sed
59+ else
60+ sed -i " s/^ \{1,$min_indent \}//" " $f " # Linux sed
61+ fi
62+ fi
63+ done
64+
65+ echo " Done: $( ls " $OUTDIR " /* ." $EXT " 2> /dev/null | wc -l | tr -d ' ' ) snippets extracted"
0 commit comments