0
0

Git_作業ディレクトリとステージングエリア

Last updated at Posted at 2024-09-12

作業ディレクトリ(Working Directory)

作業ディレクトリとは、パソコンで確認できるディレクトリのことです。たとえば、私のlearngitフォルダが作業ディレクトリです。

image.png

リポジトリ(Repository)

作業ディレクトリには.gitという隠しディレクトリがあり、これは作業ディレクトリではなく、Gitのリポジトリです。

Gitのリポジトリには多くのデータが保存されていますが、その中でも最も重要なのはstage(またはindexとも呼ばれる)と呼ばれるステージングエリアです。また、Gitは自動的に最初のブランチmasterと、そのmasterを指すポインタHEADを作成します。

image.png

ファイルをGitリポジトリに追加する際には、次の2ステップで実行されます。

  1. git addコマンドを使ってファイルを追加します。実際には、ファイルの変更をステージングエリアに追加するという作業です。
  2. 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.txtLICENSEをステージングエリアに追加し、もう一度git statusで状態を確認します。

$ git status
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

	new file:   LICENSE
	modified:   readme.txt

これで、ステージングエリアの状態は次のようになります。

image.png

つまり、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

現在のリポジトリの状態は次のようになり、ステージングエリアには何も残っていません。

image.png


長文をお読みいただき、ありがとうございました。

ご質問や異論があれば、コメントをお願いします。

( •̀ ω •́ )y

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0