Rebase the current branch onto the latest code from upstream/main, suitable for the scenario of syncing upstream updates in a fork repository.
Pre-checks
Before performing any operation, first check:
# 1. 确认 remote 配置
git remote -v
# 2. 确认当前分支
git branch --show-current
# 3. 检查是否有 upstream remote
git remote | grep -q upstream || echo "需要先添加 upstream remote"
If the user has not configured the upstream remote, ask the user for the upstream repository URL.
Workflow
Step 1: Fetch the latest upstream code
git fetch upstream
Step 2: Check the update status
# 你的提交
git log upstream/main..HEAD --oneline
# 上游更新
git log HEAD..upstream/main --oneline
Quick exit check:
- If there are no new commits upstream (
HEAD..upstream/mainis empty), directly inform the user:
✅ The current branch is already up to date, no sync needed. There are no new updates upstream.
Then ask the user whether they need to handle changes in the current working directory (if any), and end the process directly.
- If there are upstream updates, continue with the following steps.
Step 3: Handle uncommitted changes
Check whether there are uncommitted changes:
git status
If there are uncommitted changes, ask the user to choose:
- Stash then rebase(recommended) - stash the changes and restore them after the rebase is complete
- Commit first, then rebase - commit these changes, then rebase
- Discard changes - discard these changes
Step 4: Perform the Rebase
# 如果用户选择 stash
git stash push -m "temporary stash before rebase"
# 执行 rebase
git rebase upstream/main
If a conflict occurs during the rebase:
- List the conflicted files
- Guide the user to resolve the conflicts
- After resolving, run
git rebase --continue
Step 5: Restore the stashed changes
If changes were stashed earlier:
git stash pop
Step 6: Push the updates
After a successful rebase, a force push is required (because the history was rewritten):
# 先展示 rebase 后的 commit 历史
git log --oneline -5
# 询问用户确认后强制推送
git push origin <branch-name> --force
Important: A force push is an operation that rewrites history and must be confirmed with the user first.
Completion notice
After the operation is complete, inform the user:
- ✅ Rebase successful
- ✅ The PR has been automatically updated (GitHub PRs will automatically reflect the pushed new commits)
- If there are stashed files, explain the current state (staged/unstaged)
Common issues
upstream remote is not configured
git remote add upstream <upstream-repo-url>
Rebase conflict
- View conflicted files:
git status - Resolve conflicts manually
- Mark as resolved:
git add <files> - Continue the rebase:
git rebase --continue - If you want to abort:
git rebase --abort
Push rejected
If the force push fails, there may be new commits on the remote. Pull first, then rebase:
git pull origin <branch> --rebase
git push origin <branch> --force