-
-
Save JacobGabrielson/af9d3995b3487757e614c35a9971e3a1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Like the 'aws' cli except caches results | |
# http://redsymbol.net/articles/unofficial-bash-strict-mode/ | |
set -euo pipefail | |
IFS=$'\n\t' | |
#set -x | |
# Produce short hash just as insurance in case the directory scheme | |
# produces a collision. For example "s3 ls a@" and "s3 ls a_" both | |
# wind up in .caws-cache/s3/ls/a/ so there needs to be a final | |
# disambiguation. | |
function hexsum { | |
printf "%x" $(echo -n $@ | cksum | cut -d' ' -f 1) | |
} | |
# https://stackoverflow.com/a/17841619/68127 | |
function join_by { local IFS="$1"; shift; echo "$*"; } | |
function args_to_dir { | |
local -a dir_safe_args | |
for arg in $@ | |
do | |
xlated=$(echo -n $arg | tr --delete --complement 'a-zA-Z0-9_') | |
dir_safe_args+=( $xlated ) | |
done | |
join_by "/" ${dir_safe_args[@]} | |
} | |
CAWS_CACHE_DIR=${CAWS_CACHE_DIR-.caws-cache} | |
cached_output_dir="${CAWS_CACHE_DIR}/$(args_to_dir $@)/$(hexsum $@)" | |
mkdir -p $cached_output_dir | |
cached_output=$cached_output_dir/output | |
if [[ ! -f $cached_output ]] | |
then | |
maybe_cached_output=$(mktemp --tmpdir=$cached_output_dir 'maybe_outputXXXXX.out') | |
trap "rm -f $maybe_cached_output" EXIT | |
maybe_error_output=$cached_output_dir/last-error.out | |
set +e | |
aws $@ >$maybe_cached_output 2>$maybe_error_output | |
error_code=$? | |
set -e | |
if [[ $error_code != 0 ]] | |
then | |
cat 1>&2 $maybe_error_output | |
exit $error_code | |
else | |
mv $maybe_cached_output $cached_output | |
fi | |
fi | |
cat $cached_output | |
exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment