Files
Mycontent/scripts/gitea_sync.sh

95 lines
3.1 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.

#!/bin/bash
# ============================================
# 《一场soul的创业实验》→ Gitea 自动同步(与 GitHub fnvtk/Mycontent 同路径)
# 用法:有更新时在项目根目录执行 bash scripts/gitea_sync.sh
# 可选export GITEA_HTTP_PROXY=http://127.0.0.1:7897 外网时走代理
# ============================================
set -euo pipefail
REPO_DIR="${1:-$(cd "$(dirname "$0")/.." && pwd)}"
BRANCH="main"
REMOTE_GITEA="gitea"
REMOTE_ORIGIN="origin"
# 默认只同步 gitea如需同时同步 GitHub显式设置export SYNC_WITH_GITHUB=1
SYNC_WITH_GITHUB="${SYNC_WITH_GITHUB:-0}"
cd "$REPO_DIR" || exit 1
# 外网推送时可走代理与卡若AI Gitea 一致)
if [ -n "${GITEA_HTTP_PROXY:-}" ]; then
export HTTP_PROXY="$GITEA_HTTP_PROXY" HTTPS_PROXY="$GITEA_HTTP_PROXY" ALL_PROXY="$GITEA_HTTP_PROXY"
fi
if ! git rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo "[gitea_sync] 当前目录不是 Git 仓库:$REPO_DIR"
exit 1
fi
# 确保在 main避免把内容提交到错误分支
current_branch="$(git branch --show-current 2>/dev/null || true)"
if [ "$current_branch" != "$BRANCH" ]; then
echo "[gitea_sync] 当前分支=$current_branch,切换到 $BRANCH"
git checkout "$BRANCH" >/dev/null
fi
has_remote() {
local r="$1"
git remote get-url "$r" >/dev/null 2>&1
}
ff_merge_remote_branch() {
local remote="$1"
if ! has_remote "$remote"; then
return 0
fi
git fetch "$remote" "$BRANCH" --prune >/dev/null 2>&1 || true
# 仅允许快进合并,避免脚本自动制造复杂历史
if git show-ref --verify --quiet "refs/remotes/${remote}/${BRANCH}"; then
git merge --ff-only "${remote}/${BRANCH}" >/dev/null 2>&1 || {
echo "[gitea_sync] ❌ 无法 ff-only 合并 ${remote}/${BRANCH}(可能已分叉或有冲突),请手动处理后再同步。"
exit 1
}
fi
}
commit_if_needed() {
git add -A >/dev/null 2>&1 || true
if ! git diff --cached --quiet 2>/dev/null; then
local ts msg
ts="$(date '+%Y-%m-%d %H:%M')"
msg="🔄 同步 ${ts} | 一场soul的创业实验书稿"
git commit -m "$msg" --quiet 2>/dev/null || true
fi
}
# 1) 先把本地新增/删除提交掉,保证 pull 时可 rebase/ff
commit_if_needed
# 2) 再拉取远端新增(默认只拉 Gitea避免与 GitHub 分叉时阻塞同步)
ff_merge_remote_branch "$REMOTE_GITEA"
if [ "$SYNC_WITH_GITHUB" = "1" ]; then
ff_merge_remote_branch "$REMOTE_ORIGIN"
fi
# 3) 拉完后如果又产生本地变更(例如 merge 带来的更新),再补一次提交(一般不会)
commit_if_needed
# 4) 推送到 Gitea必须可选推送到 GitHub若配置了 origin
if has_remote "$REMOTE_GITEA"; then
git push "$REMOTE_GITEA" "$BRANCH" >/dev/null 2>&1 && \
echo "[gitea_sync] ✅ 已推送到 Gitea"
else
echo "[gitea_sync] ❌ 未配置 gitea 远程"
exit 1
fi
if [ "$SYNC_WITH_GITHUB" = "1" ] && has_remote "$REMOTE_ORIGIN"; then
git push "$REMOTE_ORIGIN" "$BRANCH" >/dev/null 2>&1 && \
echo "[gitea_sync] ✅ 已推送到 GitHuborigin"
fi
echo "[gitea_sync] 📌 仓库:$REPO_DIR"
echo "[gitea_sync] 🔚 完成"
exit 0