Git: A Detailed Explanation of Git Staging and Multitasking
「スタッシング」とは、ワークスペースに加えられた変更を一時的に保存する機能です。緊急のタスクを処理するためにブランチを切り替える必要があり、未完了の作業をコミットしたくない場合、スタッシングが最適な選択肢となります。開発におけるマルチタスクを行う上で、スタッシングの使い方を理解することは極めて重要です。
1. 一時保存の基本概念
(1) 一時保管場所とは何ですか?
ステージングでは、ワークスペースおよびステージング領域に加えられた変更が一時的に保存されます:
- 一時保存:未送信の変更内容を保存する
- ワークスペースのクリーンアップ:ワークスペースをクリーンな状態に戻す
- ブランチの切り替え:ブランチを自由に切り替えることができます
- 後で再開:保存した変更内容をいつでも再開できます
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」とは「スタック」のことです:
- stash@{0}: 最新のスタッシュ
- stash@{1}: スタッシュに最近追加されたアイテム
- stash@{n}: n+1番目のスタッシュ
2. 一時保存の基本操作
(1) 現在の変更内容を一時的に保存する
▶ サンプル:変更内容のステージング
# 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) 説明付きのステージング
▶ サンプル:説明文を追加する
# 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) ステージングには追跡対象外のファイルが含まれています
▶ サンプル:追跡対象外のファイルを含める
# 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) ステージングリストを表示する
▶ サンプル:すべてのステージングエリアを一覧表示する
# 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) ステージングされたコンテンツを表示する
▶ サンプル:ステージングの詳細の表示
# 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) ステージング領域を削除する
▶ サンプル:ステージング領域の削除
# 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) ステージング領域を適用してポップする
▶ サンプル:アプリケーションのステージング
# 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に保存する
# 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
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 の使用例:
- 1回のみご応募ください
- このステージング領域が不要になったことを確認する
apply の使用タイミング:
- 複数回の申請が必要になる場合があります
- ステージング領域をバックアップとして残しておきたい
- 複数の支店に申し込む
5. 一時保存オプションの詳細な説明
(1) 一般的な一時保存の選択肢
| オプション | 説明 | 利用例 |
|---|---|---|
save |
クリップボードに保存(旧構文) | 基本クリップボード |
push |
クリップボードに保存(新しい構文) | おすすめ |
-m |
説明を追加 | 下書きとして保存 |
-u |
追跡対象外のファイルが含まれています | 新規ファイルもステージングする必要があります |
-a |
すべてのファイルを含める | 無視されたファイルを含める |
-k |
ステージング領域を維持 | ワークスペースのみをステージング |
▶ サンプル:「一時保存」オプションの使用
# 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) スタッシュからブランチを作成する
▶ サンプル:ステージング領域からブランチを作成する
# 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) 緊急タスクの切り替え
▶ サンプル:緊急のバグへの対応
# 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) 複数のタスクの並行開発
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
▶ サンプル:タスクの切り替え
# 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) アプリケーションを別のブランチにステージングする
▶ サンプル:ブランチ間の変更のステージング
# 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) 一時保管に関する推奨事項
ベストプラクティス:
# 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
避けるべき慣行:
# 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) ステージングエリアにおける競合の処理
▶ サンプル:ステージング時の競合の解決
# 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) 一時ストレージ管理スクリプト
▶ サンプル:ステージング管理ツール
#!/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
❓ よくある質問
stash popとstash applyの違いは何ですか?pop はコミットを適用してコミットレコードを削除しますが、apply はコミットを適用してもコミットレコードは保持します。同じコミットを複数回適用する必要がある場合は、apply を使用してください。git stash -u または git stash --include-untracked を使用すると、追跡対象外のファイルを含めることができます。git stash -a を使用すると、すべてのファイル(無視されているファイルを含む)を含めることができます。git stash list を使用するとステージングリストを表示でき、git stash show を使用するとステージング統計情報を表示でき、git stash show -p を使用するとステージングリストの完全な差異を表示できます。git add を使用して競合を解決済みとしてマークし、次に git stash drop を使用してステージングから変更を削除します。変更を破棄したい場合は、git reset --hard と git stash drop を使用してください。📖 まとめ
- 「クリップボードに保存」は、ワークスペースに加えられた変更を一時的に保存し、タスクを切り替えられるようにする機能です。
- 基本操作:
git stashクリップボードに保存、git stash pop適用して削除 - 説明付き:
git stash save "description"またはgit stash push -m "description" - 追跡対象外のファイルを含める:
-uこのオプションを指定すると、追跡対象外のファイルも含まれます - スタッシュを表示:
git stash list一覧、git stash show詳細 - pop と apply の違い:pop は一時的な値を削除するのに対し、apply はその値を保持します
- ワークフローのステージング:現在の作業をステージング → ブランチを切り替える → タスクを完了 → ステージングを解除
📝 練習問題
-
基本演習:ファイルを編集した後、
stashを使用して変更内容をスタッシュし、スタッシュリストと詳細を確認してから、スタッシュを適用して、スタッシュの全プロセスを体験してください。 -
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.
-
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.