Files
diodeinc__pcb/bin/embed-readme
Akhil Velagapudi 89a05bfdb1 Clean up repository tooling (#1008)
Remove obsolete direnv and stale bin helpers.
2026-08-03 22:29:10 -04:00

98 lines
2.6 KiB
Bash
Executable File

#!/usr/bin/env bash
set -euo pipefail
# Embeds file contents into markdown code blocks
# Usage: embed-readme [-c|--check] <markdown-file>
#
# Directives:
# [embed-readme]:# (path/to/file language)
#
# The directive must be followed by a fenced code block which will be
# replaced with the contents of the referenced file.
check_mode=false
if [[ "${1:-}" == "-c" ]] || [[ "${1:-}" == "--check" ]]; then
check_mode=true
shift
fi
markdown_file="${1:-README.md}"
if [[ ! -f "$markdown_file" ]]; then
echo "Error: File not found: $markdown_file" >&2
exit 1
fi
# Create temp file
temp_file=$(mktemp)
trap 'rm -f "$temp_file"' EXIT
# Process the markdown file
in_code_block=false
code_file=""
code_lang=""
skip_next_block=false
while IFS= read -r line || [[ -n "$line" ]]; do
# Check for embed-readme directive: [embed-readme]:# (path [language])
if [[ "$line" =~ ^\[embed-readme\]:#[[:space:]]*\(([^[:space:]]+)([[:space:]]+([^\)]+))?\) ]]; then
code_file="${BASH_REMATCH[1]}"
code_lang="${BASH_REMATCH[3]:-}"
# Check if the file exists
if [[ ! -f "$code_file" ]]; then
echo "Error: Referenced file not found: $code_file" >&2
exit 1
fi
# Write the directive and code block together.
{
printf '%s\n' "$line"
printf '```%s\n' "$code_lang"
cat "$code_file"
printf '```\n'
} >> "$temp_file"
skip_next_block=true
continue
fi
# Skip the existing code block after embedmd directive
if $skip_next_block; then
if [[ "$line" =~ ^\`\`\` ]]; then
if $in_code_block; then
# End of code block - skip and reset
in_code_block=false
skip_next_block=false
else
# Start of code block - skip
in_code_block=true
fi
continue
fi
# Skip lines inside the code block
if $in_code_block; then
continue
fi
fi
# Write all other lines as-is
echo "$line" >> "$temp_file"
done < "$markdown_file"
# Check mode: compare and return error if different
if $check_mode; then
if ! diff -q "$markdown_file" "$temp_file" > /dev/null 2>&1; then
echo "Error: $markdown_file is out of sync. Run 'bin/embed-readme $markdown_file' to update." >&2
diff -u "$markdown_file" "$temp_file" || true
exit 1
fi
echo "✓ $markdown_file is in sync"
exit 0
fi
# Update mode: replace the original file
mv "$temp_file" "$markdown_file"
echo "✓ Updated $markdown_file"