# Git 代码自动同步详细说明 ## 一、概述 Git 代码自动同步是指通过自动化手段,将本地代码变更自动推送到远程仓库(或反之),减少手动操作步骤,保证多设备/多人协作时代码始终一致。 --- ## 二、核心概念 | 概念 | 说明 | |------|------| | **远程仓库(Remote)** | GitHub / GitLab / Gitee / GOG 等托管平台上的仓库 | | **本地仓库(Local)** | 开发者机器上的 `.git` 仓库 | | **Push** | 本地 → 远程,上传自己的提交 | | **Pull** | 远程 → 本地,拉取他人的更新 | | **Fetch + Merge** | Pull 的底层实现,先拉取再合并 | | **Hook** | Git 生命周期回调,可在特定事件时自动触发脚本 | --- ## 三、自动同步的几种典型方案 ### 方案 1:Git Hook 自动 Push(本地变更后自动推送) **适用场景**:本地提交后自动推送到远程,适合单人多设备同步。 **实现步骤**: ```bash # 1. 进入仓库目录 cd /path/to/your/repo # 2. 创建 post-commit hook cat > .git/hooks/post-commit << 'EOF' #!/bin/bash # 提交后自动推送 git push origin $(git branch --show-current) 2>&1 | tee -a .git/hooks/push.log EOF # 3. 赋予执行权限 chmod +x .git/hooks/post-commit ``` **注意**: - 需要预先配置好 SSH Key 或 Credential,避免每次 push 都要求输入密码 - 如果远程有冲突,push 会失败,需手动解决 --- ### 方案 2:定时自动 Pull + Push(Cron / 任务计划) **适用场景**:定时双向同步,适合服务器和开发机之间保持同步。 **Linux Cron 实现**: ```bash # 编辑 crontab crontab -e # 每 5 分钟自动 pull + push */5 * * * * cd /path/to/repo && git pull --rebase origin main && git push origin main >> /var/log/git-sync.log 2>&1 ``` **Windows 任务计划实现**(PowerShell): ```powershell # 创建同步脚本 sync.ps1 Set-Location "C:\path\to\repo" git pull --rebase origin main git push origin main # 使用 Windows 任务计划程序创建定时任务 $action = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "-File C:\path\to\sync.ps1" $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 5) Register-ScheduledTask -TaskName "GitAutoSync" -Action $action -Trigger $trigger ``` --- ### 方案 3:文件监听自动同步(inotify / fswatch) **适用场景**:文件保存后实时同步,无需等待 cron 周期。 **Linux(inotifywait)**: ```bash #!/bin/bash # auto-sync.sh REPO_DIR="/path/to/repo" BRANCH="main" inotifywait -m -r -e close_write,move,create,delete "$REPO_DIR" | while read -r directory events filename; do cd "$REPO_DIR" git add -A git diff --cached --quiet || { git commit -m "auto sync: $(date '+%Y-%m-%d %H:%M:%S')" git push origin "$BRANCH" } done ``` **macOS(fswatch)**: ```bash brew install fswatch fswatch -r /path/to/repo --event Updated --event Created --event Removed | while read event; do cd /path/to/repo git add -A git diff --cached --quiet || { git commit -m "auto sync: $(date '+%Y-%m-%d %H:%M:%S')" git push origin main } done ``` --- ### 方案 4:使用 Git Bundle 离线同步 **适用场景**:两台机器不联网,通过 U 盘等介质同步。 ```bash # 机器 A:打包变更 git bundle create /media/usb/repo.bundle --all # 机器 B:从 bundle 拉取 git pull /media/usb/repo.bundle main ``` --- ### 方案 5:使用 rsync + Git 混合方案 **适用场景**:大量非代码文件(如编译产物)也需要一起同步。 ```bash #!/bin/bash # 1. 先 git 同步代码 cd /path/to/repo git add -A && git commit -m "auto sync" && git push origin main # 2. 再 rsync 同步构建产物 rsync -avz --exclude='.git' /path/to/repo/ user@remote:/path/to/repo/ ``` --- ## 四、SSH Key 免密配置(前提条件) 自动同步的前提是免密认证: ```bash # 1. 生成 SSH Key(如果没有) ssh-keygen -t ed25519 -C "your_email@example.com" # 2. 复制公钥到远程平台 cat ~/.ssh/id_ed25519.pub # 粘贴到 GitHub/GitLab/Gitee 的 SSH Keys 设置中 # 3. 测试连接 ssh -T git@github.com ``` --- ## 五、冲突处理策略 自动同步最大的风险是冲突。推荐策略: | 场景 | 策略 | |------|------| | 单人多设备 | 使用 `pull --rebase`,避免无意义 merge commit | | 多人协作 | 不自动 push,改为 CI/CD 自动 pull 和测试 | | 纯文档类 | 可接受 occasional conflict,用 `ours` 或 `theirs` 策略 | | 二进制文件 | 使用 Git LFS 或改用 rsync 方案 | **自动解决冲突的配置**(仅限单人场景): ```bash # 优先使用远程版本 git config pull.rebase true git config rerere.enabled true # 或者冲突时自动选择一方 git config merge.strategy.option theirs # 远程优先 ``` --- ## 六、完整自动化脚本示例 ```bash #!/bin/bash # git-auto-sync.sh - 完整的自动同步脚本 # 用法: ./git-auto-sync.sh [仓库路径] [远程名] [分支名] REPO_DIR="${1:-.}" REMOTE="${2:-origin}" BRANCH="${3:-main}" LOG_FILE="$REPO_DIR/.git/auto-sync.log" log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG_FILE" } cd "$REPO_DIR" || exit 1 # 检查是否有未提交的变更 if [[ -n "$(git status --porcelain)" ]]; then git add -A git commit -m "auto sync: $(date '+%Y-%m-%d %H:%M:%S')" log "Committed local changes" fi # 拉取远程更新(rebase 方式) if git pull --rebase "$REMOTE" "$BRANCH" >> "$LOG_FILE" 2>&1; then log "Pull success" else log "Pull failed - conflict?" git rebase --abort exit 1 fi # 推送本地提交 if git push "$REMOTE" "$BRANCH" >> "$LOG_FILE" 2>&1; then log "Push success" else log "Push failed" exit 1 fi ``` --- ## 七、注意事项 1. **安全性**:自动 push 前确保不会泄露敏感信息(密钥、密码等),建议使用 `.gitignore` 排除 2. **网络依赖**:自动 push 失败时要有重试或告警机制 3. **提交粒度**:自动 commit 会产生大量细粒度提交,建议定期 `git rebase -i` 整理 4. **备份策略**:重要项目建议保留多个 remote 做冗余 5. **权限隔离**:CI/CD 场景使用 Deploy Key 而非个人 SSH Key --- ## 八、推荐方案选择 | 你的情况 | 推荐方案 | |----------|----------| | 单人,2台设备,偶尔同步 | 方案2:Cron 定时 Pull | | 单人,实时同步需求 | 方案3:文件监听自动同步 | | 多人协作 | 不建议自动 push,改为 CI/CD 自动测试 | | 离线环境 | 方案4:Git Bundle | | 大文件 + 代码混合 | 方案5:rsync + Git | --- *文档生成时间:2026-10-02*