Skip to content

Instantly share code, notes, and snippets.

@pahaz
Created August 4, 2016 14:08
Show Gist options
  • Save pahaz/8613dd6c8bde6c5b30baa3d1dbf10dfa to your computer and use it in GitHub Desktop.
Save pahaz/8613dd6c8bde6c5b30baa3d1dbf10dfa to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
set -o errexit # always exit on error
set -o pipefail # don't ignore exit codes when piping output
set -o nounset # fail on unset variables
set -o xtrace # print command traces before executing command
echo "PWD=$PWD"
# #
# FRONT FUNCTIONS #
# #
BACK_CACHE_SIGNATURE_FILE=./.back-cache-signature
BACK_CACHE_ARCHIVE=./.back-cache.tar.gz
BACK_CACHE_BASEDIR=/tmp/.back-cache
BACK_PIP_CACHE_DIRECTORY="${BACK_CACHE_BASEDIR}/pip"
create_back_cache_signature() {
# echo "python=$(python --version);"
if [[ -f "requirements.txt" ]]; then
echo "requirementstxt=$(cat requirements.txt);" | tr -d "\n\r "
echo ""
fi
}
save_back_cache_signature() {
echo -n "$(create_back_cache_signature)" > ${BACK_CACHE_SIGNATURE_FILE}
}
load_back_cache_signature() {
if [[ -f "${BACK_CACHE_SIGNATURE_FILE}" ]]; then
cat ${BACK_CACHE_SIGNATURE_FILE}
else
echo ""
fi
}
get_back_cache_status() {
if ! ${BACK_CACHE:-true}; then
echo "disabled"
elif [ "$(create_back_cache_signature)" != "$(load_back_cache_signature)" ]; then
echo "invalid"
else
echo "valid"
fi
}
restore_from_back_cache() {
rm -rf "${BACK_CACHE_BASEDIR}"
mkdir -p "${BACK_CACHE_BASEDIR}"
tar -xPpzf "${BACK_CACHE_ARCHIVE}"
pip install --no-index --find-links="${BACK_PIP_CACHE_DIRECTORY}" -r requirements.txt
rm -rf "${BACK_CACHE_BASEDIR}"
}
save_back_cache() {
rm -rf "${BACK_CACHE_BASEDIR}"
mkdir -p "${BACK_PIP_CACHE_DIRECTORY}"
pip wheel --wheel-dir="${BACK_PIP_CACHE_DIRECTORY}" -r requirements.txt
tar -cPpzf "${BACK_CACHE_ARCHIVE}" --one-file-system "${BACK_CACHE_BASEDIR}"
rm -rf "${BACK_CACHE_BASEDIR}"
}
clear_back_cache() {
rm -rf "${BACK_CACHE_BASEDIR}"
rm -f "${BACK_CACHE_ARCHIVE}"
rm -f "${BACK_CACHE_SIGNATURE_FILE}"
}
install_used_cache() {
back_cache_status="$(get_back_cache_status)"
echo "BACK-CACHE-STATUS: ${back_cache_status}"
if [ "$back_cache_status" == "valid" ]; then
restore_from_back_cache
else
save_back_cache
save_back_cache_signature
restore_from_back_cache
fi
}
case "$1" in
-h | --help | help)
echo "use: $0 (install|clean|status)"
exit 0
;;
install)
install_used_cache
exit 0
;;
clean)
clear_front_cache
exit 0
;;
status)
set +x
back_cache_status="$(get_back_cache_status)"
echo $back_cache_status
if [ "$back_cache_status" == "valid" ]; then
exit 0
else
exit 1
fi
exit 0
;;
save)
clear_back_cache
save_back_cache
save_back_cache_signature
exit 0
;;
restore)
restore_from_back_cache
exit 0
;;
*) # No more options
echo "Error: Unknown option: $1" >&2
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment