go2Demo/sync.sh

81 lines
3.0 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
# ============================================================
# 脚本名称: git-force-sync.sh
# 功能描述: 强制让本地分支与远程仓库完全一致(远程覆盖本地)
# 警告提示: 会永久删除本地所有未提交的修改、未推送的提交和未跟踪的文件
# ============================================================
set -e # 遇到错误立即退出
# ---------- 颜色定义(提升可读性)----------
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# ---------- 1. 检查是否在 Git 仓库中 ----------
if ! git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
echo -e "${RED}错误:当前目录不是 Git 仓库${NC}"
exit 1
fi
# ---------- 2. 获取当前分支名 ----------
CURRENT_BRANCH=$(git branch --show-current)
if [ -z "$CURRENT_BRANCH" ]; then
echo -e "${RED}错误:当前处于 HEAD 分离状态detached HEAD请先切换到具体分支。${NC}"
exit 1
fi
echo -e "${BLUE}当前分支:${CURRENT_BRANCH}${NC}"
# ---------- 3. 检查本地是否有未提交的更改 ----------
if ! git diff --quiet || ! git diff --cached --quiet; then
echo -e "${YELLOW}⚠️ 检测到本地存在未提交的更改(包括已暂存和未暂存)。${NC}"
echo -e "${RED}这些更改将在同步后永久丢失!${NC}"
read -p "确定要继续吗?请输入 'yes' 以确认: " CONFIRM
if [ "$CONFIRM" != "yes" ]; then
echo -e "${GREEN}操作已取消。${NC}"
exit 0
fi
fi
# ---------- 4. 检查是否有未跟踪的文件(可选清理提示) ----------
UNTRACKED=$(git ls-files --others --exclude-standard | head -n 1)
if [ -n "$UNTRACKED" ]; then
echo -e "${YELLOW}⚠️ 检测到本地存在未跟踪的文件(如编译产物、日志等)。${NC}"
read -p "是否同步删除这些未跟踪文件?(y/N) " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
DO_CLEAN=true
else
DO_CLEAN=false
fi
else
DO_CLEAN=false
fi
# ---------- 5. 拉取远程最新引用 ----------
echo -e "${BLUE}正在从远程仓库获取最新引用...${NC}"
git fetch origin
# ---------- 6. 验证远程分支是否存在 ----------
if ! git rev-parse "origin/$CURRENT_BRANCH" > /dev/null 2>&1; then
echo -e "${RED}错误:远程不存在分支 origin/$CURRENT_BRANCH,请检查分支名。${NC}"
exit 1
fi
# ---------- 7. 执行强制覆盖(硬重置) ----------
echo -e "${BLUE}正在将本地重置为 origin/$CURRENT_BRANCH ...${NC}"
git reset --hard "origin/$CURRENT_BRANCH"
# ---------- 8. 清理未跟踪文件 ----------
if [ "$DO_CLEAN" = true ]; then
echo -e "${BLUE}正在删除所有未跟踪的文件和目录...${NC}"
git clean -fd
else
echo -e "${YELLOW}已跳过删除未跟踪文件。${NC}"
fi
# ---------- 9. 完成 ----------
echo -e "${GREEN}✅ 同步完成!本地分支 '${CURRENT_BRANCH}' 已与远程 'origin/${CURRENT_BRANCH}' 完全一致。${NC}"