作業ディレクトリ(Working Directory)
作業ディレクトリとは、パソコンで確認できるディレクトリのことです。たとえば、私のlearngit
フォルダが作業ディレクトリです。
リポジトリ(Repository)
作業ディレクトリには.git
という隠しディレクトリがあり、これは作業ディレクトリではなく、Gitのリポジトリです。
Gitのリポジトリには多くのデータが保存されていますが、その中でも最も重要なのはstage
(またはindex
とも呼ばれる)と呼ばれるステージングエリアです。また、Gitは自動的に最初のブランチmaster
と、そのmaster
を指すポインタHEAD
を作成します。
ファイルをGitリポジトリに追加する際には、次の2ステップで実行されます。
-
git add
コマンドを使ってファイルを追加します。実際には、ファイルの変更をステージングエリアに追加するという作業です。 -
git commit
コマンドを使って変更をコミットします。これは、ステージングエリアの全ての内容を現在のブランチにコミットする作業です。
Gitリポジトリを作成した際、Gitは自動的にmaster
という唯一のブランチを作成するため、git commit
コマンドを実行すると、変更はmaster
ブランチにコミットされます。
簡単に言うと、ステージングエリアにはコミットしたいファイルの変更をすべて置いておき、その後、一度にすべての変更をコミットします。
実際にやってみると理解が深まります。まず、readme.txt
を修正し、以下のような行を追加します。
Git is a distributed version control system.
Git is free software distributed under the GPL.
Git has a mutable index called stage.
次に、作業ディレクトリにLICENSE
という新しいテキストファイルを追加します(内容は何でも構いません)。
git status
コマンドで状態を確認します。
$ git status
On branch master
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: readme.txt
Untracked files:
(use "git add <file>..." to include in what will be committed)
LICENSE
no changes added to commit (use "git add" and/or "git commit -a")
Gitは非常に明確に状態を教えてくれます。readme.txt
は変更されており、LICENSE
はまだ追加されていないため、Untracked
の状態です。
ここで、git add
コマンドを2回使用して、readme.txt
とLICENSE
をステージングエリアに追加し、もう一度git status
で状態を確認します。
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
new file: LICENSE
modified: readme.txt
これで、ステージングエリアの状態は次のようになります。
つまり、git add
コマンドは、コミットするすべての変更をステージングエリアに置く作業です。そして、git commit
コマンドを実行すると、ステージングエリアにあるすべての変更を一度にブランチにコミットします。
$ git commit -m "understand how stage works"
[master e43a48b] understand how stage works
2 files changed, 2 insertions(+)
create mode 100644 LICENSE
一度コミットすると、作業ディレクトリに変更がない場合、作業ディレクトリは「クリーン」な状態になります。
$ git status
On branch master
nothing to commit, working tree clean
現在のリポジトリの状態は次のようになり、ステージングエリアには何も残っていません。
長文をお読みいただき、ありがとうございました。
ご質問や異論があれば、コメントをお願いします。
( •̀ ω •́ )y