Git: Gitのステージングエリアにファイルを追加するための詳細ガイド
ステージングエリアはGit独自の概念であり、作業ディレクトリとリポジトリの中間に位置し、各コミットの内容を細かく制御することを可能にします。git add コマンドは、変更内容をステージングエリアに追加します。
1. git addの概要
(1) 一時保管場所とは何ですか?
ステージングエリアは、Gitの3ゾーンモデルの重要な構成要素です:
graph TB
subgraph GitThe Three-Zone Model
W[Workspace<br/>Working Directory<br/>Files Actually Edited]
S[Buffer<br/>Staging Area<br/>Changes Ready to Be Submitted]
R[Repository<br/>Repository<br/>All Commit History]
end
W -->|git add| S
S -->|git commit| R
R -->|git checkout| W
style W fill:#fff3cd
style S fill:#d4edda
style R fill:#c3e6cb
(2) なぜバッファが必要なのでしょうか?
ステージング領域では、コミットをきめ細かく制御できます:
| 利点 | 説明 | 例 |
|---|---|---|
| 選択的なコミット | すべての変更をコミットする必要はない | バグを修正したファイルのみをコミットし、実験的なコードはコミットしない |
| 一括で送信 | 異なる変更を個別に送信 | 機能Aと機能Bを個別に送信 |
| 変更の確認 | コミット前のチェック | ステージングされた変更内容が正しいことを確認する |
| 変更を元に戻す | ステージングされた変更を元に戻しても、作業ディレクトリには影響しません | ステージングされたファイルへの変更を元に戻すことができます |
(3) git addの目的
git add コマンドは、作業ディレクトリからの変更をステージング領域にコピーします:
- 新規ファイル:ステージング領域に追加され、コミット準備完了としてマークされた新しいファイル
- ファイルの変更:変更後のバージョンをステージング領域に追加する
- ファイルの削除:ステージング領域に削除操作を追加する
2. プロセスの追加
(1) 基本的な構文
# Add a Single File
git add <File Name>
# Add Multiple Files
git add <Documents1> <Documents2> <Documents3>
# Add all files in the directory
git add <Directory Name>
# Add all files in the current directory
git add .
(2) 追加プロセスの詳細な説明
sequenceDiagram
participant W as Workspace
participant S as Buffer
participant R as Repository
Note over W: Document Status: Modified/Untracked
W->>S: git add <file>
Note over S: Copy the file to the temporary storage area<br/>CalculationSHA-1Hash<br/>Update Index
Note over S: Document Status: Staged
S->>R: git commit
Note over R: Document Status: Committed
(3) 追加後の変更点
ファイルをステージング領域に追加した後:
- ワークスペース:ファイルは変更されず、引き続き編集が可能です
- 一時保存:ファイルが追加された時点のスナップショットを保存します
- ステータスの変更:ファイルのステータスが「未追跡/変更済み」から「ステージング済み」に変更されます
▶ サンプル:単一のファイルを追加する
# Create a New File
echo "# My Project" > README.md
# View Status(Not tracked)
git status
# Untracked files:
# README.md
# Add to Stash
git add README.md
# View Status(Saved)
git status
# Changes to be committed:
# new file: README.md
# View the contents of the staging area
git diff --staged
# diff --git a/README.md b/README.md
# new file mode 100644
# index 0000000..e69de29
# --- /dev/null
# +++ b/README.md
# @@ -0,0 +1 @@
# +# My Project
▶ サンプル:複数のファイルを追加する
# Create Multiple Files
echo "console.log('app');" > app.js
echo "console.log('test');" > test.js
echo "node_modules/" > .gitignore
# Add Multiple Files
git add app.js test.js .gitignore
# View Status
git status -s
# A .gitignore
# A app.js
# A test.js
# Or add them one by one
git add app.js
git add test.js
git add .gitignore
# The results are the same
3. オプションを追加する
(1) 一括追加方法
Git には、ファイルを一括で追加するいくつかの方法があります:
# Add all files in the current directory(Excludes deletions)
git add .
# Add all modifications and deletions to tracked files
git add -u
# Add All Files (Including new files, Edit, Delete)
git add -A
# Or
git add --all
# Interactive Addition(Verify one by one)
git add -p
(2) 選択肢の比較
| コマンド | 新規ファイル | 変更済み | 削除済み | 適用範囲 |
|---|---|---|---|---|
git add <文件> |
✅ | ✅ | ✅ | ファイルを指定 |
git add . |
✅ | ✅ | ❌ | 現在のディレクトリ |
git add -u |
❌ | ✅ | ✅ | リポジトリ全体 |
git add -A |
✅ | ✅ | ✅ | リポジトリ全体 |
(3) 対話型加算
git add -p(パッチモード)では、変更ブロックを1つずつ確認することができます:
git add -p
# Show Modified Blocks,Ask if you want to save a draft
# Stage this hunk [y,n,q,a,d,e,?]?
# y - yes,Temporarily store this block
# n - no,Do not cache
# q - quit,Exit
# a - all,Cache all blocks in this file
# d - discard,Do not cache any blocks from this file
# e - edit,Edit this block manually
# ? - help,Show Help
▶ サンプル:比較条件の一括追加
# Create a Scene
echo "new file" > new.txt # New Document
echo "content" > tracked.txt
git add tracked.txt
git commit -m "Add tracked"
echo "modified" >> tracked.txt # Modified
git rm tracked.txt # Delete(Simulation)
# Usage git add .
git add .
git status -s
# A new.txt
# (Do not process deletion)
# Reset
git reset
# Usage git add -u
git add -u
git status -s
# D tracked.txt
# (Process only modifications and deletions to tracked files)
# Reset
git reset
# Usage git add -A
git add -A
git status -s
# A new.txt
# D tracked.txt
# (Process all)
4. バッファ管理
(1) ステージング領域の内容を表示する
# View Staged Changes
git diff --staged
# Or
git diff --cached
# View the differences between the staging area and the repository
git diff --staged HEAD
# View the list of files in the staging area
git status
(2) バッファの特性
バッファの主な特徴:
graph TB
A[Workspace Files] -->|git add| B[Swap Area Snapshot]
B -->|git commit| C[Repository Commit]
A -->|Continue editing| D[New Version of the Workspace]
D -->|git add| E[Update the temporary storage area]
B -.->|Different Versions| D
style B fill:#d4edda
style D fill:#fff3cd
要点:
- 一時保存領域には、参照ではなく、追加時のスナップショットが保存されます
- 追加した後も編集を続けてください。ワークスペースとステージング領域には異なるバージョンが存在することになります
- ステージング領域を更新するには、
git addを再度実行する必要があります
(3) 一時保存領域の上書き
git add を繰り返すと、クリップボードの内容が上書きされます:
# First time adding
echo "version 1" > file.txt
git add file.txt
# Buffer:version 1
# Edit File
echo "version 2" > file.txt
# Workspace:version 2
# Buffer:version 1(Unchanged)
# Add Again
git add file.txt
# Buffer:version 2(Updated)
▶ サンプル:ステージング領域と作業領域の分離
# Create and Add Files
echo "Line 1" > file.txt
git add file.txt
# View the contents of the staging area
git diff --staged
# +Line 1
# Continue editing the file
echo "Line 2" >> file.txt
# View the differences between the workspace and the staging area
git diff
# +Line 2
# View Status
git status -s
# AM file.txt
# A:The temporary storage area contains data(Line 1)
# M:There are new changes in the workspace(Line 2)
# Update the temporary storage area
git add file.txt
# The staging area currently contains all changes.
git diff --staged
# +Line 1
# +Line 2
5. 加算の取り消し
(1) スタッシュを元に戻す
間違ったファイルをステージングしてしまった場合は、そのステージングを解除できます:
# Undo Staging for a Single File(New Grammar)
git restore --staged <File Name>
# Undo Staging for a Single File(Old Syntax)
git reset HEAD <File Name>
# Uncheck all checkboxes
git restore --staged .
# Or
git reset
(2) 取り消し後の状況
ステージングを解除した後:
- 保留:ファイルが削除されました
- ワークスペース:ファイルは変更されません
- 状態の変化:
- 新規ファイル:「Staged」から「Untracked」に変更されました
- 変更済み:「Staged」から「Modified」に変更しました
(3) 取り消しと破棄
以下の2つの操作を必ず区別してください:
graph TB
A[Saved Files] -->|git restore --staged| B[Undo Temporary Save<br/>Workspace Retained]
A -->|git restore| C[Discard Changes<br/>Revert to the version in the staging area]
B --> D[Status: Untracked/Modified]
C --> E[Status: Staged]
style B fill:#d4edda
style C fill:#f8d7da
▶ サンプル:ステージング操作の取り消し
# Create and Add Files
echo "test content" > test.txt
git add test.txt
git status -s
# A test.txt
# Undo Temporary Save
git restore --staged test.txt
git status -s
# ?? test.txt
# The file has reverted to an untracked state
# Undo for Tracked Files
echo "# Project" > README.md
git add README.md
git commit -m "Add README"
echo "new content" >> README.md
git add README.md
git status -s
# M README.md
# Undo Temporary Save
git restore --staged README.md
git status -s
# M README.md
# The file reverts to its modified state,Changes Retained
▶ サンプル:シーンをインタラクティブに追加する
# Create a file containing multiple changes
cat > app.js << 'EOF'
function oldFunction() {
console.log('old');
}
function newFeature() {
console.log('new feature');
}
function debugCode() {
console.log('debug'); // Temporary Debugging Code
}
EOF
git add app.js
git commit -m "Add app"
# Edit File:Includes feature improvements and debugging code
cat > app.js << 'EOF'
function oldFunction() {
console.log('old');
console.log('improved'); // Feature Improvements
}
function newFeature() {
console.log('new feature');
console.log('enhanced'); // Feature Enhancements
}
function debugCode() {
console.log('debug'); // Temporary Debugging Code
}
EOF
# Use Interactive Add,Improvements to the Temporary Storage Feature
git add -p
# Confirm each modification block one by one
# y - Improvements to the Temporary Storage Feature
# n - Do not cache debug code
# Submit Feature Improvements
git commit -m "Improve features"
# The debugging code is still in the workspace,Not submitted
❓ よくある質問
git add .とgit add -Aの違いは何ですか?git add . は、現在のディレクトリとそのサブディレクトリ内のファイルのみを処理し、他のディレクトリからの削除は対象としません。git add -A は、リポジトリ全体のすべてのファイルを処理し、すべてのディレクトリにおける追加、変更、削除を含みます。リポジトリのルートディレクトリでは、この2つのコマンドの効果は同じですが、サブディレクトリで使用した場合には違いがあります。git add を使用してステージング領域を再度更新するか、ステージング領域の内容をコミットする必要があります。git diff --staged または git diff --cached を使用すると、ステージング領域の変更内容を確認できます。これにより、ステージング領域と前回のコミットとの違いが表示されます。特定のファイルの内容を確認したい場合は、git show :filename を使用して、ステージング領域にあるファイルを表示してください。git add は、すでにステージングされた内容を上書きしますか?git add を再度実行すると、ステージング領域の内容が最新バージョンに更新されます。これはステージング領域を更新する通常の方法であり、問題ではなく機能です。git add -p を入力して対話モードに入ります。Git は変更内容をハンクごとに表示し、「y」でステージング、「n」でスキップ、「e」で手動編集を行うことができます。これにより、どの変更をステージングするかを細かく制御でき、1つのファイル内の異なる変更を個別にコミットすることが可能になります。📖 まとめ
- ステージング領域は、ワークスペースとリポジトリの間のバッファとして機能し、コミットをきめ細かく制御できるようにします
git add <file>指定したファイルを追加します。複数のファイルやディレクトリの追加に対応しています。- ファイルを一括で追加するには、次の3つの方法があります:
.現在のディレクトリ、-u追跡対象のファイル、-Aすべてのファイル - インタラクティブな
git add -p機能を使用すると、変更内容をブロックごとに確認・承認できるため、部分的なコミットが可能になります。 - クリップボードには、アイテムが追加された時点の状態が保存されます。追加後に編集した場合は、再度追加する必要があります。
git restore --stagedを使用すると、ステージング領域が破棄されます。ワークスペース内のファイルは変更されません。- ステージング領域の仕組みを理解することは、Gitのワークフローを習得する上で重要です
📝 練習問題
-
基本演習:Gitリポジトリを作成し、複数のファイルをステージングエリアに追加し、
git diff --stagedを使用してステージングされた内容を表示してから、コミットを行います。各ステップでのステータスの変化を確認してください。 -
応用演習:ファイルを作成し、ステージング領域に追加してから、編集を続けます。作業ディレクトリとステージング領域の違いを確認してください。インタラクティブな追加コマンド
git add -pを使用して、変更の一部のみをステージング領域に追加してみてください。 -
課題:実際のシナリオをシミュレートします。2つのバグを修正し、新機能を追加し、一時的なデバッグコードをいくつか記述したとします。インタラクティブコミットや複数のコミットを活用して、異なる変更を区別し、コミット履歴を明確に保ちましょう。