ギークなエンジニアを目指す男

機械学習系の知識を蓄えようとするブログ

Git入門(Branchやってみる編)

前回に続きGit記事第2弾です。

第1弾はこちら

taxa-program.hatenablog.com

今回はブランチを使ってみようと思います。

Branch (ブランチ)とは

ブランチは基本的にはリポジトリのコピーで、ブランチ上では元のファイルを触らずに新しいコードを書くなど、自由に変更や実験を試すことができます。通常、親リポジトリはmasterブランチと呼ばれ、トピックブランチ (短期間だけ使う一時的なブランチ) はcheckoutと-bフラグを使って作成できます。

ブランチの作成方法

下記コマンドで新規のブランチ(枝分かれ)を作成できます。

$ git checkout -b modify-first
Switched to a new branch 'modify-first'

現在どのブランチを使用しているかは下記で確認できます。
*印が付いているものが現在のブランチです。

$ git branch
  master
* modify-first

ファイルの編集

今回は特定のファイルの中身を変更して、commitまで行ってみます。
hello_app/README.md

# Ruby on Rails Tutorial

## "hello, world!"

This is the first application for the
[*Ruby on Rails Tutorial*](https://railstutorial.jp/)
by [Michael Hartl](http://www.michaelhartl.com/). Hello, world!

上記ファイルを変更後、ブランチの状態を確認してみると...

$ git status
On branch modify-first
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   README.md

no changes added to commit (use "git add" and/or "git commit -a")

READMEファイルが編集された形跡が確認できると思います。

ここで、ファイルへの変更を一括でコミットする-aオプションを追加し、コミットします。

$ git commit -a -m "Improve the README file"

ブランチのMerge (マージ)

ファイルの変更が終わったので、masterブランチにこの変更をマージ (merge) します。 まずはブランチの変更を行います。

$ git checkout master

この状態でhello_app/README.mdファイルを参照してみると元の記述に戻っているはずです。

この状態で下記コマンドを入力し、マージを行います。

$ git merge modify-first
Updating 629803c..9fbc7f3
Fast-forward
 README.md | 27 +++++----------------------

 1 file changed, 5 insertions(+), 22 deletions(-)

マージ後は、トピックブランチを削除して終了です。

$ git branch -d modify-first
Deleted branch modify-first (was 9fbc7f3).

以上、ブランチやってみる編でした。