Git: Um guia detalhado sobre como fazer check-out e…

Checkout é um comando versátil e importante do Git que permite alternar entre branches, restaurar arquivos e fazer o checkout de commits específicos. O Git 2.23 introduziu os comandos git switch e git restore, mais claros, para dividir as funções do checkout.

1. Visão geral do comando checkout

(1) As múltiplas funções do “checkout”

git checkout é um comando multifuncional:

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) Introdução de novos comandos

Como havia muitas funções de checkout, o Git 2.23 introduziu dois novos comandos:

(3) Comparação de comandos

Operação checkout switch/restore
Mudar de ramificação git checkout <branch> git switch <branch>
Criar e alternar git checkout -b <branch> git switch -c <branch>
Restaurar arquivo git checkout -- <file> git restore <file>
Restaurar Stash git checkout HEAD -- <file> git restore --staged <file>

2. Mudar de ramificação

(1) Comutação básica

▶ Exemplo: Mudança para um branch existente

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) Explicação detalhada do processo de comutação

Ao alternar entre branches, o Git realiza as seguintes ações:

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) Opções do interruptor

▶ Exemplo: Como usar a opção de alternância

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. Criação e alternância entre ramificações

(1) Criar um novo branch

▶ Exemplo: Criar e alternar imediatamente

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) Opções para criar um branch

▶ Exemplo: Opções para criar um ramo

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. Arquivos detectados

(1) Recuperação de arquivos do repositório

▶ Exemplo: Restaurando arquivos da área de trabalho

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) Restauração a partir da área de preparação

▶ Exemplo: Cancelar a preparação

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) Recuperar arquivos excluídos

▶ Exemplo: Recuperação de arquivos excluídos acidentalmente

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. Checkout e Commit (Ponteiro de cabeça separado)

(1) O que é um ponteiro de desacoplamento?

Quando um commit — em vez de um branch — é selecionado, o HEAD aponta diretamente para esse commit, em vez de para um ponteiro de branch. Esse estado é chamado de “HEAD desanexado”.

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) Entrar no estado do ponteiro do cabeçote de separação

▶ Exemplo: Fazendo o check-out de um commit específico

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) Operação no estado do ponteiro do cabeçote do separador

▶ Exemplo: Operações com o ponteiro separador

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) Salve as alterações no ponteiro de divisão de cabeçalho

▶ Exemplo: Salvar as alterações em um novo branch

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. Resolução de conflitos ao alternar entre ramificações

(1) Como lidar com alterações não salvas

Ao alternar entre ramificações, se houver alterações não confirmadas no diretório de trabalho, pode ocorrer o seguinte:

▶ Exemplo: Como lidar com alterações não salvas

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) Métodos para resolver conflitos de comutação

▶ Exemplo: Resolução de conflitos de comutação

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 x switch x restore

(1) Resumo das comparações entre comandos

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) Uso recomendado

▶ Exemplo: Como usar comandos modernos do 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

❓ Perguntas Frequentes

P: Qual devo usar: checkout, switch ou restore?

R: Recomendamos usar os novos comandos: git switch para alternar entre ramificações e git restore para restaurar arquivos. O comando git checkout é muito complexo e pode causar confusão. No entanto, o comando checkout ainda é útil em certos cenários avançados.

P: O que é um ponteiro de cabeça dividida? Quais são os riscos?

R: Uma “cabeça isolada” refere-se a uma situação em que HEAD aponta diretamente para um commit, em vez de para um branch. O risco é que os commits nesse estado não pertençam a nenhum branch e possam ser perdidos ao alternar entre branches. Recomenda-se criar um novo branch para salvar seu trabalho.

P: O que devo fazer se receber uma mensagem sobre alterações não salvas ao mudar de branch?

R: Existem três opções: 1) Confirmar as alterações antes de mudar; 2) Usar git stash para preparar as alterações; 3) Usar git restore . para descartar as alterações. Escolha o método adequado com base na importância das alterações.

P: Como faço para restaurar um arquivo de uma versão anterior?

R: Use git restore --source=<commit> <file> ou git checkout <commit> -- <file> para restaurar arquivos a partir de um commit específico. Por exemplo: git restore --source=HEAD~5 README.md.

P: Como faço para salvar meu trabalho enquanto o cursor está no modo dividido?

R: Use git switch -c <new-branch> para criar um novo branch e salvar seu trabalho atual. Se você já tiver mudado de branch, pode usar git reflog para recuperar o commit e, em seguida, usar git branch <name> <commit> para criar o branch.


📖 Resumo


📝 Exercícios

  1. Exercício básico: Crie vários branches, use git switch para alternar entre eles, observe como o espaço de trabalho muda ao alternar entre os branches e compreenda a função do ponteiro HEAD.

  2. Exercício avançado: Simule um cenário de “head-pointing”: verifique um commit histórico específico, crie um commit nesse estado e, em seguida, use git switch -c para criar um novo branch e salvar seu trabalho.

  3. Desafio: Simule um cenário real de desenvolvimento: enquanto desenvolve um recurso em um branch de recurso, você precisa, de repente, mudar para o branch principal para corrigir um bug urgente. Use stash para salvar seu trabalho atual e, após corrigir o bug, restaure seu trabalho e continue o desenvolvimento.

Web-Tutorial.com

Equipe Técnica Web-Tutorial

Uma plataforma de tutoriais mantida por diversos desenvolvedores. Cada tutorial é escrito e revisado por profissionais da área correspondente. Trabalhamos para manter nosso conteúdo preciso e confiável — se encontrar algum problema, avise-nos.

100%