「git reset」コマンドを試していきましょう。まずは、「--soft」オプションを試してみます。
「--soft」オプションを指定した場合、HEADが指すブランチの移動だけが行われます。ステージングエリアや作業ディレクトリは操作されません。この動作を利用して2つのコミットを1つのコミットにまとめる手順を解説していきます。
「git reset」コマンドを試すための環境を作ります。
適当なディレクトリに移動し、Gitリポジトリを作成します。そして、コミットを3回行います。
$ cd /Users/hirayashingo/Documents/hello-git-6 $ git init Initialized empty Git repository in /Users/hirayashingo/Documents/hello-git-6/.git/ $ echo one > numbers.txt $ git add numbers.txt $ git commit -m "first commit" [master (root-commit) 96c3a6a] first commit 1 file changed, 1 insertion(+) create mode 100644 numbers.txt $ echo two >> numbers.txt $ git add numbers.txt $ git commit -m "second commit" [master 03bcaed] second commit 1 file changed, 1 insertion(+) $ echo three >> numbers.txt $ git add numbers.txt $ git commit -m "third commit" [master 727d2f8] third commit 1 file changed, 1 insertion(+)
ここで、テキストファイルの内容とコミットログを確認してみます。コミットごとに1行ずつ文字列が追加されるコミット履歴が作られました。
$ cat numbers.txt one two three $ git log -p commit 727d2f8ef84f396acdf38647b0063931d0d8dece Author: Shingo Hiraya <shingohiraya@example.com> Date: Thu Oct 20 07:45:55 2016 +0900 third commit diff --git a/numbers.txt b/numbers.txt index 814f4a4..4cb29ea 100644 --- a/numbers.txt +++ b/numbers.txt @@ -1,2 +1,3 @@ one two +three commit 03bcaed4ebbba1c296f19efbc5ca0e39454dbc34 Author: Shingo Hiraya <shingohiraya@example.com> Date: Thu Oct 20 07:45:38 2016 +0900 second commit diff --git a/numbers.txt b/numbers.txt index 5626abf..814f4a4 100644 --- a/numbers.txt +++ b/numbers.txt @@ -1 +1,2 @@ one +two commit 96c3a6adf606e2219e31a3911e73f8f65983113a Author: Shingo Hiraya <shingohiraya@example.com> Date: Thu Oct 20 07:45:24 2016 +0900 first commit diff --git a/numbers.txt b/numbers.txt new file mode 100644 index 0000000..5626abf --- /dev/null +++ b/numbers.txt @@ -0,0 +1 @@ +one
「git reset --soft」コマンドを使用して、コミット「727d2f8」「03bcaed」を1つのコミットにまとめます。
現在、HEADはmasterを指し、masterはコミット「727d2f8」を指しています。
$ git log --oneline --decorate 727d2f8 (HEAD -> master) third commit 03bcaed second commit 96c3a6a first commit
「git reset --soft HEAD~2」コマンドを使用してmasterが指すコミットを2つ前のコミットに移動させます。「HEAD~2」はHEADの2つ前のコミットを指します。今回は「96c3a6a」を指します。
$ git reset --soft HEAD~2
masterが2つ前のコミット(1番目のコミット)を指すようになりました。コミット「727d2f8」と「03bcaed」はコミット履歴から消えました。
$ git log --oneline --decorate 96c3a6a (HEAD -> master) first commit
ステータスを確認すると、numbers.txtに対する変更はステージングエリアに残っています。「準備」で行った変更(2〜3行目の追加)がコミットされていない状態に戻っています。
$ git status On branch master Changes to be committed: (use "git reset HEAD <file>..." to unstage) modified: numbers.txt
ここでコミットを実行すれば、もともと2つのコミットに分かれていた変更が1つのコミットにまとまります。
$ git commit -m "add two and three" [master 4187dcf] add two and three 1 file changed, 2 insertions(+)
作業ディレクトリがクリーンになり、コミット履歴が2件になりました。
$ git status On branch master nothing to commit, working directory clean $ git log --oneline --decorate 4187dcf (HEAD -> master) add two and three 96c3a6a first commit
「git reset」コマンドと「--soft」オプションを使用してコミットをまとめる操作はこれで完了です。
Copyright © ITmedia, Inc. All Rights Reserved.