LoginSignup
2
1

More than 1 year has passed since last update.

git revert(間違ったコミットを打ち消したいとき )

Posted at

経緯 

railsにてログイン機能を実装していた時、うっかりdevelopブランチのまま作業をしていた...!

% git branch                        
* develop
  main

それに気づかないまま、git add . し、 git commit してしまった。(コミット名は、login_user としていました)

やったこと

コミットを取り消したいということで、git revert <commitID> コマンドを使いました。

git revert <commitID>

commitIDは、後述のgit log コマンドを入力して確認できます。

既存のコミットを取り消すためのコマンドです。
「取り消したいコミットを打ち消すようなコミットを新しく作成する」という処理によって、既存のコミットを取り消します。
新しくコミットを追加しているだけなので、既存コミットの履歴が消えるわけではありません(コミットログをみると残っています)。
どんな変更があったのかということが(revertしたということも含めて)残るので、リモートにpushされて公開されているコミットに対しても安全に使うことができます。

コミットIDを指定することで、そのコミットを打ち消すようなコミットが新しく追加されます。
コードは、そのコミットがなかったときの状態になります。
revertコマンドを実行するとエディタが開き、コミットメッセージを編集することができます
https://qiita.com/chihiro/items/2fa827d0eac98109e7ee

注意点

git reset という直前のcommitを取り消すコマンドとは似ていますが、挙動が異なります。
・git reset:  そのまま過去に戻す
・git revert: 「打ち消しするコミット」を新たに追加して、状況を戻す

下記の記事でわかりやすく書かれています。

% git revert 696f612a618958b77e9677e89146711586e24d90
[develop 2efe394] Revert "login_user"
 Committer: **** <***.local>
Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:

    git config --global user.name "Your Name"
    git config --global user.email you@example.com

After doing this, you may fix the identity used for this commit with:

    git commit --amend --reset-author

 10 files changed, 66 insertions(+), 119 deletions(-)

git log

git log をみると、最新のコミット名の前にRevertが付与されているのがわかります。

% git log
commit 2efe39460fded828917cf8db02c20a6ff17a24d1 (HEAD -> develop)
Author: **** <****.local>
Date:   Sat Dec 24 06:53:27 2022 +0900

    Revert "login_user"   #こちら
    
    This reverts commit 696f612a618958b77e9677e89146711586e24d90.

commit 696f612a618958b77e9677e89146711586e24d90
Author: **** <****.local>
Date:   Sat Dec 24 06:50:36 2022 +0900

    login_user

commit 9b17c66b3e08b90867d96b91b86b1d63961fbe60 (origin/develop)
Merge: 9634da5 d0df5be
Author: **** <****@users.noreply.github.com>
Date:   Tue Dec 20 08:40:18 2022 +0900

新しいブランチへ切り替え

commit前の状態に戻ったところで、git checkout -b (作成したいブランチ名) で、developからブランチを切りました。
「-b」オプションを指定することで、ブランチの作成とチェックアウトを同時に行うことができます。

今回は、feature/login_user というブランチ名にしました。(ややこしいですが、コミット名と同じです)

% git checkout -b feature/login_user
Switched to a new branch 'feature/login_user'
% git branch                        
  develop
* feature/login_user #こちら
  main

補足ですが、以下のコマンドでもブランチの作成はできます。

git branch <branchname>

参考記事

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1