Git: A Detailed Explanation of Git Staging and Multitasking

「スタッシング」とは、ワークスペースに加えられた変更を一時的に保存する機能です。緊急のタスクを処理するためにブランチを切り替える必要があり、未完了の作業をコミットしたくない場合、スタッシングが最適な選択肢となります。開発におけるマルチタスクを行う上で、スタッシングの使い方を理解することは極めて重要です。

1. 一時保存の基本概念

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

ステージングでは、ワークスペースおよびステージング領域に加えられた変更が一時的に保存されます:

100%
graph TB
    A[Changes have been made to the workspace] --> B[git stash]
    B --> C[Edit and save tostash]
    C --> D[The workspace is now clean]
    D --> E[Switch Branches]
    E --> F[git stash pop]
    F --> G[Restore Changes]
    
    style B fill:#fff3cd
    style D fill:#d4edda
    style G fill:#c3e6cb

(2) 「stash」と「commit」の違い

機能 スタッシュ コミット
目的 一時保管 永久保存
履歴 コミット履歴にない コミット履歴にある
ブランチ どのブランチにもない 現在のブランチ上
プッシュ通知 プッシュ通知なし プッシュ通知あり
ユースケース 一時的なタスクの切り替え 機能開発の完了

(3) stashの保存構造

「stash」とは「スタック」のことです:



2. 一時保存の基本操作

(1) 現在の変更内容を一時的に保存する

▶ サンプル:変更内容のステージング

BASH
# View Current Changes
git status

# Output:
# Changes not staged for commit:
#   modified:   src/auth.js
#   modified:   src/user.js

# Save current changes temporarily
git stash

# Output:
# Saved working directory and index state WIP on main: a1b2c3d feat: Add Feature

# View Status(The workspace is clean)
git status

# Output:
# On branch main
# nothing to commit, working tree clean

(2) 説明付きのステージング

▶ サンプル:説明文を追加する

BASH
# Save for now and add a description
git stash save "WIP: User Login Feature"

# Or usepush(New Grammar)
git stash push -m "WIP: User Login Feature"

# Output:
# Saved working directory and index state On main: WIP: User Login Feature

# View the staging list
git stash list

# Output:
# stash@{0}: On main: WIP: User Login Feature

(3) ステージングには追跡対象外のファイルが含まれています

▶ サンプル:追跡対象外のファイルを含める

BASH
# Create a New File(Not tracked)
touch new-file.js

# DefaultstashUntracked files will not be saved
git stash

# Output:
# Saved working directory and index state WIP on main: a1b2c3d
# new-file.js still untracked

# Usage-uThe selection includes untracked files
git stash -u

# Or
git stash --include-untracked

# Usage-aThe option includes all files(Include ignored files)
git stash -a


3. ステージングの表示と管理

(1) ステージングリストを表示する

▶ サンプル:すべてのステージングエリアを一覧表示する

BASH
# View the staging list
git stash list

# Output:
# stash@{0}: On main: WIP: User Login Feature
# stash@{1}: On feature: WIP: Shopping Cart Feature
# stash@{2}: On develop: FixBug

# Limit the number of items displayed
git stash list -3

# View Staging Details
git stash show

# Output:
#  src/auth.js | 10 ++++++++++
#  src/user.js |  5 ++---
#  2 files changed, 12 insertions(+), 3 deletions(-)

# View Detailed Differences
git stash show -p

# View a Specific Cache
git stash show stash@{1}

(2) ステージングされたコンテンツを表示する

▶ サンプル:ステージングの詳細の表示

BASH
# View the latest full diff from the staging area
git stash show -p stash@{0}

# Output:
# diff --git a/src/auth.js b/src/auth.js
# index abc1234..def5678 100644
# --- a/src/auth.js
# +++ b/src/auth.js
# @@ -10,6 +10,16 @@ function validate() {
# +  // Added validation logic
# +  if (!token) {
# +    return false;
# +  }
#    return true;
#  }

# View Cached Statistics
git stash show --stat

# Output:
#  src/auth.js | 10 ++++++++++
#  src/user.js |  5 ++---
#  2 files changed, 12 insertions(+), 3 deletions(-)

(3) ステージング領域を削除する

▶ サンプル:ステージング領域の削除

BASH
# Delete the latest staging
git stash drop

# Delete Specified Stash
git stash drop stash@{2}

# Clear All Cache
git stash clear

# Confirm Deletion
git stash list


4. アプリケーションのステージング

(1) ステージング領域を適用してポップする

▶ サンプル:アプリケーションのステージング

BASH
# Apply, Save, and Delete
git stash pop

# Output:
# On branch main
# Changes not staged for commit:
#   modified:   src/auth.js
#   modified:   src/user.js

# Use Specified Stash
git stash pop stash@{1}

# If there is a conflict
# CONFLICT (content): Merge conflict in src/auth.js
# The stash entry is kept in case you need it again.

# After Resolving the Conflict,Manually Delete the Stash
git stash drop

(2) 適用するが、ステージング環境に留める(適用)

▶ サンプル:Stashに保存する

BASH
# App is cached but not deleted
git stash apply

# Use Specified Stash
git stash apply stash@{1}

# View the staging list(The temporary file is still there)
git stash list

# Output:
# stash@{0}: On main: WIP: User Login Feature
# stash@{1}: On feature: WIP: Shopping Cart Feature

# applySuitable for multiple uses of the same temporary storage

(3) pop 対 apply

100%
graph TB
    A[App Stash] --> B{Method}
    B -->|pop| C[Apply and Clear the Clipboard]
    B -->|apply| D[Apply but keep in the staging area]
    C --> E[Single-use]
    D --> F[Reusable]
    
    style C fill:#d4edda
    style D fill:#fff3cd

pop の使用例:

apply の使用タイミング:



5. 一時保存オプションの詳細な説明

(1) 一般的な一時保存の選択肢

オプション 説明 利用例
save クリップボードに保存(旧構文) 基本クリップボード
push クリップボードに保存(新しい構文) おすすめ
-m 説明を追加 下書きとして保存
-u 追跡対象外のファイルが含まれています 新規ファイルもステージングする必要があります
-a すべてのファイルを含める 無視されたファイルを含める
-k ステージング領域を維持 ワークスペースのみをステージング

▶ サンプル:「一時保存」オプションの使用

BASH
# Only cache changes to tracked files
git stash

# Check-in includes untracked files
git stash -u

# Check out includes ignored files
git stash -a

# Temporary Workspace Only,Reserve a buffer
git stash -k

# Cache only specific files
git stash push src/auth.js

# Cache only files that match the pattern
git stash push '*.js'

# Preserve the temporary storage index
git stash --index

(2) スタッシュからブランチを作成する

▶ サンプル:ステージング領域からブランチを作成する

BASH
# Create a New Branch from a Stash
git stash branch feature-from-stash

# Output:
# Switched to a new branch 'feature-from-stash'
# On branch feature-from-stash
# Changes not staged for commit:
#   modified:   src/auth.js

# This will create a new branch and apply the staged changes.
# Ideal for transferring staged changes to a new branch for development


6. ワークフローを保存する

(1) 緊急タスクの切り替え

▶ サンプル:緊急のバグへの対応

BASH
# Features currently under developmentA
echo "feature A code" > feature-a.js
git status

# Output:
# Untracked files:
#   feature-a.js

# Sudden need for urgent repairsBug
# Save the current work
git stash save "WIP: FeaturesAUnder development"

# Switch tohotfixBranch
git checkout -b hotfix-urgent-bug

# FixBug
echo "fix" > fix.js
git add fix.js
git commit -m "fix: Urgent FixBug"

# Push Fix
git push origin hotfix-urgent-bug

# Switch back to the original branch and resume work
git checkout main
git stash pop

# Continue Developing FeaturesA

(2) 複数のタスクの並行開発

100%
sequenceDiagram
    participant Developer
    participant mainBranch
    participant featureBranch
    participant Stash
    
    Developer->>mainBranch: Development FeaturesA
    Developer->>Stash: git stash Save A
    Developer->>featureBranch: Switch to Branch DevelopmentB
    Developer->>Stash: git stash Save B
    Developer->>mainBranch: Cut back tomain
    Developer->>Stash: git stash pop Restore A

▶ サンプル:タスクの切り替え

BASH
# Development FeaturesA
echo "feature A" > feature-a.js
git stash push -m "FeaturesA"

# Toggle Development FeaturesB
git checkout -b feature-b
echo "feature B" > feature-b.js
git stash push -m "FeaturesB"

# View the staging list
git stash list

# Output:
# stash@{0}: On feature-b: FeaturesB
# stash@{1}: On main: FeaturesA

# Back tomainContinue DevelopmentA
git checkout main
git stash pop stash@{1}

# Completed FeaturesA
git add feature-a.js
git commit -m "feat: FeaturesADone"

# Cut tofeature-bContinue DevelopmentB
git checkout feature-b
git stash pop

(3) アプリケーションを別のブランチにステージングする

▶ サンプル:ブランチ間の変更のステージング

BASH
# Staging Changes on feature Branch
git checkout feature
echo "some changes" > file.js
git stash save "Share Edits"

# Switch tomainBranch Application Staging
git checkout main
git stash apply

# NowmainThese changes are also present in the branch.
# The temporary file is still there,Can be applied to other branches

# Switch todevelopBranch Applications
git checkout develop
git stash apply

# Delete Stash
git stash drop


7. 一時保存に関するベストプラクティス

(1) 一時保管に関する推奨事項

ベストプラクティス:

BASH
# Add a clear description
git stash save "WIP: User Authentication Feature,Complete the login logic"

# Clear the cache list periodically
git stash list
git stash drop stash@{5}  # Delete the old staging area

# Usageapplyrather thanpop,If you're not sure whether you still need it
git stash apply

# Check the status before saving temporarily
git status
git diff

避けるべき慣行:

BASH
# No description,Difficult to identify
git stash

# Retaining large amounts of temporary data over the long term
git stash list  # Dozens of temporary files

# Forgot to restore the staging area
git stash
# ... A few days later, I forgot what I had saved.

(2) ステージングエリアにおける競合の処理

▶ サンプル:ステージング時の競合の解決

BASH
# Conflicts caused by app cache
git stash pop

# Output:
# CONFLICT (content): Merge conflict in src/auth.js
# The stash entry is kept in case you need it again.

# View Conflicting Files
git status

# Resolving Conflicts
# Editing Files with Conflicts,Keep the necessary content

# Mark the conflict as resolved
git add src/auth.js

# Delete Stash
git stash drop

# Or discard the temporary file
git reset --hard
git stash drop

(3) 一時ストレージ管理スクリプト

▶ サンプル:ステージング管理ツール

BASH
#!/bin/bash
# stash-manager.sh - Cache Management Tool

case "$1" in
    list)
        echo "=== Stash List ==="
        git stash list
        ;;
    show)
        if [ -z "$2" ]; then
            git stash show -p
        else
            git stash show -p "stash@{$2}"
        fi
        ;;
    apply)
        if [ -z "$2" ]; then
            git stash apply
        else
            git stash apply "stash@{$2}"
        fi
        ;;
    drop)
        if [ -z "$2" ]; then
            git stash drop
        else
            git stash drop "stash@{$2}"
        fi
        ;;
    clear)
        read -p "Clear all stashes? (y/n) " -n 1 -r
        echo
        if [[ $REPLY =~ ^[Yy]$ ]]; then
            git stash clear
            echo "All stashes cleared"
        fi
        ;;
    *)
        echo "Usage: $0 {list|show [n]|apply [n]|drop [n]|clear}"
        ;;
esac

❓ よくある質問

Q 「stash」と「commit」の違いは何ですか?
A スタッシュは一時的な保存であり、コミット履歴には表示されず、プッシュされず、どのブランチにも属しません。コミットは永続的な記録であり、コミット履歴に表示され、プッシュされ、現在のブランチに属します。
Q stash popstash applyの違いは何ですか?
A pop はコミットを適用してコミットレコードを削除しますが、apply はコミットを適用してもコミットレコードは保持します。同じコミットを複数回適用する必要がある場合は、apply を使用してください。
Q stash は追跡対象外のファイルも保存しますか?
A デフォルトでは、含まれません。git stash -u または git stash --include-untracked を使用すると、追跡対象外のファイルを含めることができます。git stash -a を使用すると、すべてのファイル(無視されているファイルを含む)を含めることができます。
Q ステージングエリアの内容を確認するにはどうすればよいですか?
A git stash list を使用するとステージングリストを表示でき、git stash show を使用するとステージング統計情報を表示でき、git stash show -p を使用するとステージングリストの完全な差異を表示できます。
Q アプリのステージング中に競合が発生した場合はどうすればよいですか?
A ファイル内の競合を解決するには、git add を使用して競合を解決済みとしてマークし、次に git stash drop を使用してステージングから変更を削除します。変更を破棄したい場合は、git reset --hardgit stash drop を使用してください。

📖 まとめ


📝 練習問題

  1. 基本演習:ファイルを編集した後、stash を使用して変更内容をスタッシュし、スタッシュリストと詳細を確認してから、スタッシュを適用して、スタッシュの全プロセスを体験してください。

  2. Advanced Exercise: Simulate a scenario where you need to switch tasks urgently: While developing a feature, stash your current work, switch branches to fix a bug, then restore the stash and continue development to experience the practical application of stashing.

  3. Challenge: Experience parallel development of multiple tasks: Create multiple staging areas, switch between different branches to apply different staging areas, and understand how the staging stack works.

Web-Tutorial.com

Web-Tutorial 技術チーム

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

100%