如何迁移已推送的Change1至分支并向两个远程推送不同分支
Let’s walk through how to safely move your Change 1 commits to a dedicated branch, get your master branch back in sync with production, and handle the urgent Change 2 deployment.
1. Preserve Change 1 in a new branch
Since all your Change 1 work is currently on master, create a new branch to lock in those commits:
git checkout -b feature/change1
This creates and switches to a new branch that includes every commit you made for Change 1. You now have a safe, separate copy of that work.
2. Reset master to match production
Next, we need to revert master back to the state it was in before you started Change 1.
First, find the commit hash that matches the production environment. Use git log to browse your commit history—look for the last commit that was deployed to production (the one right before your Change 1 began). Let’s call this hash <PROD_COMMIT_HASH>.
Switch back to master and reset it:
git checkout master git reset --hard <PROD_COMMIT_HASH>
The --hard flag will discard all changes on master made after <PROD_COMMIT_HASH>, so double-check that your Change 1 commits are fully present on feature/change1 first!
If you already pushed Change 1 to the remote master
Since you’ve already pushed your Change 1 commits to the remote, you’ll need to force-push the reset master to update the production remote. Warning: Only do this if no other developers have pulled the modified master branch—force-pushing can overwrite others’ work if they have those commits locally.
git push <LIVE_REMOTE> master --force
Replace <LIVE_REMOTE> with the name of your production server remote (e.g., live or origin if that’s your production target).
3. Deploy Change 2 to production
Now master matches the production environment, so you can safely implement your urgent Change 2 directly on master:
- Make your changes
- Commit them:
git add . && git commit -m "Urgent fix: Change 2 for production deployment" - Push to production:
git push <LIVE_REMOTE> master
4. Push Change 1 to staging
Switch back to your feature/change1 branch and push it to the staging server’s remote:
git checkout feature/change1 git push <STAGING_REMOTE> feature/change1
Replace <STAGING_REMOTE> with the name of your staging server remote (e.g., staging). If you haven’t added this remote yet, run git remote add staging <STAGING_SERVER_URL> first.
Key Notes:
- Coordinate with teammates: If other developers pulled the modified
masterbranch with Change 1, tell them to reset their localmasterwithgit fetch <LIVE_REMOTE> && git reset --hard <LIVE_REMOTE>/master. - Verify commits: Before resetting, use
git log feature/change1to confirm all your Change 1 commits are on the new branch. - Backup first: If you’re nervous about resetting, create a temporary backup branch of
masterfirst withgit checkout -b master-backup.
内容的提问来源于stack exchange,提问作者Ping

