LoginSignup
2

More than 3 years have passed since last update.

Git で特定のコミットの特定のファイルだけ取り出したい

Posted at

特定のコミットの内容を取り込むなら cherry-pick でできます。
だけどさらに、その中の特定のファイルの差分だけ取り込んで、他は無視したい場合はどうする? という話です。

TL;DR

git checkout -p でできます。

git checkout (-p|--patch) [<tree-ish>] [--] [<paths>...]

使い方

$ git diff HEAD daa154e hoge.txt  # カレントブランチとの差分を確認する
diff --git a/hoge.txt b/hoge.txt
index e42f4ce..2262de0 100644
--- a/hoge.txt
+++ b/hoge.txt
@@ -1,2 +1 @@
 hoge
-fuga

$ git checkout -p daa154e hoge.txt  # 差分をインデックスに反映する
diff --git b/hoge.txt a/hoge.txt
index 2262de0..e42f4ce 100644
--- b/hoge.txt
+++ a/hoge.txt
@@ -1 +1,2 @@
 hoge
+fuga
(1/1) Apply this hunk to index and worktree [y,n,q,a,d,e,?]? y

$ git diff --staged  # インデックスに反映されたことを確認する
diff --git a/hoge.txt b/hoge.txt
index 2262de0..e42f4ce 100644
--- a/hoge.txt
+++ b/hoge.txt
@@ -1 +1,2 @@
 hoge
+fuga

(1/1) Apply this hunk to index and worktree [y,n,q,a,d,e,?]? の部分はインタラクティブになっていて、 y を選ぶと表示されている箇所の差分が取り込まれます。
? で各コマンドの内容を確認できます。

(1/1) Apply this hunk to index and worktree [y,n,q,a,d,e,?]? ?
y - apply this hunk to index and worktree
n - do not apply this hunk to index and worktree
q - quit; do not apply this hunk or any of the remaining ones
a - apply this hunk and all later hunks in the file
d - do not apply this hunk or any of the later hunks in the file
e - manually edit the current hunk
? - print help

コミットハッシュの部分は tree-ish なのでブランチ名やタグ名を指定して取り込むこともできます。

おまけ

Git でこれやりたいけどコマンド分からん...ってときは Git Explorer というサイトが便利です。
今回の git checkout -p は "I want to" から "merge" -> "merge a single file from one branch to another." の順に選択して発見しました。

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
What you can do with signing up
2