本記事ではGitHub Flowのように機能追加やバグ修正などの度にブランチを作成して開発を進める際によく利用する機能をユースケースに分けて紹介します。本記事のキーワードはstashrebasecherry-pickです。 これらの機能を利用することで、複数のブランチで非同期的に開発が進んでも、簡単に差分を自分のワーキングディレクトリに取り組むことができるようになります。

目次

(stash) プログラムを編集後にブランチを作成したい

プログラムを編集しているときに、ブランチがmasterだったことはよくあると思います。 その場合は git stash を使います。 git stashを実行することで、まだステージングしておらず、ワーキングディレクトリにある差分を一時的に退避することができます。

git stash  # ワーキングディレクトリの内容を一時退避
git branch <新しいブランチ>  # 新しいブランチの作成
git checkout <新しいブランチ>  # 新しいブランチに移動
git stash pop  # 一時退避していたワーキングディレクトリを新しいブランチに反映

git stash popで以下のようなエラーが出たら、新しいブランチでの差分をcommitした後にサイド実行します。

error: Your local changes to the following files would be overwritten by merge:
Please commit your changes or stash them before you merge.
Aborting

差分をまだコミットしていないなら、stashを使わずにgit checkout <新しいブランチ> を実行するだけで良いです。

(rebase) ブランチの開始地点を最新のmasterにしたい

開発用ブランチを作ったあとに、そのブランチの開始地点であったmasterブランチが進んでいたとします。 現在のmasterブランチを改めて開発用ブランチの開始地点としたいときは git rebase を使います。

git checkout master  # masterブランチに移動
git pull origin master  # リモートのmasterとの差分をローカルのmasterに反映
git checkout <開発ブランチ>  # 開発ブランチに移動
git rebase master  # 開発ブランチの開始時点をmasterにする

git rebase master実行後、以下のようにエラーが出た場合は、エラー中にあるファイルのコンフリクトを解消した後にgit addgit rmで差分をステージングします。その後 git rebase --continueを実行してrebaseを完了します。

CONFLICT (content): Merge conflict in <ファイル名>
error: Failed to merge in the changes.
Patch failed at 0001 add <ファイル名>
hint: Use 'git am --show-current-patch' to see the failed patch
Resolve all conflicts manually, mark them as resolved with
"git add/rm <conflicted_files>", then run "git rebase --continue".
You can instead skip this commit: run "git rebase --skip".
To abort and get back to the state before "git rebase", run "git rebase --abort".

(cherrypick) 開発用ブランチの一部のコミットを別のブランチに取り込みたい

開発用ブランチでいくつか差分をコミットしていて、その一部をmasterブランチに反映させたいときは git cherrypick を使います。

git checkout <差分を取り込みたいブランチ>  # 差分を取り込みたいブランチに移動
git cherry-pick <コミットID>  # 指定したコミットの内容を今いるブランチに反映

git cherry-pick <コミットID>実行後、以下のようにエラーが出た場合は、エラー中にあるファイルのコンフリクトを解消します。

error: could not apply <コミットID>... add <ファイル名>
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'

まとめ

本記事はGitを用いたソフトウェア開発において、複数のブランチを利用して開発する際に便利なGitの機能をご紹介しました。便利な機能としてstashrebasecherry-pickの3つを紹介しました。


関連記事


最近の記事