]> Sergey Matveev's repositories - zk.zsh.git/blob - zk.zsh
56e071f8af79e60139d3b569ec5870fb79b9b74f
[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     local tgt=$2:a
55     cd $1:h
56     relative $tgt
57 }
58
59 genhtml() {
60     local page=$1
61     local data
62     [[ $# -eq 1 ]] && data="`cat $page`" || data=$2
63     local tgt
64     data="${data//&/&amp;}"
65     data="${data//</&lt;}"
66     data="${data//>/&gt;}"
67     for p (${(k)pages}) {
68         [[ $p = ALL ]] && continue
69         [[ $p = index ]] && continue
70         tgt=`getrel $page $p`
71         data="${data//${p}/<a href=\"${tgt}.html\">$p</a>}"
72     }
73     print "<\!DOCTYPE html>
74 <html><head><title>$page</title></head><body><pre>
75 $data
76 </pre><hr/><ul>"
77     for p (${(oi)=${backs[$page]}}) {
78         [[ $p = ALL ]] && continue
79         tgt=`getrel $page $p`
80         print "<li><a href=\"${tgt}.html\">$p</a></li>"
81     }
82     print "</ul></body></html>"
83 }
84
85 case $1 in
86 (links) for w (${(oi)=${links[$2]}}) print $w ;;
87 (backs) for w (${(oi)=${backs[$2]}}) print $w ;;
88 (html) genhtml $2 ;;
89 (htmls)
90     for p (${(k)pages}) {
91         local subdir=$p:h
92         mkdir -p $2/$subdir
93         genhtml $p > $2/$p.html
94     }
95     local all=""
96     for p (${(oi)${(k)pages}}) all="$p\n$all"
97     genhtml ALL $all > $2/ALL.html
98     ;;
99 (*) usage ;;
100 esac