Git はじめました(ファイルの無視、ステージ前後の差分)

ファイルの無視

例えば、コンパイル後の Python モジュール(拡張子が .pyc のファイル)はリポジトリに追加したくないといった場合、.gitignore が使える。.gitignore をプロジェクトのディレクトリの直下に置き、条件を指定しておくことで、ファイルをステージングするときに Git が自動で無視してくれるようになる。

$ python -m py_compile hello.py
$ ls
README	hello.py  hello.pyc
$ git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#	hello.pyc <-- hello.pyc が追加されている
nothing added to commit but untracked files present (use "git add" to track)
$ vim .gitignore
*.pyc <-- 正規表現等で無視するファイルの条件を指定
$ git status
# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#	.gitignore <-- hello.pyc が無視され、.gitignore だけが認識された
nothing added to commit but untracked files present (use "git add" to track)

ステージ前後の差分

あるファイルを編集したときのレポジトリとの差分は git diff コマンドで確認できたが、ステージ後のファイルとレポジトリとの差分も --staged オプションを使うことで見ることができる。

$ git add hello.py
$ vim hello.py
print 'Hello world!'
print 'This file is staged.'
$ git add hello.py
$ git diff --staged
diff --git a/hello.py b/hello.py
index f7756a3..1cc26ee 100644
--- a/hello.py
+++ b/hello.py
@@ -1 +1,2 @@
 print 'Hello world!'
+print 'This file is staged.'

いったん hello.py をステージした状態でもう一度元のファイルを編集してみる。

$ vim hello.py
print 'Hello world!'
print 'This file is modified but not staged.'
$ git diff
diff --git a/hello.py b/hello.py
index 1cc26ee..3cf3790 100644
--- a/hello.py
+++ b/hello.py
@@ -1,2 +1,2 @@
 print 'Hello world!'
-print 'This file is staged.'
+print 'This file is modified but not staged.'

すると今度は、修正後のファイルとステージされたファイルの差分をみることができる。よって、diff に --staged オプションをつけると、リポジトリのファイルとステージされたファイルの間での差分が表示され、--staged をつけないとステージされたファイルと手元のまだステージされていないファイルの差分をみることができる。