site-auto-updater/site-update.sh

118 lines
2.6 KiB
Bash
Executable File

#!/usr/bin/env bash
# update a git repository and copy its contents to a directory
set -o errexit
set -o nounset
set -o pipefail
if [[ "${TRACE-0}" == "1" ]]; then
set -o xtrace
fi
help() {
echo "Update a git repository and copy the files to OUTDIR"
echo "Intended for use with static websites"
echo
echo "Usage: ./site-update.sh [-b BRANCH|d SRCDIR|f FILE|h|p] OUTDIR"
echo "Options"
echo "b BRANCH git branch to update, defaults to the current branch in SRCDIR"
echo "d SRCDIR directory containing git repository to update, defaults to current working directory"
echo "f FILE update a batch of repositories, as defined in FILE"
echo "h print this help message"
echo "p publish files only, do not update"
}
get_changes() {
git fetch origin
if [[ $(git status | grep behind) ]]; then
git merge origin/"${BRANCH}"
fi
}
change_directory() {
if [[ -n "$SRCDIR" ]]; then
cd "${SRCDIR}"
fi
}
checkout_branch() {
if [[ -n "$BRANCH" ]]; then
git checkout "${BRANCH}"
else
BRANCH=$(git branch --show-current)
fi
}
copy_to_dest () {
cp -r "${SRCDIR}/." "${OUTDIR}"
}
update_publish() {
if [[ -n "$SRCDIR" ]]; then
cd "${SRCDIR}"
fi
if [[ -n "$BRANCH" ]]; then
git checkout "${BRANCH}"
else
BRANCH=$(git branch --show-current)
fi
if [[ "$PUBONLY" == false ]]; then
get_changes
fi
if diff "${SRCDIR}" "${OUTDIR}" >/dev/null; then
echo "No changes detected."
else
copy_to_dest
fi
}
main() {
srcdirlen=${#SRCDIR}
if [[ ${SRCDIR:(-1)} == '/' ]]; then
SRCDIR=${SRCDIR:0:-1}
fi
if [[ -f "$FILE" ]]; then
while read -r src out rem; do
# use rem as dummy variable to guarantee out countains one word
echo "${src} | ${out} | ${rem}"
done < "${FILE}"
else
update_publish
fi
}
SRCDIR=$(pwd)
BRANCH=
FILE=
PUBONLY=false
OUTDIR=
while getopts ":hd:f:b:p" option; do
case $option in
b) # select branch
BRANCH=$OPTARG;;
f) # file listing directories
FILE=$OPTARG;;
d) # directory to act on
SRCDIR=$OPTARG;;
h) #display help
help
exit;;
p) #publish only, do not update
PUBONLY=true;;
\?) #invalid option
echo "Error: Invalid option"
exit;;
esac
done
if [[ -z "$FILE" ]]; then
OUTDIR="${@:$OPTIND:1}"
echo "$OUTDIR"
if [[ ! -d "$OUTDIR" ]]; then
echo "Directory \"${OUTDIR}\" does not exist"
exit 1
fi
fi
main