Skip to content

Instantly share code, notes, and snippets.

@millionfor
Last active August 9, 2022 06:40
Show Gist options
  • Save millionfor/3ef404655274805b6ff6068bc90e3540 to your computer and use it in GitHub Desktop.
Save millionfor/3ef404655274805b6ff6068bc90e3540 to your computer and use it in GitHub Desktop.
A shell-based oss upload script
#!/bin/bash
# vim: set ft=sh fdm=manual ts=2 sw=2 sts=2 tw=85 et:
# =======================================================
# Description:
# Author QuanQuan <millionfor@apache.org>
# Last Modified Tue, Aug 09, 2022 14:40
# GistID 3ef404655274805b6ff6068bc90e3540
# GistURL https://gist.github.com/millionfor/3ef404655274805b6ff6068bc90e3540
# =======================================================
set -eu
die() {
echo >&2 "${1-}"
exit "${2-1}"
}
env=
source=
dest=
dry_run=false
args=()
while [ $# -gt 0 ]; do
case "$1" in
-e | --env)
# env (pro or test)
env=${2-}
shift
;;
--dry-run)
dry_run=true
;;
-h | --help)
echo "hss-upload-oss [-e <env_name> | -h]"
exit
;;
*) die "fatal: invalid parameter: $1" ;;
esac
shift
done
if [ "${dry_run}" = "true" ]; then
run() {
echo "$1"
}
else
run() {
eval "$1"
}
fi
dir=$(cd $(dirname $0) && pwd)
echo $env
host="oss-cn-shanghai.aliyuncs.com"
bucket="$(jq -r ".bucket" $HOME/.aliyun)"
ak="$(jq -r ".ak" $HOME/.aliyun)"
sk="$(jq -r ".sk" $HOME/.aliyun)"
ossHost=$bucket.$host
version="$(jq -r ".version" package.json)"
fileName="__v${version}.zip"
dir=${dir//scripts/}
cd "${dir}dist"
zip -r $fileName ./*
cd ..
source="${dir}dist/${fileName}"
dest="mall/${env}/zips"
declare -a result=()
encodeFilename=""
upload() {
urlencode "$(basename "$source")"
cloudDir="$dest/$encodeFilename"
contentType=$(file -b --mime-type "$source")
dateValue="$(TZ=GMT env LANG=en_US.UTF-8 date +'%a, %d %b %Y %H:%M:%S GMT')"
echo $dateValue
stringToSign="PUT\n\n$contentType\n$dateValue\n/$bucket/$dest/$encodeFilename"
signature=$(echo -en "$stringToSign" | openssl sha1 -hmac "$sk" -binary | base64)
curl -i -q -X PUT -T "$source" \
-H "Host: $bucket.$host" \
-H "Date: $dateValue" \
-H "Content-Type: $contentType" \
-H "Authorization: OSS $ak:$signature" \
https://"$bucket"."$host"/"$cloudDir"
result+=(https://"$bucket"."$host"/"$cloudDir")
}
urlencode() {
encodeFilename=""
local length="${#1}"
for ((i = 0; i < length; i++)); do
local c="${1:i:1}"
case $c in
[a-zA-Z0-9.~_-])
encodeFilename=$encodeFilename$(printf "$c")
;;
*)
encodeFilename=$encodeFilename$(printf "$c" | xxd -p -c1 \
| while read x; do
printf "%%%s" "$x"
done)
;;
esac
done
}
upload
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment