普段重宝しているGitのコマンドのオプション

Nyle
Nyle Engineering Blog
4 min readJan 14, 2014

はじめまして。エンジニアの黒砂糖です。

突然ですがGit、便利ですよね。入社した当初はまだGitを使っていなくて、こんな資料を作ってGitの社内普及につとめたりしてました。最近では社内にGitが普及して、おかげさまで潜む事無く堂々とGitを使って仕事ができています。

さて、今日も楽しくGitと一緒にお仕事しているわけですが、どうにもまだsvn的な使い方でとどまっている人も多いようです。そこで、社内への啓蒙の意味もこめてGitのコマンドの覚えると便利なオプションを紹介していこうと思います。

git add -p

普段使い慣れているgit addも、-pをつけるとファイル単位どころか変更した部分(=ハンク)単位でのステージングが可能です。

$ git add -p
diff --git a/test_file b/test_file
index 9d4c2c0..a5e313c 100644
--- a/test_file
+++ b/test_file
@@ -1,3 +1,3 @@
this is a test file.
-before change.
+after change.
end of file.
Stage this hunk [y,n,q,a,d,/,e,?]?

「このハンクどうするの?」とか聞かれてます。ここで?を入力してヘルプがみれます。

y - stage this hunk
n - do not stage this hunk
q - quit; do not stage this hunk nor any of the remaining ones
a - stage this hunk and all later hunks in the file
d - do not stage this hunk nor 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
k - leave this hunk undecided, see previous undecided hunk
K - leave this hunk undecided, see previous hunk
s - split the current hunk into smaller hunks
e - manually edit the current hunk
? - print help

ちなみに自分はy,n,sくらいしか使いません。あ、稀にeも使うかな。y、nは分かりやすいと思うんですが、sが面白いです。最初の例みたいに小さいハンクだと出てこないんですが、でっかいハンクで出てきちゃった時はsが選べます。こいつを選べば「大きすぎたよね?ごめんね、もう少し小さくして出し直すね?」とちっさいハンクでやり直してくれます。それでもまだ大きかったりゴミがついているときは、eを選んでやれば一行単位で+や-をつけ外して細かく指定してやることもできます。ただこれ、毎回混乱するのであまりオススメはできません^^;

git reset -p

ブラックにはホワイト、ノボリにはクダリ、git add -pにはもちろんgit reset -pです。

git reset -pも基本的にはgit add -pと同じでハンク単位でステージングから変更を取り除く事が可能です。ただ残念なのは — hardや — softなんかとは一緒に使えない事。まあ、それこそ一度普通にgit resetしてしまってからgit add -pすれば良いんですけど。その方が安全ですし。

$ git reset -p
diff --git b/test_file a/test_file
index a5e313c..0000000
--- b/test_file
+++ /dev/null
deleted file mode 100644
@@ -1,3 +0,0 @@
-this is a test file.
-after change.
-end of file.
Apply deletion to index [y,n,q,a,d,/,?]?

まるでおんなじですね。

Gitはビクビクしないで大胆にコミットしてこそその真価が発揮できると思います。ローカルリポジトリなら他の誰にも迷惑かけないわけですし。うっかりテンションが上がって2機能くらい作っちゃっても今日からはしっかり個別のコミットにしてpushできますね。良いGit生活を!

参考サイト:

Git-のさまざまなツール-対話的なステージング

--

--