Git: Uma explicação detalhada sobre o staging no Git e a…

O stashing é um recurso que salva temporariamente as alterações feitas no seu espaço de trabalho. Quando você precisa mudar de branch para lidar com uma tarefa urgente, mas não quer fazer o commit de um trabalho inacabado, o stashing é a melhor opção. Entender como usar o stashing é fundamental para realizar várias tarefas simultaneamente no desenvolvimento.

1. Conceitos básicos de armazenamento temporário

(1) O que é uma área de armazenamento temporário?

A área de preparação salva temporariamente as alterações feitas no espaço de trabalho e na área de preparação:

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) A diferença entre “stash” e “commit”

Recurso stash commit
Finalidade Armazenamento temporário Registro permanente
Histórico Não consta no histórico de commits Consta no histórico de commits
Ramo Não está em nenhum ramo Está no ramo atual
Notificações push Sem notificações push Notificações push
Casos de uso Alternância temporária entre tarefas Conclusão do desenvolvimento de funcionalidades

(3) A estrutura de armazenamento do stash

Um stash é uma pilha:


2. Operações básicas de armazenamento temporário

(1) Salvar as alterações atuais temporariamente

▶ Exemplo: Preparando as alterações

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) Organização com uma descrição

▶ Exemplo: Adicionar uma descrição

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) A preparação inclui arquivos não rastreados

▶ Exemplo: Inclui arquivos não rastreados

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. Visualização e gerenciamento do ambiente de teste

(1) Visualizar a lista de preparação

▶ Exemplo: Listar todas as áreas de preparação

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) Visualizar conteúdo preparado

▶ Exemplo: Visualização dos detalhes da área de preparação

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

▶ Exemplo: Exclusão de uma área de preparação

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. Preparação da aplicação

(1) Aplicar e liberar a área de preparação

▶ Exemplo: Preparação de aplicativos

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) Aplicar, mas manter no ambiente de teste (aplicar)

▶ Exemplo: Guardar na lista de favoritos

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

Cenários de uso do pop:

Quando usar apply:


5. Explicação detalhada das opções de armazenamento temporário

(1) Opções comuns de armazenamento temporário

Opção Descrição Caso de uso
save Salvar na área de transferência (sintaxe antiga) Área de transferência básica
push Salvar na área de transferência (nova sintaxe) Recomendado
-m Adicionar descrição Marcar como rascunho
-u Inclui arquivos não rastreados Os novos arquivos também devem ser adicionados à área de preparação
-a Incluir todos os arquivos Incluir arquivos ignorados
-k Manter a área de preparação Preparar apenas a área de trabalho

▶ Exemplo: Como usar a opção “Armazenamento temporário”

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) Criando um branch a partir de um stash

▶ Exemplo: Criando um branch a partir de uma área de preparação

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. Salvar o fluxo de trabalho

(1) Troca de tarefas em situações de emergência

▶ Exemplo: Como lidar com um bug urgente

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) Desenvolvimento paralelo de várias tarefas

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

▶ Exemplo: Alternando entre tarefas

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) Transferir o aplicativo para um branch diferente

▶ Exemplo: Preparando alterações em diferentes ramificações

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. Melhores práticas para armazenamento temporário

(1) Recomendações para armazenamento temporário

Melhores práticas:

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

Práticas inadequadas:

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) Como lidar com conflitos na área de preparação

▶ Exemplo: Resolução de conflitos de staging

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) Script de gerenciamento de armazenamento temporário

▶ Exemplo: Ferramenta de gerenciamento de ambientes de teste

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

❓ Perguntas Frequentes

P: Qual é a diferença entre stash e commit?

R: Um stash é um salvamento temporário; ele não aparece no histórico de commits, não é enviado e não pertence a nenhum branch. Um commit é um registro permanente; ele aparece no histórico de commits, é enviado e pertence ao branch atual.

P: Qual é a diferença entre stash pop e stash apply?

R: pop aplica o commit e exclui o registro do commit, enquanto apply aplica o commit, mas mantém o registro do commit. Se você precisar aplicar o mesmo commit várias vezes, use apply.

P: O stash salva arquivos não rastreados?

R: Por padrão, não. Use git stash -u ou git stash --include-untracked para incluir arquivos não rastreados. Use git stash -a para incluir todos os arquivos (incluindo os arquivos ignorados).

P: Como faço para visualizar o conteúdo da área de preparação?

R: Use git stash list para visualizar a lista de preparação, git stash show para visualizar as estatísticas de preparação e git stash show -p para visualizar todas as diferenças na lista de preparação.

P: O que devo fazer se ocorrer um conflito ao preparar um aplicativo?

R: Para resolver conflitos em um arquivo, use git add para marcar o conflito como resolvido e, em seguida, use git stash drop para remover as alterações da área de preparação. Se quiser descartar as alterações, use git reset --hard e git stash drop.


📖 Resumo


📝 Exercícios

  1. Exercício básico: Após modificar um arquivo, use stash para armazenar as alterações no stash, visualize a lista e os detalhes do stash e, em seguida, aplique o stash para conhecer todo o processo de armazenamento no stash.

  2. Exercício avançado: Simule uma situação em que você precise alternar entre tarefas com urgência: enquanto estiver desenvolvendo um recurso, salve seu trabalho atual no stash, mude de branch para corrigir um bug e, em seguida, restaure o stash e continue o desenvolvimento para experimentar a aplicação prática do stash.

  3. Desafio: Experimente o desenvolvimento paralelo de várias tarefas: crie várias áreas de teste, alterne entre diferentes branches para aplicar as diferentes áreas de teste e entenda como funciona a pilha de áreas de teste.

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%