site-auto-updater/site-update.sh

114 lines
2.5 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
diff "${SRCDIR} ${OUTDIR}"
local rc=$?
if [[ $rc -eq 1 ]]; then
copy_to_dest
fi
}
main() {
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