%%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'rotateCommitLabel': true}} }%%
gitGraph
commit id: "813faa2"
branch test
commit id: "28a8bf7"
commit id: "466fbe7"
commit id: "30bf56a"
commit id: "6159140"
この記事はDangit, I accidentally committed something to master that should have been on a brand new branch!をベースにしています.
Problem
新しいGitリポジトリをセットアップしたとします.最初は testという名前の新しいブランチを作成して,README.mdファイルを編集する最初のコミットの後にそこで作業する予定でした. しかし,実際にはmainブランチでそのまま変更を続けてしまったとします.
▶ 当初の予定
▶ 実際のやらかし
%%{init: { 'logLevel': 'debug', 'theme': 'base', 'gitGraph': {'rotateCommitLabel': true}} }%%
gitGraph
commit id: "813faa2"
commit id: "28a8bf7"
commit id: "466fbe7"
commit id: "30bf56a"
commit id: "6159140"
Solution: git resetを用いた解決方法
▶ 方針
- 現在のHEADの状態を元に,新しい
testブランチを作成します。 - 最初のコミット直後の状態に
mainブランチをリセットします。 testブランチに切り替えます。
▶ Commands
## Step 1: 現在の内容をtest branchに保存する
% git branch test
## Step 2: main branchをきれいな状態に戻す
% git reset 813faa2 --hard
## Step 3: 開発ブランチをtestにする
% git switch test▶ 解説
git branch <branch-name>コマンドを使うと,現在のHEADを元に新しいブランチを作成できますが,ブランチの切り替えは行われませんgit reset --softではなくgit reset --hardを使うと,デフォルトで現在のブランチのインデックスやファイルに変更が残らないようにできます- もし現在のブランチに変更が残っている場合は,
git stashやgit cleanを実行する必要があります
警告 !
もし誤ったコミットをリモートリポジトリに既にプッシュしてしまった場合,他の開発者に迷惑をかける可能性があるため,上記の解決策を実行しないほうが良いです.