]> Sergey Matveev's repositories - zk.zsh.git/blob - zk.zsh
Require []-brackets and more simple code because of that
[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 (`< $p`) {
30         [[ $w =~ "\[(.*)\]" ]] || continue
31         w=${match[1]}
32         [[ ${pages[$w]} ]] || continue
33         links[$p]="$w ${links[$p]}"
34     }
35 }
36
37 # Deduplicate all references
38 for p w (${(kv)links}) {
39     local ws=(${(u)=w})
40     links[$p]=${(j: :)ws}
41     for w ($ws) backs[$w]="$p ${backs[$w]}"
42 }
43 for p w (${(kv)backs}) {
44     local ws=(${(u)=w})
45     backs[$p]=${(j: :)ws}
46 }
47
48 autoload -U relative
49 getrel() {
50     # nearly the copy-paste of Functions/Misc/relative
51     local dst=$2:a
52     local src=$1:h:a
53     local -a cur abs
54     cur=(${(s:/:)src})
55     abs=(${(s:/:)dst:h} $dst:t)
56     integer i=1
57     while [[ i -le $#abs && $abs[i] == $cur[i] ]] ; do
58         ((++i > $#cur)) && {
59             REPLY=${(j:/:)abs[i,-1]}
60             return
61         }
62     done
63     src=${(j:/:)cur[i,-1]/*/..}
64     dst=${(j:/:)abs[i,-1]}
65     REPLY=$src${dst:+/$dst}
66 }
67
68 genhtml() {
69     local page=$1
70     local data
71     [[ $# -eq 1 ]] && data=`< $page` || data=$2
72     data="${data//&/&amp;}"
73     data="${data//</&lt;}"
74     data="${data//>/&gt;}"
75     for p (${(k)pages}) {
76         [[ $p = index ]] && continue
77         getrel $page $p
78         data="${data//${p}/<a href=\"${REPLY}.html\">$p</a>}"
79     }
80     print "<\!DOCTYPE html>
81 <html><head><title>$page</title></head><body><pre>
82 $data
83 </pre><hr/><ul>"
84     for p (${(oi)=${backs[$page]}}) {
85         getrel $page $p
86         print "<li><a href=\"${REPLY}.html\">$p</a></li>"
87     }
88     print "</ul></body></html>"
89 }
90
91 case $1 in
92 (links) for w (${(oi)=${links[$2]}}) print $w ;;
93 (backs) for w (${(oi)=${backs[$2]}}) print $w ;;
94 (html) genhtml $2 ;;
95 (htmls)
96     for p (${(k)pages}) {
97         local subdir=$p:h
98         mkdir -p $2/$subdir
99         genhtml $p > $2/$p.html
100     }
101     local all=""
102     for p (${(Oi)${(k)pages}}) all="$p\n$all"
103     genhtml ALL $all > $2/ALL.html
104     ;;
105 (*) usage ;;
106 esac