]> Sergey Matveev's repositories - zk.zsh.git/blob - zk.zsh
5a46d999208819990a59ed9c152d83c38debec84
[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     # nearly the copy-paste of Functions/Misc/relative
55     local dst=$2:a
56     local src=$1:h:a
57     local -a cur abs
58     cur=(${(s:/:)src})
59     abs=(${(s:/:)dst:h} $dst:t)
60     integer i=1
61     while [[ i -le $#abs && $abs[i] == $cur[i] ]] ; do
62         ((++i > $#cur)) && {
63             REPLY=${(j:/:)abs[i,-1]}
64             return
65         }
66     done
67     src=${(j:/:)cur[i,-1]/*/..}
68     dst=${(j:/:)abs[i,-1]}
69     REPLY=$src${dst:+/$dst}
70 }
71
72 genhtml() {
73     local page=$1
74     local data
75     [[ $# -eq 1 ]] && data="`cat $page`" || data=$2
76     local tgt
77     data="${data//&/&amp;}"
78     data="${data//</&lt;}"
79     data="${data//>/&gt;}"
80     for p (${(k)pages}) {
81         [[ $p = ALL ]] && continue
82         [[ $p = index ]] && continue
83         tgt=`getrel $page $p`
84         data="${data//${p}/<a href=\"${tgt}.html\">$p</a>}"
85     }
86     print "<\!DOCTYPE html>
87 <html><head><title>$page</title></head><body><pre>
88 $data
89 </pre><hr/><ul>"
90     for p (${(oi)=${backs[$page]}}) {
91         [[ $p = ALL ]] && continue
92         tgt=`getrel $page $p`
93         print "<li><a href=\"${tgt}.html\">$p</a></li>"
94     }
95     print "</ul></body></html>"
96 }
97
98 case $1 in
99 (links) for w (${(oi)=${links[$2]}}) print $w ;;
100 (backs) for w (${(oi)=${backs[$2]}}) print $w ;;
101 (html) genhtml $2 ;;
102 (htmls)
103     for p (${(k)pages}) {
104         local subdir=$p:h
105         mkdir -p $2/$subdir
106         genhtml $p > $2/$p.html
107     }
108     local all=""
109     for p (${(Oi)${(k)pages}}) all="$p\n$all"
110     genhtml ALL $all > $2/ALL.html
111     ;;
112 (*) usage ;;
113 esac