0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Gitでコミットを一つにまとめたい

0
Posted at

概要

複数コミットを一つのコミットにまとめたい

手順

1. 作業中の変更をコミットまたはスタッシュする

現在作業中の変更があれば、コミットするかスタッシュ(退避)してください。
未保存の変更があるとリベースを始められません。

   git add .
   git commit -m "WIP" # 必要に応じてコミットメッセージを付ける

または、変更をスタッシュする場合

   git stash

2. リベースを開始

まとめるコミットの数を確認した上で、git rebase -i HEAD~<コミット数> を実行します。
例えば、過去5つのコミットをまとめたい場合

   git rebase -i HEAD~5

3. インタラクティブリベースの設定

コマンドを実行すると、デフォルトのエディタ(例: Vim)が開き、以下のような画面が表示されます

   pick 123abc Initial commit
   pick 456def Added email validation
   pick 789ghi Fixed resend bug
   pick abc123 Refactored validation code
   pick def456 Final tweaks

ここで、最初のコミット (例: 123abc) はそのまま pick のままにします。他のコミットに対しては squash(または省略して s)に変更してください。
例:

   pick 123abc Initial commit
   squash 456def Added email validation
   squash 789ghi Fixed resend bug
   squash abc123 Refactored validation code
   squash def456 Final tweaks

squash の意味:対象のコミットを直前のコミットに統合します。

4. コミットメッセージを編集する

次に、統合後のコミットメッセージの編集画面が開きます。ここで、まとまったコミットの説明を1つに記述し、不要なメッセージは削除できます。
例:

   # This is a combination of 5 commits.
   # The first commit's message is:
   Initial commit

   # The following commit messages will also be included:
   Added email validation
   Fixed resend bug
   Refactored validation code
   Final tweaks

必要に応じて、以下のように1つのメッセージに整理します:

   Added email validation and fixed related issues.

保存してエディタを閉じます。

5. リベースの完了

リベースが正常に完了すると、Gitは自動的に統合されたコミットを更新します。

6. 作業内容を確認

まとめられた状態を確認するには、以下のコマンドを使用します

   git log

まとめられた1つのコミットが表示されるはずです。

7. リモートブランチへの反映

リモートブランチに変更を反映する場合は、--force(または短縮形の -f)オプションを利用してプッシュします。
注意:この操作は強制プッシュなので、リモートの履歴が上書きされます。

   git push --force

プロダクトに向き合い、ユーザーとつながる開発を。
ネットネイティブでは、そんなエンジニアを歓迎しています
https://www.wantedly.com/companies/mdpr

0
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?