|
| 1 | +#!/bin/bash |
| 2 | + |
| 3 | +set -e |
| 4 | + |
| 5 | +CACHE_FILE=$1 |
| 6 | +CACHE_KEY=$2 |
| 7 | + |
| 8 | +if [ -z "$CACHE_FILE" ]; then |
| 9 | + echo "You must pass the file or directory you want to be cached" |
| 10 | + return 1 |
| 11 | +fi |
| 12 | + |
| 13 | +# We can automatically derive a cache key if one isn't provided |
| 14 | +if [ -z "$CACHE_KEY" ]; then |
| 15 | + echo "No cache key provided – automatically deriving one:" |
| 16 | + |
| 17 | + # if the $CACHE_FILE is a directory, derived the key from the hash of all files within it |
| 18 | + if [[ -d $CACHE_FILE ]]; then |
| 19 | + CACHE_KEY=$(hash_directory "$CACHE_FILE") |
| 20 | + echo " '$CACHE_FILE' is a directory with the hash $CACHE_KEY" |
| 21 | + |
| 22 | + # if the $CACHE_FILE is a regular file, derive the key from the file's hash |
| 23 | + elif [[ -f $CACHE_FILE ]]; then |
| 24 | + CACHE_KEY=$(hash_file "$CACHE_FILE") |
| 25 | + echo " '$CACHE_FILE' is a file with the hash $CACHE_KEY" |
| 26 | + fi |
| 27 | +fi |
| 28 | + |
| 29 | +if [ -z "$CACHE_BUCKET_NAME" ]; then |
| 30 | + if [ -z "$BUILDKITE_PLUGIN_BASH_CACHE_BUCKET" ]; then |
| 31 | + printenv | grep buildkite |
| 32 | + echo "Reading bucket name from 'BUILDKITE_PLUGIN_BASH_CACHE_BUCKET'" |
| 33 | + CACHE_BUCKET_NAME="$BUILDKITE_PLUGIN_BASH_CACHE_BUCKET" |
| 34 | + else |
| 35 | + echo "⛔Unable to save file to cache – no \$CACHE_BUCKET_NAME is set" |
| 36 | + return 1 |
| 37 | + fi |
| 38 | +fi |
| 39 | + |
| 40 | +if ! aws s3api head-object --bucket "$CACHE_BUCKET_NAME" --key "$CACHE_KEY" > /dev/null 2>&1; then |
| 41 | + echo "No existing cache entry for $CACHE_KEY – storing in cache" |
| 42 | + |
| 43 | + echo " Compressing" |
| 44 | + tar -czf "$CACHE_KEY" "$CACHE_FILE" |
| 45 | + |
| 46 | + echo " Uploading" |
| 47 | + aws s3 cp "$CACHE_KEY" "s3://$CACHE_BUCKET_NAME/$CACHE_KEY" --quiet |
| 48 | + |
| 49 | + echo " Cleaning Up" |
| 50 | + rm "$CACHE_KEY" |
| 51 | +else |
| 52 | + echo "This file is already cached – skipping upload" |
| 53 | +fi |
0 commit comments