Git はじめました(ファイルの変更、追加、コミット)
変更内容のリポジトリへの記録
前回すでに add や commit やの例を書いてますが、リポジトリを作成した後のファイル変更→変更内容のスナップショットをリポジトリにコミットする方法を書いていく。
まず前提として、リポジトリのコピーの各ファイルには「tracked」と「untracked」の二通りの状態がある。tracked とは直近のスナップショットにファイルが存在している状態で、これらのファイルにはさらに「unmodified」「modified」「staged」の 3 つの状態がある。untracked とは、これらのどれにも当てはまらないファイルの状態(リポジトリ内のスナップショットとは無関係の状態)をいう。
最初にプロジェクトをクローンした時点では、すべてのファイルは tracked かつ unmodified の状態となっている。ファイルを変更すると Git はそれを modified とみなし、そのファイルを staged にして commit するというのが大まかな流れとなる。これについてはちょっと説明を書くのが大変なので、本家のサイトを参照してほしい。
source : http://git-scm.com/book/en/Git-Basics-Recording-Changes-to-the-Repository
ファイルの状態の確認
ファイルの状態の確認は git status コマンドを使う。クローン直後の場合、以下のような結果になる。
$ cd ~/workspace/src/sampleproject $ git status # On branch master nothing to commit (working directory clean)
ファイルの追加
ためしに前回作ったディレクトリに README というファイルを追加してみる。その後 git status を実行すると、Untracked files: というところの下に、新しく作った README が追加されるのがわかる。
$ vim README
This is a sample project.
$ git status # On branch master # Untracked files: # (use "git add <file>..." to include in what will be committed) # # README nothing added to commit but untracked files present (use "git add" to track)
README をステージングする(staged の状態にする)には git add コマンドを使う。
$ git add README $ git status # On branch master # Changes to be committed: # (use "git reset HEAD <file>..." to unstage) # # new file: README #
すると Changes to be committed: の下に README が移動しており、このファイルがリポジトリにコミットできる状態となっていることがわかる。
README をコミットする。
$ git commit -m 'second commit' [master d409479] second commit 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 README
git commit を実行すると、リポジトリに変更が反映される。-m オプションでコミット時のコメントを追加することができ、省略した場合は標準のエディタ(事前に vim を設定した)が立ち上がり、コメントを入力することができる。
なお、-a オプションをつけると git add のステップを飛ばしてコミットできる。
$ git commit -a -m 'skip add process'
既存ファイルの修正
既存のファイルを修正してみる。
$ vim hello.py
print 'Hello world!'
リポジトリに反映されている内容との差分は git diff コマンドで確認できる。
$ git diff diff --git a/hello.py b/hello.py index 61d2637..f7756a3 100644 --- a/hello.py +++ b/hello.py @@ -1 +1 @@ -print 'Hello' +print 'Hello world!'
git status を見てみると、内容が変更されている。
$ git status # On branch master # Changed but not updated: # (use "git add <file>..." to update what will be committed) # (use "git checkout -- <file>..." to discard changes in working directory) # # modified: hello.py # no changes added to commit (use "git add" and/or "git commit -a")
変更したファイルも git add してコミットすればリポジトリに反映される。
$ git add hello.py $ git commit -m 'third commit' [master 1deaf4c] third commit 1 files changed, 1 insertions(+), 1 deletions(-)