Recently Written · git

tmpl

Insanely simple templates

git clone https://github.com/equwal/tmpl

Log | Files | Refs


bin/tmpl (1695 bytes)

1 #!/bin/sh
2 # Print, list or pick templates from the tmpl repository.
3 #
4 # usage: tmpl -l            list templates as "path<TAB>summary"
5 #        tmpl -f            pick a template with fzf and print it
6 #        tmpl LANG NAME     print a template, for example: tmpl sh for-find
7 #        tmpl PATH          print a template, for example: tmpl sh/trap/cleanup-temp
8 #
9 # TMPL_DIR overrides the template directory. The default is the parent of
10 # the directory that holds this script.
11 
12 set -eu
13 
14 root=${TMPL_DIR:-$(cd "$(dirname "$0")/.." && pwd)}
15 
16 usage() {
17     sed -n '2,8p' "$0" | sed 's/^# \{0,1\}//' >&2
18     exit 2
19 }
20 
21 # Print every template path relative to $root, one per line.
22 list_paths() {
23     find "$root" -type f \
24         ! -path '*/.*' ! -path '*/__pycache__/*' \
25         ! -path "$root/bin/*" ! -path "$root/tests/*" \
26         ! -name '*.py' ! -name '*.md' ! -name Makefile \
27         | sed "s|^$root/||" | LC_ALL=C sort
28 }
29 
30 # Print the summary comment on the first line of a file. A #! line may come first.
31 summary() {
32     awk 'NR == 1 && /^#!/ { next }
33          /^[ \t]*(#+|;+|\/\/|<!--)[ \t]+/ { sub(/^[ \t]*(#+|;+|\/\/|<!--)[ \t]+/, ""); sub(/[ \t]*-->[ \t]*$/, ""); print }
34          { exit }' "$1"
35 }
36 
37 list() {
38     list_paths | while IFS= read -r path; do
39         printf '%s\t%s\n' "$path" "$(summary "$root/$path")"
40     done
41 }
42 
43 case ${1:-} in
44     -l) list ;;
45     -f) pick=$(list | fzf --with-nth=1,2 --delimiter='\t' | cut -f1 | head -n 1)
46         [ -n "$pick" ] && cat "$root/$pick" ;;
47     -h|--help|'') usage ;;
48     *)  path=$(printf '%s/' "$@" | sed 's|/$||')
49         [ -f "$root/$path" ] || { printf 'tmpl: no template %s\n' "$path" >&2; exit 1; }
50         cat "$root/$path" ;;
51 esac