site-auto-updater/site-update.sh

114 lines
2.5 KiB
Bash
Raw Normal View History

2023-08-17 17:50:47 +00:00
#!/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
}
2023-09-24 18:48:28 +00:00
change_directory() {
if [[ -n "$SRCDIR" ]]; then
cd "${SRCDIR}"
fi
2023-08-17 17:50:47 +00:00
}
2023-09-24 18:48:28 +00:00
checkout_branch() {
if [[ -n "$BRANCH" ]]; then
git checkout "${BRANCH}"
else
BRANCH=$(git branch --show-current)
2023-08-17 17:50:47 +00:00
fi
2023-09-24 18:48:28 +00:00
}
copy_to_dest () {
cp -r "${SRCDIR/*}" "${OUTDIR}"
}
update_publish() {
2023-08-17 17:50:47 +00:00
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
2023-09-24 18:48:28 +00:00
copy_to_dest
2023-08-17 17:50:47 +00:00
fi
}
2023-09-24 18:48:28 +00:00
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)
2023-08-17 17:50:47 +00:00
BRANCH=
FILE=
PUBONLY=false
2023-09-24 18:48:28 +00:00
OUTDIR=
2023-08-17 17:50:47 +00:00
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
2023-09-24 18:48:28 +00:00
if [[ -z "$FILE" ]]; then
OUTDIR="${@:$OPTIND:1}"
echo "$OUTDIR"
if [[ ! -d "$OUTDIR" ]]; then
echo "Directory \"${OUTDIR}\" does not exist"
exit 1
fi
fi
main
2023-08-17 17:50:47 +00:00