¿Cómo corregir la confirmación a la rama Git incorrecta?


Acabo de hacer un commit perfectamente bueno a la rama equivocada. ¿Cómo deshago la última confirmación en mi rama master y luego tomo esos mismos cambios y los introduzco en mi rama upgrade?

Author: mikewilliamson, 2010-05-31

8 answers

Si aún no ha empujado sus cambios, también puede hacer un reinicio suave:

git reset --soft HEAD^

Esto revertirá la confirmación, pero volverá a poner los cambios confirmados en su índice. Suponiendo que las ramas están relativamente actualizadas entre sí, git te permitirá hacer un checkout en la otra rama, con lo que simplemente puedes confirmar:

git checkout branch
git commit

La desventaja es que necesita volver a ingresar su mensaje de confirmación.

 733
Author: Blair Holloway,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-05-31 05:53:20

Si tiene una copia de trabajo limpia (sin modificar)

Para revertir una confirmación (asegúrese de anotar el hash de la confirmación para el siguiente paso):

git reset --hard HEAD^

Para tirar de esa confirmación en una rama diferente:

git checkout other-branch
git cherry-pick COMMIT-HASH

Si tiene cambios modificados o sin seguimiento

También tenga en cuenta que git reset --hard eliminará cualquier cambio no rastreado y modificado que pueda tener, por lo que si tiene esos podría preferir:

git reset HEAD^
git checkout .
 93
Author: Michael Mrozek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-18 07:37:13

4 años de retraso en el tema, pero esto podría ser útil para alguien.

Si olvidó crear una nueva rama antes de commit y commited all en master, no importa cuántas confirmaciones haya hecho, el siguiente enfoque es más fácil:

git stash                       # skip if all changes are committed
git branch my_feature
git reset --hard origin/master
git checkout my_feature
git stash pop                   # skip if all changes were committed

Ahora tienes tu rama maestra igual a origin/master y todas las nuevas confirmaciones están en my_feature. Tenga en cuenta que my_feature es una rama local, no remota.

 86
Author: fotanus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-01 16:45:07

Si ya ha empujado sus cambios, tendrá que forzar su siguiente empujón después de restablecer la CABEZA.

git reset --hard HEAD^
git merge COMMIT_SHA1
git push --force

Advertencia: un hard reset deshará cualquier modificación no confirmada en su copia de trabajo, mientras que un force push sobrescribirá completamente el estado de la rama remota con el estado actual de la rama local.

Por si acaso, en Windows (usando la línea de comandos de Windows, no Bash) es en realidad cuatro ^^^^ en lugar de uno, por lo que es

git reset --hard HEAD^^^^
 17
Author: Igor Zevaka,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-18 07:32:24

Recientemente hice lo mismo, cuando accidentalmente cometí un cambio a master, cuando debería haber cometido a otra rama. Pero no empujé nada.

Si acabas de comprometer a la rama incorrecta, y no has cambiado nada desde entonces, y no has empujado al repositorio, entonces puedes hacer lo siguiente:

// rewind master to point to the commit just before your most recent commit.
// this takes all changes in your most recent commit, and turns them into unstaged changes. 
git reset HEAD~1 

// temporarily save your unstaged changes as a commit that's not attached to any branch using git stash
// all temporary commits created with git stash are put into a stack of temporary commits.
git stash

// create other-branch (if the other branch doesn't already exist)
git branch other-branch

// checkout the other branch you should have committed to.
git checkout other-branch

// take the temporary commit you created, and apply all of those changes to the new branch. 
//This also deletes the temporary commit from the stack of temp commits.
git stash pop

// add the changes you want with git add...

// re-commit your changes onto other-branch
git commit -m "some message..."

NOTA: en el ejemplo anterior, estaba rebobinando 1 commit con git reset HEAD~1. Pero si quieres rebobinar n confirmaciones, entonces puedes hacer git reset CABEZA~n.

Además, si terminaste comprometiéndote con la rama incorrecta, y también terminaste escribiendo algo más de código antes de darte cuenta de que te comprometiste con la rama incorrecta, entonces podrías usar git stash para guardar tu trabajo en progreso:

// save the not-ready-to-commit work you're in the middle of
git stash 

// rewind n commits
git reset HEAD~n 

// stash the committed changes as a single temp commit onto the stack. 
git stash 

// create other-branch (if it doesn't already exist)
git branch other-branch

// checkout the other branch you should have committed to.
git checkout other-branch

// apply all the committed changes to the new branch
git stash pop

// add the changes you want with git add...

// re-commit your changes onto the new branch as a single commit.
git commit -m "some message..."

// pop the changes you were in the middle of and continue coding
git stash pop

NOTA: He utilizado este sitio web como referencia https://www.clearvision-cm.com/blog/what-to-do-when-you-commit-to-the-wrong-git-branch/

 9
Author: Ali Mizan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-30 21:51:29

Así que si su escenario es que usted ha comprometido a master pero la intención de comprometerse a another-branch (que puede o no puede no existir ya) pero no ha empujado todavía, esto es bastante fácil de arreglar.

// if your branch doesn't exist, then add the -b argument 
git checkout -b another-branch
git branch --force master origin/master

Ahora todos tus commits a master estarán en another-branch.

Obtenido con amor de: http://haacked.com/archive/2015/06/29/git-migrate /

 5
Author: Lorcan O'Neill,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-08 13:19:46

Si la rama a la que quería aplicar sus cambios ya existe (branch develop, por ejemplo), siga las instrucciones que proporcionó fotanus a continuación, entonces:

git checkout develop
git rebase develop my_feature # applies changes to correct branch
git checkout develop # 'cuz rebasing will leave you on my_feature
git merge develop my_feature # will be a fast-forward
git branch -d my_feature

Y obviamente podrías usar tempbranch o cualquier otro nombre de rama en lugar de my_feature si quisieras.

También, si corresponde, retrasa el pop del alijo (aplicar) hasta después de que hayas fusionado en tu rama de destino.

 0
Author: fbicknel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:03:09

Si se encuentra con este problema y tiene Visual Studio, puede hacer lo siguiente:

Haga clic con el botón derecho en su rama y seleccione View History:

introduzca la descripción de la imagen aquí

Haga clic con el botón derecho en la confirmación a la que desea volver. Y Revertir o restablecer según sea necesario.

introduzca la descripción de la imagen aquí

 0
Author: Trevor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-04 23:39:24