]> git.plutz.net Git - shellwiki/blob - parsers/40_indexer.sh
eliminate race condition in index time stamping
[shellwiki] / parsers / 40_indexer.sh
1 #!/bin/sh
2
3 # Copyright 2023 Paul Hänsch
4
5 # Permission to use, copy, modify, and/or distribute this software for any
6 # purpose with or without fee is hereby granted, provided that the above
7 # copyright notice and this permission notice appear in all copies.
8
9 # THE SOFTWARE IS PROVIDED “AS IS” AND THE AUTHOR DISCLAIMS ALL WARRANTIES
10 # WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
11 # MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
12 # SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
13 # WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
14 # ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
15 # IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
16
17 DOC="${PATH_INFO%/}/" P="$_DATA/pages${DOC}" I="$_DATA/index/"
18
19 if [ -f "$P/#index.flag" -a ! "$P/#page.md" -nt "$P/#index.flag" ] || [ ! -d "$P" ]; then
20   cat
21   exit 0
22 fi
23
24 . "$_EXEC/cgilite/storage.sh"
25
26 exec 3>&1
27
28 touch -d "@$_DATE" "$P/#index.flag"
29 mkdir -p "$I"
30
31 { cat; printf \\n; } \
32 | while IFS='' read -r line; do
33   printf '%s\n' "$line" >&3
34   printf '%s\n' "$line"
35 done \
36 | awk '
37   BEGIN { FS = "([] \t\n\r!\"#'\''()*+,./:;<=>?\\^_`{|}~[-]|%[0-9A-Fa-f]{2})+" }
38         { for (n = 1; n <= NF; n++) {
39             if ( $n != "" && length($n) <= 128 ) {
40               words[tolower($n)]++; total++;
41         } } }
42     END { for (w in words) printf "%i %i %f %s\n", words[w], total, words[w] / total, w; }
43 ' \
44 | while read num total freq word; do
45   [ "$word" ] || continue
46   F="$I/$word"
47   L="$(STRING "$DOC")"
48
49   if LOCK "$F"; then
50     touch "$F"
51     { while read d l f n t; do
52       [ "$l" = "$L" ] \
53       || printf "%i     %s      %f      %i      %i\n" \
54                 "$d" "$l" "$f" "$n" "$t"
55       done <"$F"
56       printf "%i        %s      %f      %i      %i\n" \
57              "$_DATE" "$L" "$freq" "$num" "$total"
58     } >"$F.$$"
59     mv -- "$F.$$" "$F"
60     RELEASE "$F"
61   fi
62 done