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