Files
app-api/scripts/upload.sh
T
2026-06-12 15:50:01 +08:00

125 lines
2.7 KiB
Bash
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bash
set -euo pipefail
REMOTE_DIR="/data/project/app-api/"
DEFAULT_PATHS=(
./cmd/
./internal/
./pkg
./go.mod
./go.sum
./Dockerfile
./docker-compose.yml
)
show_help() {
cat <<'EOF'
用法: upload.sh [选项] [服务器] [路径...]
将本地代码同步到远程服务器(rsync)。
选项:
-n 虚拟执行,不实际传输或删除远程文件
-h, --help 显示此帮助信息
服务器:
api1 仅上传到 api1 (luxsin-api1)
api2 仅上传到 api2 (luxsin-api2)
(省略) 同时上传到 api1 和 api2
路径:
指定要同步的文件或目录,可传多个。
省略时使用默认路径: cmd/ internal/ pkg go.mod go.sum Dockerfile docker-compose.yml
示例:
upload.sh 同步默认路径到 api1 和 api2
upload.sh api1 同步默认路径到 api1
upload.sh api2 ./internal 同步 internal/ 到 api2
upload.sh -n 虚拟执行,预览同步到 api1 和 api2
upload.sh -n api1 ./internal 虚拟执行,预览同步到 api1
EOF
}
remote_host_for() {
case "$1" in
api1) echo "luxsin-api1" ;;
api2) echo "luxsin-api2" ;;
*)
echo "未知服务器: $1(可选: api1, api2" >&2
exit 1
;;
esac
}
upload_to() {
local server="$1"
shift
local paths=("$@")
local remote_host
remote_host="$(remote_host_for "$server")"
if [ "$DRY_RUN" = true ]; then
echo "虚拟上传到 ${server} (${remote_host}) ..."
else
echo "上传到 ${server} (${remote_host}) ..."
fi
local rsync_opts=(-avz --progress)
if [ "$DRY_RUN" = true ]; then
rsync_opts+=(-n)
fi
local item rel remote_path
for item in "${paths[@]}"; do
rel="${item#./}"
remote_path="${REMOTE_DIR}${rel}"
if [[ -d "$item" ]]; then
echo " 同步目录: $item -> ${remote_host}:${remote_path}/"
rsync "${rsync_opts[@]}" --delete "${item}/" "${remote_host}:${remote_path}/"
else
echo " 同步文件: $item -> ${remote_host}:${remote_path}"
rsync "${rsync_opts[@]}" "$item" "${remote_host}:${remote_path}"
fi
done
}
DRY_RUN=false
ARGS=()
for arg in "$@"; do
case "$arg" in
-n)
DRY_RUN=true
;;
-h|--help)
show_help
exit 0
;;
*)
ARGS+=("$arg")
;;
esac
done
SERVERS=()
if [ ${#ARGS[@]} -gt 0 ] && { [ "${ARGS[0]}" = "api1" ] || [ "${ARGS[0]}" = "api2" ]; }; then
SERVERS=("${ARGS[0]}")
ARGS=("${ARGS[@]:1}")
else
SERVERS=(api1 api2)
fi
if [ ${#ARGS[@]} -eq 0 ]; then
PATHS=("${DEFAULT_PATHS[@]}")
else
PATHS=("${ARGS[@]}")
fi
for server in "${SERVERS[@]}"; do
upload_to "$server" "${PATHS[@]}"
echo
done
echo "完成。"