◊(Local Yarn Code "relativize at [adf0d96e]")

File util/relativize artifact fca41d4e part of check-in adf0d96e


#!/bin/bash

# SPDX-License-Identifier: BlueOak-1.0.0
# This file is licensed under the Blue Oak Model License 1.0.0.

# The HTML generated assumes the whole site lives in the domain root. This script converts all links
# and image sources to relative URLs, so things don't break when accessed from within a subfolder of
# a live web server. (See ‘publish’ target of makefile)

# Stop on any error, forbid uninitialized vars
set -eu

# First parameter is used as working dir, defaults to ./
base_dir=${1:-"./"}

# Ensure directory name ends with a slash
[[ "${base_dir}" != */ ]] && base_dir="${base_dir}/"

# Ensure directory exists
if [[ ! -d "${base_dir}" ]]; then
    echo "[$(date +'%Y-%m-%dT%H:%M:%S%z')]: ${base_dir} not a directory!" >&2
    exit 1
fi

# Root folder: remove leading / from href and src attributes
# Works across (and preserves) line breaks introduced by the `tidy` command
perl -0777 -i -pe 's/ href=(\s*)"\/(?!code)/ href=$1"/ig' "${base_dir}"*.html
perl -0777 -i -pe 's/ src=(\s*)"\/(?!code)/ src=$1"/ig' "${base_dir}"*.html

# subfolders: replace leading / with ../ in href and src attributes
perl -0777 -i -pe 's/ href=(\s*)"\/(?!code)/ href=$1"..\//ig' "${base_dir}"articles/*.html
perl -0777 -i -pe 's/ src=(\s*)"\/(?!code)/ src=$1"..\//ig' "${base_dir}"articles/*.html
perl -0777 -i -pe 's/ href=(\s*)"\/(?!code)/ href=$1"..\//ig' "${base_dir}"series/*.html
perl -0777 -i -pe 's/ src=(\s*)"\/(?!code)/ src=$1"..\//ig' "${base_dir}"series/*.html