]> Sergey Matveev's repositories - zk.zsh.git/blob - zk.zsh
Show notes mtime in title
[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 zmodload -F zsh/stat b:zstat
23 typeset -A pages
24 for p (**(.)) {
25     zstat -A reply -F "%F %T" +mtime $p
26     pages[$p]=${reply[1]}
27 }
28
29 # Determine the links between them
30 typeset -A links
31 typeset -A backs
32 for p (${(k)pages}) {
33     for w (`< $p`) {
34         [[ $w =~ "\[(.*)\]" ]] || continue
35         w=${match[1]}
36         [[ ${pages[$w]} ]] || continue
37         links[$p]="$w ${links[$p]}"
38     }
39 }
40
41 # Deduplicate all references
42 for p w (${(kv)links}) {
43     local ws=(${(u)=w})
44     links[$p]=${(j: :)ws}
45     for w ($ws) backs[$w]="$p ${backs[$w]}"
46 }
47 for p w (${(kv)backs}) {
48     local ws=(${(u)=w})
49     backs[$p]=${(j: :)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=`< $page` || data=$2
76     data="${data//&/&amp;}"
77     data="${data//</&lt;}"
78     data="${data//>/&gt;}"
79     for p (${(k)pages}) {
80         [[ $p = index ]] && continue
81         getrel $page $p
82         data="${data//${p}/<a href=\"${REPLY}.html\">$p</a>}"
83     }
84     print "<\!DOCTYPE html>
85 <html><head><title>$page (${pages[$page]})</title></head><body><pre>
86 $data
87 </pre><hr/><ul>"
88     for p (${(oi)=${backs[$page]}}) {
89         getrel $page $p
90         print "<li><a href=\"${REPLY}.html\">$p</a> <sup>${pages[$p]}</sup></li>"
91     }
92     print "</ul></body></html>"
93 }
94
95 case $1 in
96 (links) for w (${(oi)=${links[$2]}}) print $w ;;
97 (backs) for w (${(oi)=${backs[$2]}}) print $w ;;
98 (html) genhtml $2 ;;
99 (htmls)
100     for p (${(k)pages}) {
101         local subdir=$p:h
102         mkdir -p $2/$subdir
103         genhtml $p > $2/$p.html
104     }
105     local all=()
106     for p (${(Oi)${(k)pages}}) all=("$p (${pages[$p]})" $all)
107     zmodload -F zsh/datetime b:strftime
108     pages[ALL]=$(strftime "%F %T")
109     genhtml ALL ${(j:\n:)all} > $2/ALL.html
110     ;;
111 (*) usage ;;
112 esac