repo-fix/scripts/publish-coverage-badges.sh

111 lines
2.8 KiB
Bash
Executable File

#!/bin/sh
set -eu
usage() {
echo "usage: $0 ROOT OWNER PROJECT DEFAULT_BRANCH NAME..." >&2
exit 2
}
[ "$#" -ge 5 ] || usage
root=$1
owner=$2
project=$3
default_branch=$4
shift 4
case "$root" in
/*) ;;
*) echo "publication root must be absolute: $root" >&2; exit 2 ;;
esac
[ -d "$root" ] && [ -w "$root" ] || {
echo "publication root must be an existing writable directory: $root" >&2
exit 2
}
validate_component() {
component_name=$1
component_value=$2
case "$component_value" in
''|.|..|*[!A-Za-z0-9._-]*)
echo "$component_name is not a safe path component: $component_value" >&2
exit 2
;;
esac
}
validate_component owner "$owner"
validate_component project "$project"
validate_component default-branch "$default_branch"
names=
for name do
case "$name" in
coverage|test|version) ;;
*) echo "unsupported badge name: $name" >&2; exit 2 ;;
esac
case " $names " in
*" $name "*) echo "duplicate badge name: $name" >&2; exit 2 ;;
esac
source_file="coverage/$name.svg"
[ ! -L "$source_file" ] && [ -f "$source_file" ] && [ -s "$source_file" ] || {
echo "badge source must be a regular, nonempty, non-symlink file: $source_file" >&2
exit 2
}
names="$names $name"
done
ensure_directory() {
directory=$1
if [ -L "$directory" ]; then
echo "publication path component must not be a symlink: $directory" >&2
exit 2
fi
if [ -e "$directory" ]; then
[ -d "$directory" ] || {
echo "publication path component is not a directory: $directory" >&2
exit 2
}
else
mkdir -m 0755 "$directory"
fi
}
owner_directory="$root/$owner"
project_directory="$owner_directory/$project"
destination="$project_directory/$default_branch"
ensure_directory "$owner_directory"
ensure_directory "$project_directory"
if [ -L "$destination" ]; then
unlink "$destination"
elif [ -e "$destination" ] && [ ! -d "$destination" ]; then
echo "default-branch destination is not a directory: $destination" >&2
exit 2
fi
ensure_directory "$destination"
temporary_files=
cleanup() {
for temporary_file in $temporary_files; do
rm -f "$temporary_file"
done
}
trap cleanup 0
trap 'exit 1' HUP INT TERM
for name in $names; do
source_file="coverage/$name.svg"
target_file="$destination/$name.svg"
if [ -L "$target_file" ] || { [ -e "$target_file" ] && [ ! -f "$target_file" ]; }; then
echo "badge destination must be absent or a regular file: $target_file" >&2
exit 2
fi
temporary_file="$destination/.$name.svg.tmp.$$"
temporary_files="$temporary_files $temporary_file"
cp "$source_file" "$temporary_file"
chmod 0644 "$temporary_file"
mv -f "$temporary_file" "$target_file"
done
trap - 0 HUP INT TERM