Git: Gitのステージングエリアにファイルを追加するための詳細ガイド

ステージングエリアはGit独自の概念であり、作業ディレクトリとリポジトリの中間に位置し、各コミットの内容を細かく制御することを可能にします。git add コマンドは、変更内容をステージングエリアに追加します。

1. git addの概要

(1) 一時保管場所とは何ですか?

ステージングエリアは、Gitの3ゾーンモデルの重要な構成要素です:

100%
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) 基本的な構文

BASH
# 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) 追加プロセスの詳細な説明

100%
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) 追加後の変更点

ファイルをステージング領域に追加した後:

▶ サンプル:単一のファイルを追加する

BASH
# 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

▶ サンプル:複数のファイルを追加する

BASH
# 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 には、ファイルを一括で追加するいくつかの方法があります:

BASH
# 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つずつ確認することができます:

BASH
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

▶ サンプル:比較条件の一括追加

BASH
# 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) ステージング領域の内容を表示する

BASH
# 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) バッファの特性

バッファの主な特徴:

100%
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

要点

(3) 一時保存領域の上書き

git add を繰り返すと、クリップボードの内容が上書きされます:

BASH
# 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)

▶ サンプル:ステージング領域と作業領域の分離

BASH
# 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) スタッシュを元に戻す

間違ったファイルをステージングしてしまった場合は、そのステージングを解除できます:

BASH
# 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) 取り消し後の状況

ステージングを解除した後:

(3) 取り消しと破棄

以下の2つの操作を必ず区別してください:

100%
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

▶ サンプル:ステージング操作の取り消し

BASH
# 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

▶ サンプル:シーンをインタラクティブに追加する

BASH
# 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

❓ よくある質問

Q git add .git add -Aの違いは何ですか?
A git add . は、現在のディレクトリとそのサブディレクトリ内のファイルのみを処理し、他のディレクトリからの削除は対象としません。git add -A は、リポジトリ全体のすべてのファイルを処理し、すべてのディレクトリにおける追加、変更、削除を含みます。リポジトリのルートディレクトリでは、この2つのコマンドの効果は同じですが、サブディレクトリで使用した場合には違いがあります。
Q ファイルをステージングした後に編集を続けた場合、どうなりますか?
A ファイルはステージング領域と作業ディレクトリの両方に表示されますが、その内容は異なります。ステージング領域には追加時のバージョンが、作業ディレクトリには編集後の新しいバージョンが含まれます。ステータスは「AM」または「MM」と表示されます。新しい変更を追加する前に、git add を使用してステージング領域を再度更新するか、ステージング領域の内容をコミットする必要があります。
Q クリップボードの内容を確認するにはどうすればよいですか?
A git diff --staged または git diff --cached を使用すると、ステージング領域の変更内容を確認できます。これにより、ステージング領域と前回のコミットとの違いが表示されます。特定のファイルの内容を確認したい場合は、git show :filename を使用して、ステージング領域にあるファイルを表示してください。
Q git add は、すでにステージングされた内容を上書きしますか?
A はい。同じファイルに対して git add を再度実行すると、ステージング領域の内容が最新バージョンに更新されます。これはステージング領域を更新する通常の方法であり、問題ではなく機能です。
Q ファイルに対して、変更の一部のみを適用するにはどうすればよいですか?
A git add -p を入力して対話モードに入ります。Git は変更内容をハンクごとに表示し、「y」でステージング、「n」でスキップ、「e」で手動編集を行うことができます。これにより、どの変更をステージングするかを細かく制御でき、1つのファイル内の異なる変更を個別にコミットすることが可能になります。

📖 まとめ


📝 練習問題

  1. 基本演習:Gitリポジトリを作成し、複数のファイルをステージングエリアに追加し、git diff --staged を使用してステージングされた内容を表示してから、コミットを行います。各ステップでのステータスの変化を確認してください。

  2. 応用演習:ファイルを作成し、ステージング領域に追加してから、編集を続けます。作業ディレクトリとステージング領域の違いを確認してください。インタラクティブな追加コマンド git add -p を使用して、変更の一部のみをステージング領域に追加してみてください。

  3. 課題:実際のシナリオをシミュレートします。2つのバグを修正し、新機能を追加し、一時的なデバッグコードをいくつか記述したとします。インタラクティブコミットや複数のコミットを活用して、異なる変更を区別し、コミット履歴を明確に保ちましょう。

Web-Tutorial.com

Web-Tutorial 技術チーム

複数の開発者によって共同維持されているプログラミングチュートリアルプラットフォーム。各チュートリアルは専門分野の開発者が執筆・レビューしています。正確で信頼性の高いコンテンツを目指しています — 問題を見つけた場合はお知らせください。

100%