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:
- Salvar temporariamente: Salvar as alterações não enviadas
- Limpar a área de trabalho: Restaurar a área de trabalho para um estado limpo
- Alternar entre ramificações: Você pode alternar livremente entre as ramificações
- Retomar mais tarde: Retome as alterações salvas a qualquer momento
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:
- stash@{0}: O stash mais recente
- stash@{1}: Itens adicionados recentemente ao stash
- stash@{n}: O n+1º stash
2. Operações básicas de armazenamento temporário
(1) Salvar as alterações atuais temporariamente
▶ Exemplo: Preparando as alterações
# 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
# 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
# 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
# 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
# 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
# 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
# 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
# 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
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:
- Aplique apenas uma vez
- Confirme se essa área de preparação não é mais necessária
Quando usar apply:
- Pode ser necessário realizar várias aplicações
- Quer manter a área de preparação como backup
- Aplicar a várias filiais
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”
# 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
# 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
# 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
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
# 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
# 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:
# 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:
# 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
# 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
#!/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 popestash apply?R:
popaplica o commit e exclui o registro do commit, enquantoapplyaplica o commit, mas mantém o registro do commit. Se você precisar aplicar o mesmo commit várias vezes, useapply.
P: O stash salva arquivos não rastreados?
R: Por padrão, não. Use
git stash -uougit stash --include-untrackedpara incluir arquivos não rastreados. Usegit stash -apara 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 listpara visualizar a lista de preparação,git stash showpara visualizar as estatísticas de preparação egit stash show -ppara 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 addpara marcar o conflito como resolvido e, em seguida, usegit stash droppara remover as alterações da área de preparação. Se quiser descartar as alterações, usegit reset --hardegit stash drop.
📖 Resumo
- “Salvar na área de transferência” é um recurso que salva temporariamente as alterações feitas na área de trabalho, permitindo que você alterne entre tarefas.
- Operações básicas:
git stashSalvar na área de transferência,git stash popAplicar e excluir - Com a descrição:
git stash save "description"ougit stash push -m "description" - Incluir arquivos não rastreados:
-uEssa opção inclui arquivos não rastreados - Visualizar Stash:
git stash listLista,git stash showDetalhes - pop x apply: o pop remove o valor temporário, enquanto o apply o preserva
- Preparar o fluxo de trabalho: Preparar o trabalho atual → Mudar de branch → Concluir a tarefa → Desmarcar
📝 Exercícios
-
Exercício básico: Após modificar um arquivo, use
stashpara 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. -
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.
-
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.