44 lines
1.7 KiB
Bash
Executable File
44 lines
1.7 KiB
Bash
Executable File
#!/usr/bin/env bash
|
||
# 与 Gitea(192.168.1.201)双向同步:先拉取,有本地变更则提交并推送
|
||
# 可手动执行,也可由 launchd 每 10 分钟执行
|
||
|
||
set -e
|
||
REPO_ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
|
||
REMOTE="gitea-local"
|
||
LOG_FILE="$REPO_ROOT/.cursor/scripts/gitea-sync.log"
|
||
|
||
cd "$REPO_ROOT"
|
||
BRANCH=$(git rev-parse --abbrev-ref HEAD)
|
||
|
||
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" | tee -a "$LOG_FILE"; }
|
||
|
||
log "--- sync start (branch=$BRANCH, remote=$REMOTE) ---"
|
||
|
||
# 1. 拉取远程更新(若远程无此分支则仅 fetch)
|
||
git fetch "$REMOTE" 2>&1 | tee -a "$LOG_FILE" || true
|
||
if git ls-remote --exit-code --heads "$REMOTE" "$BRANCH" &>/dev/null; then
|
||
git pull "$REMOTE" "$BRANCH" --no-edit 2>&1 | tee -a "$LOG_FILE" || log "pull 失败或冲突,继续尝试推送本地变更"
|
||
else
|
||
log "远程无 $REMOTE/$BRANCH,仅 fetch"
|
||
fi
|
||
|
||
# 2. 若有本地未提交变更,则提交并推送
|
||
STATUS=$(git status -s)
|
||
if [ -n "$STATUS" ]; then
|
||
git add -A
|
||
git commit -m "sync: $(date '+%Y-%m-%d %H:%M')" 2>&1 | tee -a "$LOG_FILE" || log "commit failed (nothing to commit or conflict)"
|
||
git push "$REMOTE" "$BRANCH" 2>&1 | tee -a "$LOG_FILE" || log "push failed"
|
||
else
|
||
# 若有已提交但未推送的提交,也推送(仅当远程有此分支且本地比远程多提交时)
|
||
if git ls-remote --exit-code --heads "$REMOTE" "$BRANCH" &>/dev/null; then
|
||
AHEAD=$(git rev-list "refs/remotes/${REMOTE}/${BRANCH}"..HEAD --count 2>/dev/null || echo 0)
|
||
if [ "${AHEAD:-0}" -gt 0 ]; then
|
||
git push "$REMOTE" "$BRANCH" 2>&1 | tee -a "$LOG_FILE" || log "push failed"
|
||
fi
|
||
else
|
||
git push -u "$REMOTE" "$BRANCH" 2>&1 | tee -a "$LOG_FILE" || log "push (new branch) failed"
|
||
fi
|
||
fi
|
||
|
||
log "--- sync end ---"
|