DEV Community

d.yoshimitsu
d.yoshimitsu

Posted on

git add -pのすゝめ

うっかり秘匿情報をプッシュした経験はありませんか?
そんな悲劇を回避するためのtipsです。

そもそも

$ git add -A するな。
force push並の大罪やぞ。悔い改めろ。

git add -pとは

Git - git-add Documentationからの引用

-p
--patch
Interactively choose hunks of patch between the index and the work tree and add them to the index. This gives the user a chance to review the difference before adding modified contents to the index.

This effectively runs add --interactive, but bypasses the initial command menu and directly jumps to the patch subcommand. See “Interactive mode” for details.

要するにaddするに差分を対話的に確認できるコマンドです。

Let's try

ワーキングツリーに差分がある状態で、 $ git add -p してみてください。

Screen Shot 2018-12-07 at 23.32.29.png

こんな感じになるはずです。
差分の塊(hunk)をステージするかを対話的に聞かれるので、[y,n,q,a,d,e,?]を使って、処理していきます。

Stage this hunk [y,n,q,a,d,e,?]? 

困ったときは?を実行してください。helpが表示されます。

y - stage this hunk
n - do not stage this hunk
q - quit; do not stage this hunk or any of the remaining ones
a - stage this hunk and all later hunks in the file
d - do not stage this hunk or any of the later hunks in the file
g - select a hunk to go to
/ - search for a hunk matching the given regex                                                                                                                        い。
j - leave this hunk undecided, see next undecided hunk
J - leave this hunk undecided, see next hunk
e - manually edit the current hunk
? - print help

なんだか色々あって不安になるかもしれませんが、ynの2つを覚えれば大丈夫です。

  • y
    差分の塊(hunk)をステージングします。
    差分の内容を確認し問題なければyです。

  • n
    差分の塊(hunk)をステージングしません。
    差分の内容を確認し意図しない秘匿情報や、デバッグログ出力等が含まれていた場合はnです。

一つ処理するとまた次の差分が自動的に表示され、全ての差分に対して処理するまで続きます。
q で強制的にそれ以降を全てステージングせずにadd -pを終了することも出来ます。

上記の処理を繰り返してステージングが完了したら、いつものようにcommitを行ってください。

Screen Shot 2018-12-07 at 23.37.51.png

反省

force push並の大罪やぞ。悔い改めろ。

とかいいながら、サンプルプロジェクト作るときに-Aを使ってしまいました。悔い改めます。

Latest comments (0)