]> Sergey Matveev's repositories - zk.zsh.git/commitdiff
Initial commit
authorSergey Matveev <stargrave@stargrave.org>
Sat, 12 Mar 2022 19:44:51 +0000 (22:44 +0300)
committerSergey Matveev <stargrave@stargrave.org>
Sat, 12 Mar 2022 19:44:51 +0000 (22:44 +0300)
zk.zsh [new file with mode: 0755]

diff --git a/zk.zsh b/zk.zsh
new file mode 100755 (executable)
index 0000000..56e071f
--- /dev/null
+++ b/zk.zsh
@@ -0,0 +1,100 @@
+#!/usr/bin/env zsh
+
+set -e
+
+usage() {
+    cat >&2 <<EOF
+Usage:
+  \$ $0:t links PAGE
+    Print the PAGE's links
+  \$ $0:t backs PAGE
+    Print who backlinks to the PAGE
+  \$ $0:t htmls DIR
+    Generate HTMLs in DIR
+EOF
+    exit 1
+}
+
+[[ $# -eq 2 ]] || usage
+
+# Collect all pages
+setopt GLOB_STAR_SHORT
+typeset -A pages
+for f (**(.)) pages[$f]=1
+
+# Determine the links between them
+typeset -A links
+typeset -A backs
+for p (${(k)pages}) {
+    for w (`cat $p`) {
+        [[ $w =~ "^\(.*\)$" ]] && w=${MATCH[2,-2]}
+        [[ ${pages[$w]} ]] || continue
+        links[$p]="$w ${links[$p]}"
+    }
+}
+
+# Deduplicate all references
+typeset -A ws
+for p (${(k)links}) {
+    ws=()
+    for w (${=${links[$p]}}) {
+        ws[$w]=1
+        backs[$w]="$p ${backs[$w]}"
+    }
+    links[$p]=${(k)ws}
+}
+for p (${(k)backs}) {
+    ws=()
+    for w (${=${backs[$p]}}) ws[$w]=1
+    backs[$p]=${(k)ws}
+}
+
+autoload -U relative
+getrel() {
+    local tgt=$2:a
+    cd $1:h
+    relative $tgt
+}
+
+genhtml() {
+    local page=$1
+    local data
+    [[ $# -eq 1 ]] && data="`cat $page`" || data=$2
+    local tgt
+    data="${data//&/&amp;}"
+    data="${data//</&lt;}"
+    data="${data//>/&gt;}"
+    for p (${(k)pages}) {
+        [[ $p = ALL ]] && continue
+        [[ $p = index ]] && continue
+        tgt=`getrel $page $p`
+        data="${data//${p}/<a href=\"${tgt}.html\">$p</a>}"
+    }
+    print "<\!DOCTYPE html>
+<html><head><title>$page</title></head><body><pre>
+$data
+</pre><hr/><ul>"
+    for p (${(oi)=${backs[$page]}}) {
+        [[ $p = ALL ]] && continue
+        tgt=`getrel $page $p`
+        print "<li><a href=\"${tgt}.html\">$p</a></li>"
+    }
+    print "</ul></body></html>"
+}
+
+case $1 in
+(links) for w (${(oi)=${links[$2]}}) print $w ;;
+(backs) for w (${(oi)=${backs[$2]}}) print $w ;;
+(html) genhtml $2 ;;
+(htmls)
+    for p (${(k)pages}) {
+        local subdir=$p:h
+        mkdir -p $2/$subdir
+        genhtml $p > $2/$p.html
+    }
+    local all=""
+    for p (${(oi)${(k)pages}}) all="$p\n$all"
+    genhtml ALL $all > $2/ALL.html
+    ;;
+(*) usage ;;
+esac