コミットを新しいブランチに移動させる

Beginner

This tutorial is from open-source community. Access the source code

はじめに

Git は、開発者がコードベースに対して行った変更を追跡することができる強力なバージョン管理システムです。Git の便利な機能の 1 つは、コミットを 1 つのブランチから別のブランチに移動させる機能です。master ブランチに対して行った変更の一部が別のブランチで行われるべきだったことに気付いた場合、これは役立ちます。この実験では、master ブランチからのコミットを新しいブランチに移動させる方法を学びます。

コミットを新しいブランチに移動させる

この実験では、https://github.com/labex-labs/git-playground のリポジトリを使用します。あなたは master ブランチでプロジェクトを作業してきました。あなたが行った一部の変更は、別のブランチで行われるべきだったことに気付きました。これらの変更を feature と呼ばれる新しいブランチに移動させたいと思います。

  1. リポジトリをクローンし、ディレクトリに移動して ID を設定します。
git clone https://github.com/labex-labs/git-playground
cd git-playground
git config --global user.name "your-username"
git config --global user.email "your-email"
  1. master ブランチにチェックアウトします。
git checkout master
  1. hello.txt という名前のファイルを作成し、そこに "hello, world" を追加し、ステージングエリアに追加して、"Added hello.txt" というメッセージでコミットします。
echo "hello,world" >> hello.txt
git add.
git commit -m "Added hello.txt"
  1. feature という新しいブランチを作成して切り替えません。master ブランチで新しいブランチを作成するとき、新しいブランチの状態は master ブランチと同じです。つまり、新しいブランチのファイルは master ブランチのファイルと同じで、同じ内容とバージョン履歴を持っています。
git branch feature
  1. master の最後のコミットを元に戻します。
git reset HEAD~1 --hard
  1. master ブランチのコミット履歴と feature ブランチのコミット履歴を確認して結果を確認します。
git log
git checkout feature
git log

これが git log を実行した結果です。

commit 7969ab5d6606e2a40c9fd826c732206b835976e9 (HEAD -> feature)
Author: xiaoshengyunan <@users.noreply.github.com>
Date:   Fri Jul 21 20:19:22 2023 +0800

    Added hello.txt

まとめ

Git を使用して作業する際、コミットを 1 つのブランチから別のブランチに移動させることは便利な機能です。この実験では、git branchgit resetgit checkout コマンドを使用して、master ブランチからのコミットを新しいブランチに移動させる方法を学びました。これは、変更がローカルでのみコミットされており、リモートにプッシュされていない場合にのみ機能することを忘れないでください。