]> Sergey Matveev's repositories - zk.zsh.git/blob - zk.zsh
94a670067926cfcc7aeca94a164cf4204fb39882
[zk.zsh.git] / zk.zsh
1 #!/usr/bin/env zsh
2
3 set -e
4
5 usage() {
6     cat >&2 <<EOF
7 Usage:
8   \$ $0:t links PAGE
9     Print the PAGE's links
10   \$ $0:t backs PAGE
11     Print who backlinks to the PAGE
12   \$ $0:t htmls DIR
13     Generate HTMLs in DIR
14 EOF
15     exit 1
16 }
17
18 [[ $# -eq 2 ]] || usage
19
20 # Collect all pages
21 setopt GLOB_STAR_SHORT
22 typeset -A pages
23 for f (**(.)) pages[$f]=1
24
25 # Determine the links between them
26 typeset -A links
27 typeset -A backs
28 for p (${(k)pages}) {
29     for w (`cat $p`) {
30         [[ $w =~ "^[([{].*" ]] && w=${MATCH[2,-2]}
31         [[ ${pages[$w]} ]] || continue
32         links[$p]="$w ${links[$p]}"
33     }
34 }
35
36 # Deduplicate all references
37 typeset -A ws
38 for p (${(k)links}) {
39     ws=()
40     for w (${=${links[$p]}}) {
41         ws[$w]=1
42         backs[$w]="$p ${backs[$w]}"
43     }
44     links[$p]=${(k)ws}
45 }
46 for p (${(k)backs}) {
47     ws=()
48     for w (${=${backs[$p]}}) ws[$w]=1
49     backs[$p]=${(k)ws}
50 }
51
52 autoload -U relative
53 getrel() {
54     relative $2:a $1:h
55 }
56
57 genhtml() {
58     local page=$1
59     local data
60     [[ $# -eq 1 ]] && data="`cat $page`" || data=$2
61     local tgt
62     data="${data//&/&amp;}"
63     data="${data//</&lt;}"
64     data="${data//>/&gt;}"
65     for p (${(k)pages}) {
66         [[ $p = ALL ]] && continue
67         [[ $p = index ]] && continue
68         tgt=`getrel $page $p`
69         data="${data//${p}/<a href=\"${tgt}.html\">$p</a>}"
70     }
71     print "<\!DOCTYPE html>
72 <html><head><title>$page</title></head><body><pre>
73 $data
74 </pre><hr/><ul>"
75     for p (${(oi)=${backs[$page]}}) {
76         [[ $p = ALL ]] && continue
77         tgt=`getrel $page $p`
78         print "<li><a href=\"${tgt}.html\">$p</a></li>"
79     }
80     print "</ul></body></html>"
81 }
82
83 case $1 in
84 (links) for w (${(oi)=${links[$2]}}) print $w ;;
85 (backs) for w (${(oi)=${backs[$2]}}) print $w ;;
86 (html) genhtml $2 ;;
87 (htmls)
88     for p (${(k)pages}) {
89         local subdir=$p:h
90         mkdir -p $2/$subdir
91         genhtml $p > $2/$p.html
92     }
93     local all=""
94     for p (${(Oi)${(k)pages}}) all="$p\n$all"
95     genhtml ALL $all > $2/ALL.html
96     ;;
97 (*) usage ;;
98 esac