Git: Gitでのチェックアウトとブランチ切り替えに関する詳細ガイド

Checkout は、Git における汎用性が高く重要なコマンドであり、ブランチの切り替え、ファイルの復元、特定のコミットのチェックアウトを行うことができます。Git 2.23 では、checkout の機能を分割するため、より分かりやすい git switch および git restore コマンドが導入されました。

1. checkout コマンドの概要

(1) 「checkout」のさまざまな機能

git checkout は多機能コマンドです:

100%
graph TB
    A[git checkout] --> B[Switch Branches]
    A --> C[Create a Branch]
    A --> D[Restore Files]
    A --> E[Checkout and Submit]
    
    style A fill:#fff3cd
    style B fill:#d4edda
    style C fill:#c3e6cb
    style D fill:#cce5ff
    style E fill:#f8d7da

(2) 新しいコマンドの導入

チェックアウト関数が多すぎたため、Git 2.23 では 2 つの新しいコマンドが導入されました:

(3) コマンドの比較

操作 チェックアウト 切り替え/復元
支店を切り替える git checkout <branch> git switch <branch>
作成・切り替え git checkout -b <branch> git switch -c <branch>
ファイルを復元 git checkout -- <file> git restore <file>
スタッシュを復元 git checkout HEAD -- <file> git restore --staged <file>


2. ブランチを切り替える

(1) 基本的なスイッチング

▶ サンプル:既存のブランチへの切り替え

BASH
# Traditional Method
git checkout feature

# A New Approach(Recommendations)
git switch feature

# Output:
# Switched to branch 'feature'

# Switch tomainBranch
git switch main

# Output:
# Switched to branch 'main'
# Your branch is up to date with 'origin/main'.

(2) スイッチングプロセスの詳細な説明

ブランチを切り替える際、Git は以下の処理を行います:

100%
sequenceDiagram
    participant User
    participant Git
    participant HEAD
    participant Workspace
    
    User->>Git: git switch feature
    Git->>Git: Check unsaved changes
    Git->>HEAD: UpdateHEADPointer
    HEAD->>Git: OrientationfeatureBranch
    Git->>Workspace: Update File
    Workspace->>User: Switchover complete

(3) スイッチのオプション

▶ サンプル:トグルオプションの使用

BASH
# Switch to the previous branch
git switch -

# Output:
# Switched to branch 'main'

# Switch Branches and Create a Branch(If it does not exist)
git switch -c new-feature

# Force Switch(Discard Local Changes)
git switch -f feature

# Switch workspaces without changing them(Update OnlyHEAD)
git switch --detach feature


3. ブランチの作成と切り替え

(1) 新しいブランチを作成する

▶ サンプル:作成してすぐに切り替える

BASH
# Traditional Method
git checkout -b feature

# A New Approach(Recommendations)
git switch -c feature

# Output:
# Switched to a new branch 'feature'

# Created based on a specific commit
git switch -c feature a1b2c3d

# Created from a remote branch
git switch -c feature origin/feature

# Output:
# Branch 'feature' set up to track remote branch 'feature' from 'origin'.
# Switched to a new branch 'feature'

(2) ブランチを作成する方法

▶ サンプル:ブランチを作成する方法

BASH
# Create a branch but do not switch to it
git branch feature

# Create and Switch,Set Up an Upstream Branch
git switch -c feature --track origin/feature

# Create a branch based on a specific tag
git switch -c v1.1-branch v1.0.0

# Create from a commit on another branch
git switch -c feature main~5


4. 検出されたファイル

(1) リポジトリからのファイルの復元

▶ サンプル:ワークスペースファイルの復元

BASH
# Traditional Method
git checkout -- README.md

# A New Approach(Recommendations)
git restore README.md

# Restore from a Specific Commit
git restore --source=a1b2c3d README.md

# Restore from HEAD (Latest Commit)
git restore --source=HEAD README.md

# Restore Multiple Files
git restore file1.js file2.js

# Restore the entire directory
git restore src/

(2) ステージング領域からの復元

▶ サンプル:ステージングの解除

BASH
# Traditional Method
git reset HEAD README.md

# A New Approach(Recommendations)
git restore --staged README.md

# Cancel the temporary save and restore the workspace at the same time
git restore --staged --worktree README.md

# Or
git checkout HEAD -- README.md

(3) 削除されたファイルの復元

▶ サンプル:誤って削除してしまったファイルの復元

BASH
# Accidentally Deleted Files
rm important-file.js

# Restore from the repository
git restore important-file.js

# Or
git checkout HEAD -- important-file.js

# View Deleted Files
git status

# Output:
# deleted:    important-file.js

# Recover All Deleted Files
git restore .


5. チェックアウトとコミット(ヘッドポインタの分離)

(1) デカップリングポインタとは何ですか?

ブランチではなくコミットをチェックアウトした場合、HEAD はブランチポインタではなく、そのコミットを直接指します。この状態は「Detached HEAD」と呼ばれます。

100%
graph TB
    subgraph Normal State
        HEAD1[HEAD] --> main1[main]
        main1 --> C1[SubmitC3]
    end
    
    subgraph Separator Arrow
        HEAD2[HEAD] --> C2[Submita1b2c3d]
        main2[main] --> C2
    end
    
    style HEAD1 fill:#d4edda
    style HEAD2 fill:#f8d7da

(2) 分離ヘッドのポインタの状態を入力する

▶ サンプル:特定のコミットをチェックアウトする

BASH
# Detect Specific Commits
git checkout a1b2c3d

# Output:
# Note: switching to 'a1b2c3d'.
# 
# You are in 'detached HEAD' state. You can look around, make experimental
# changes and commit them, and you can discard any commits you make in this
# state without impacting any branches by switching back to a branch.
#
# HEAD is now at a1b2c3d feat: Add a login feature

# Detection Label
git checkout v1.0.0

# Detect Remote Branches
git checkout origin/feature

(3) セパレータ・ヘッド・ポインタ状態での動作

▶ サンプル:セパレータポインタを用いた演算

BASH
# Currently in the "separate head" pointer state
git status

# Output:
# HEAD detached at a1b2c3d
# nothing to commit, working tree clean

# You can view the code
git log --oneline

# You can edit the file
echo "test" > test.js

# Can be submitted
git add test.js
git commit -m "test commit"

# Output:
# [detached HEAD d4e5f6g] test commit
#  1 file changed, 1 insertion(+)
#  create mode 100644 test.js

# ⚠️ Note:This commit is not on any branch.!

(4) 分割ヘッドポインタの変更内容を保存する

▶ サンプル:変更内容を新しいブランチに保存する

BASH
# A commit was created while the pointer was in the split head state.

# Method1:Create a new branch and save
git switch -c new-branch

# Output:
# Switched to a new branch 'new-branch'

# Method2:Merge into the existing branch
git branch temp-branch
git switch main
git merge temp-branch
git branch -d temp-branch

# If you switch branches without saving
git switch main

# You can do this byreflogRetrieve
git reflog
# d4e5f6g HEAD@{0}: checkout: moving from a1b2c3d to main
# a1b2c3d HEAD@{1}: commit: test commit

# Create a branch pointing to that commit
git branch saved-work d4e5f6g


6. ブランチを切り替える際の競合の解決

(1) 保存されていない変更の処理

ブランチを切り替える際、作業ディレクトリにコミットされていない変更がある場合、次のような現象が発生することがあります:

▶ サンプル:保存されていない変更の処理

BASH
# View Current Status
git status

# Output:
# Changes not staged for commit:
#   modified:   README.md

# Situation1:Modifications do not conflict with the new branch
git switch feature
# Switch Successful,The change has been saved

# Situation2:Conflicts Between Changes and a New Branch
git switch feature
# Output Error:
# error: Your local changes to the following files would be overwritten by checkout:
#   README.md
# Please commit your changes or stash them before you switch branches.

(2) スイッチング競合を解決する方法

▶ サンプル:スイッチングの競合の解決

BASH
# Methods1:Submit Changes
git add .
git commit -m "WIP: Save as Draft"
git switch feature

# Methods2:Save Changes Temporarily(stash)
git stash
git switch feature
# After completing other tasks
git switch main
git stash pop

# Methods3:Cancel Edits
git restore .
git switch feature

# Methods4:Force Switch(Discard Changes)
git switch -f feature

# Methods5:Carry, Modify, Toggle(If possible)
git switch -m feature
# GitI'll try to merge the changes.


7. checkout と switch と restore の違い

(1) コマンド比較の概要

100%
graph TB
    A[GitCommand Selection] --> B{Operation Type}
    B -->|Switch Branches| C[git switch]
    B -->|Restore Files| D[git restore]
    B -->|Complex Operations| E[git checkout]
    
    style C fill:#d4edda
    style D fill:#c3e6cb
    style E fill:#fff3cd

(2) 推奨される使用方法

▶ サンプル:最新のGitコマンドの使用

BASH
# Switch Branches - Usageswitch
git switch feature
git switch -c new-feature

# Restore Files - Usagerestore
git restore README.md
git restore --staged README.md

# Detect Specific Commits - Usageswitch --detach
git switch --detach a1b2c3d

# checkoutReserved for special cases
git checkout HEAD~5 -- file.js  # Restore a Specific File from a Previous Version

❓ よくある質問

Q checkoutswitchrestoreのどれを使えばいいですか?
A ブランチを切り替えるには git switch、ファイルを復元するには git restore という新しいコマンドの使用をお勧めします。git checkout は複雑すぎて、混乱を招く恐れがあります。ただし、checkout は特定の上級者向けのシナリオでは依然として有用です。
Q スプリットヘッドポインタとは何ですか?どのようなリスクがありますか?
A 「デタッチドヘッド」とは、HEADがブランチではなくコミットを直接指している状態を指します。この状態のコミットはどのブランチにも属していないため、ブランチを切り替える際に失われるリスクがあります。作業内容を保存するために、新しいブランチを作成することをお勧めします。
Q ブランチを切り替える際に「未保存の変更があります」というメッセージが表示された場合はどうすればよいですか?
A 3つの選択肢があります。1) 切り替え前に変更をコミットする、2) git stash を使用して変更をステージングする、3) git restore . を使用して変更を破棄する。変更の重要度に応じて、適切な方法を選択してください。
Q 以前のバージョンのファイルを復元するにはどうすればよいですか?
A 指定したコミットからファイルを復元するには、git restore --source=<commit> <file> または git checkout <commit> -- <file> を使用します。例:git restore --source=HEAD~5 README.md
Q カーソルが分割モードにある状態で、作業内容を保存するにはどうすればよいですか?
A git switch -c <new-branch> を使用して新しいブランチを作成し、現在の作業内容を保存してください。すでにブランチを切り替えている場合は、git reflog を使用してコミットを取得し、その後 git branch <name> <commit> を使用してブランチを作成してください。

📖 まとめ


📝 練習問題

  1. 基本演習:複数のブランチを作成し、git switch を使用してそれらを切り替え、ブランチを切り替えた際にワークスペースがどのように変化するかを観察し、HEAD ポインタの役割を理解する。

  2. 応用演習:「ヘッドポインティング」のシナリオをシミュレートします。特定の過去のコミットを確認し、その状態でのコミットを作成した後、git switch -c を使用して新しいブランチを作成し、作業内容を保存してください。

  3. 課題:実際の開発シナリオをシミュレートします。機能ブランチで機能の開発を行っている最中に、緊急のバグを修正するために突然メインブランチに切り替える必要が生じました。stash を使用して現在の作業内容を保存し、バグの修正後に作業内容を復元して開発を続行してください。

Web-Tutorial.com

Web-Tutorial 技術チーム

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

100%