johnny-decimal/build-index.sh

84 lines
2.6 KiB
Bash
Executable File

#!/bin/sh
# MIT License
#
# Copyright (c) 2023 Cordelya Sharpe
# Copyright (c) 2024 Emma Tebibyte <emma@tebibyte.media>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
set -e
test -n "$DEBUG" && set -x
if test -z "$2"; then
if test -z "$1"; then
# output to and read system from current dir if $1 and $2 are not set
out="$(pwd -P)"
root="$out"
else
# if $1 is set, that is the system root
root="$1"
fi
else
# if both $1 and $2 are set, they are the root and output dir
root="$1"
out="$2"
fi
date="$(date "+%Y-%m-%d")"
# for every area dir in the root, get the basename of the area
for dir in "$root"/*; do
area="$(basename "$dir")"
# only include jd files
if test -n "$(printf '%s\n' "$area" | sed -n '/^[0-9][0-9]-.*/p')"
then
# set the filename to the area number for the filename of the index
fullpath="$out/$(printf '%s\n' "$area" | dd bs=5 count=1 2>/dev/null).md"
# if the file already exists, back it up
if test -f "$fullpath"; then
mv "$fullpath" "$fullpath.old"
fi
printf '%s: %s: Saving index as %s.\n' "$0" "$area" "$fullpath" 1>&2
# add front matter to markdown file
printf -- "---\ntitle: %s\ndate: %s\n---\n" "$area" "$date" >>"$fullpath"
# iterate through catergories
for c in "$dir"/*; do
category="$(basename "$c")"
# add category as a header to the output file
printf "# %s\n\n" "$category" >>"$fullpath"
# iterate through contents of categories
for i in "$c"/*; do
id="$(basename "$i")"
# add each content item to the output file
printf "* %s\n" "$id" >>"$fullpath"
done
printf '\n' >>"$fullpath"
done
fi
done