Skip to content

Instantly share code, notes, and snippets.

@eodabas
Created July 12, 2019 14:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save eodabas/e770fff147da20b14d016920979064e5 to your computer and use it in GitHub Desktop.
Save eodabas/e770fff147da20b14d016920979064e5 to your computer and use it in GitHub Desktop.
wrapper for editing files on s3 with vim
#!/bin/bash
print_help() {
echo -e "Usage:\n\n $0 [--profile PROFILE] [s3_url]\n"
exit 1
}
while [[ -n $1 ]];
do
if [[ $1 == "-p" ]] || [[ $1 == "--profile" ]]; then
shift
AWS_PROFILE=$1
else
[[ -z $uri ]] && uri=$1
fi
shift
done
if [[ -z $uri ]]; then
echo -e "S3 url is missing"
print_help
fi
if [[ -z $AWS_PROFILE ]]; then
echo -e "Profile is missing"
print_help
fi
# gnu sed is required
SED=sed
sed --version &>/dev/null || SED=gsed
# detect bucket name and object key
# s3://BUCKET/api/configs/config.py
# https://BUCKET.s3-eu-west-1.amazonaws.com/api/configs/config.py
# https://s3-eu-west-1.amazonaws.com/BUCKET/api/configs/config.py
if [[ $uri =~ ^s3://[^/]+/.+$ ]]; then
bucket=$(echo $uri | cut -d"/" -f3)
object=$(echo $uri | cut -d"/" -f4-)
elif [[ $uri =~ ^https?://.+\.s3-[^\.]+\.amazonaws\.com/.+$ ]]; then
bucket=$(echo $uri | cut -d"/" -f3 | sed -e "s%\(.\+\)\.s3-.*%\1%g")
object=$(echo $uri | cut -d"/" -f4-)
elif [[ $uri =~ ^https?://s3-[^\.]+\.amazonaws\.com/[^/]+/.+$ ]]; then
bucket=$(echo $uri | cut -d"/" -f4)
object=$(echo $uri | cut -d"/" -f5-)
fi
s3_uri="s3://$bucket/$object"
echo AWS_PROFILE.: $AWS_PROFILE
echo URI.........: $uri
echo S3 URI......: $s3_uri
echo BUCKET......: $bucket
echo OBJECT......: $object
echo
tmp_file="$(mktemp -d /tmp/s3vim_XXXXX)/$(basename "$object")"
echo "> Opening $s3_uri at $AWS_PROFILE"
# clean tmp files on break
trap ctrl_c INT
function ctrl_c() {
echo -e "\n> Clearing tmp files"
rm -f "$tmp_file" "${tmp_file}.bak"
exit
}
if aws s3 --profile $AWS_PROFILE cp "$s3_uri" "$tmp_file"; then
echo ""
cp "$tmp_file" "${tmp_file}.bak" && vim "$tmp_file"
else
echo ""
echo "No object found at profile $AWS_PROFILE as $s3_uri"
read -p "Press enter to create this object, ctrl+c to break..." DUMMY
touch "${tmp_file}.bak" && vim "$tmp_file"
fi
echo -e "====================== BEGIN FILE DIFF ======================="
if ! diff --color=always -bur "$tmp_file.bak" "${tmp_file}";
then
echo -e "======================= END FILE DIFF ========================"
echo -e "\n\n"
read -p "Press enter to continue with upload, ctrl+c to break..." DUMMY
aws s3 --profile $AWS_PROFILE cp "$tmp_file" "$s3_uri"
else
echo "no changes"
echo -e "======================= END FILE DIFF ========================"
fi
ctrl_c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment