Git: Gerenciamento de ramificações no Git e desenvolvimento…
Os ramos são um dos recursos mais poderosos do Git. Com os ramos, as equipes podem desenvolver diferentes funcionalidades em paralelo, sem afetar umas às outras, e depois mesclá-las. Criar ramos no Git é extremamente fácil, o que incentiva o uso frequente deles.
1. Conceitos básicos de ramificações
(1) O que é uma filial?
No Git, um branch é um ponteiro móvel que aponta para um commit específico. Cada vez que um commit é feito, o ponteiro do branch atual avança automaticamente para apontar para o novo commit.
graph LR
C1[SubmitC1] --> C2[SubmitC2] --> C3[SubmitC3]
main[mainBranch] --> C3
HEAD[HEAD] --> main
style main fill:#d4edda
style HEAD fill:#fff3cd
(2) A natureza dos ramos
Um branch do Git é, essencialmente, um arquivo que contém 41 bytes:
- Um valor de hash SHA-1 de 40 bytes
- Um caractere de avanço de linha de 1 byte
É por isso que o Git cria ramificações tão rapidamente.
# View Branch Files
cat .git/refs/heads/main
# Output:
# a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0
(3) Ponteiro HEAD
HEAD é um ponteiro especial que aponta para o ramo atual:
graph TB
HEAD[HEAD] --> main[mainBranch]
main --> C3[SubmitC3]
C3 --> C2[SubmitC2]
C2 --> C1[SubmitC1]
style HEAD fill:#f8d7da
style main fill:#d4edda
(4) As vantagens das filiais
- Desenvolvimento paralelo: Várias pessoas trabalhando simultaneamente em diferentes ramos
- Isolamento funcional: O desenvolvimento de novos recursos não afeta o ramo principal
- Experimentação segura: faça seus testes em um branch; se der errado, apague-o
- Controle de versão: Versões diferentes são mantidas em ramificações diferentes
2. Visualizar ramificações
(1) Exibir ramificações locais
▶ Exemplo: Listar ramificações
# View local branches
git branch
# Output:
# * main
# develop
# feature
# * Indicates the current branch
# View Branches and Last Commit
git branch -v
# Output:
# * main a1b2c3d feat: Add a login feature
# develop d4e5f6g Fix: FixBug
# feature h7i8j9k WIP: New Features
# View detailed branch information
git branch -vv
# The output includes information about the upstream branch:
# * main a1b2c3d [origin/main] feat: Add a login feature
(2) Ver todas as ramificações
▶ Exemplo: Visualizando um branch remoto
# View All Branches(Local+Remote)
git branch -a
# Output:
# * main
# develop
# remotes/origin/HEAD -> origin/main
# remotes/origin/main
# remotes/origin/develop
# remotes/origin/feature
# View only remote branches
git branch -r
# Output:
# origin/HEAD -> origin/main
# origin/main
# origin/develop
# origin/feature
(3) Visualizar relações entre ramificações
▶ Exemplo: Representação gráfica de ramificações
# View the branch history graph
git log --oneline --graph --all
# Output:
# * a1b2c3d (HEAD -> main) feat: Add Login
# | * d4e5f6g (feature) WIP: New Features
# |/
# * h7i8j9k Initial commit
# View the commits included in a branch
git log --oneline --graph --decorate --all
# View Branch Fork Points
git merge-base main feature
3. Criar um branch
(1) Criar um novo branch
▶ Exemplo: Como criar um branch
# Create a Branch(Based on the current commit)
git branch feature
# Create a branch and specify its starting point
git branch feature a1b2c3d
# Create a branch based on a specific tag
git branch v1.1-branch v1.0.0
# Create a branch and switch to it immediately
git checkout -b feature
# New Grammar(Recommendations)
git switch -c feature
# Created from a remote branch
git checkout -b feature origin/feature
# Or
git switch -c feature origin/feature
(2) Fluxo de trabalho para a criação de um branch
graph TB
A[mainBranch] --> B[git branch feature]
B --> C[New Branchfeature]
C --> D[feature: Go to Development]
D --> E[Submit Changes]
E --> F[Merge back intomain]
style A fill:#d4edda
style C fill:#fff3cd
style F fill:#c3e6cb
(3) Convenções de nomenclatura de ramificações
▶ Exemplo: Convenções padrão de nomenclatura de ramificações
Feature Branch:feature/user-auth
feature/shopping-cart
feature/payment-integration
Fix Branch:fix/login-error
fix/memory-leak
Thermal Repair Branch:hotfix/critical-security-issue
hotfix/payment-failure
Release Branch:release/v1.0.0
release/v2.1.0
Development Branch:develop
Main Branch: main (or master)
4. Mudar de filial
(1) Comandos para alternar entre ramificações
▶ Exemplo: Alternando entre ramos
# Traditional Commands
git checkout feature
# New Command(Recommendations)
git switch feature
# Switch to the previous branch
git switch -
# Switch tomainBranch
git switch main
# Create and Switch
git switch -c new-feature
# Output:
# Switched to branch 'new-feature'
(2) Como funciona a troca de ramificação
graph TB
A[Before switching branches] --> B[UpdateHEADPointer]
B --> C[Update the temporary storage area]
C --> D[Update Workspace]
D --> E[Switching complete]
style A fill:#fff3cd
style E fill:#d4edda
Ao mudar de branch, o Git irá:
- Atualize o HEAD para que aponte para o novo branch
- Atualizar a área de preparação para refletir o status do novo branch
- Atualize os arquivos na área de trabalho com o conteúdo do novo branch
(3) Como lidar com alterações não salvas
▶ Exemplo: Processamento de alterações antes de mudar de ramificação
# View Current Status
git status
# Method1:Submit Changes
git add .
git commit -m "WIP: Save as Draft"
git switch feature
# Method2:Save Changes Temporarily(stash)
git stash
git switch feature
# After completing other tasks
git switch main
git stash pop
# Method3:Cancel Edits
git restore .
git switch feature
# Method4:Carry, Modify, Toggle(If there is no conflict)
git switch feature
# If the changes do not conflict with the new branch,Changes will be saved
5. Exclusão de um branch
(1) Excluir ramos mesclados
▶ Exemplo: Excluindo um branch com segurança
# Delete Merged Branches
git branch -d feature
# Output:
# Deleted branch feature (was a1b2c3d).
# Delete Multiple Branches
git branch -d feature1 feature2
# Delete a merged remote branch
git push origin --delete feature
# Or
git push origin :feature
(2) Exclusão forçada de um ramo
▶ Exemplo: Exclusão forçada de ramos não mesclados
# Try deleting the unmerged branch
git branch -d feature
# Output Error:
# error: The branch 'feature' is not fully merged.
# If you are sure you want to delete it, run 'git branch -D feature'.
# Forced Deletion
git branch -D feature
# Output:
# Deleted branch feature (was a1b2c3d).
(3) Limpar ramos remotos
▶ Exemplo: Limpeza de branches remotos excluídos
# View remote branch references
git branch -r
# Delete a local reference to a remote branch(Remotely Deleted)
git fetch -p
# Or
git remote prune origin
# View which remote branch references need to be cleaned up
git remote prune origin --dry-run
6. Melhores práticas para a gestão de filiais
(1) Estratégia de filiais
Estratégias comuns de ramificação:
Git Flow:
graph TB
main[main Production] --> release[release Published]
release --> develop[develop Development]
develop --> feature[feature Features]
main --> hotfix[hotfix Thermal Repair]
style main fill:#d4edda
style develop fill:#fff3cd
style feature fill:#e1f5ff
style hotfix fill:#f8d7da
Fluxo do GitHub:
- O branch principal está sempre pronto para implantação
- Criar um branch de funcionalidade a partir de
main - Crie uma solicitação de pull assim que o desenvolvimento estiver concluído
- Incorporar ao branch principal após revisão
(2) Recomendações para a nomenclatura de ramificações
▶ Exemplo: Convenções de nomenclatura de ramificações
# Feature Branch
feature/user-authentication
feature/shopping-cart
feature/payment-integration
# BugFix
fix/login-validation-error
fix/memory-leak-issue
# Thermal Repair
hotfix/security-vulnerability
hotfix/critical-bug
# Published
release/v1.0.0
release/v2.1.0
# Experiment
experiment/new-architecture
spike/performance-optimization
(3) Fluxo de trabalho da filial
▶ Exemplo: Fluxo de trabalho completo de ramificação
# 1. Create a feature branch from main
git checkout main
git pull origin main
git checkout -b feature/user-auth
# 2. Developing on a feature branch
echo "auth code" > auth.js
git add auth.js
git commit -m "feat: Add User Authentication"
# 3. Stay in touch withmainSynchronize
git fetch origin
git merge origin/main
# or userebase
git rebase origin/main
# 4. Push Feature Branch
git push -u origin feature/user-auth
# 5. Create Pull Request (on GitHub)
# 6. Delete feature branches after merging
git checkout main
git pull origin main
git branch -d feature/user-auth
git push origin --delete feature/user-auth
❓ Perguntas Frequentes
P: O branch original será afetado após a criação de um novo branch?
R: Não. Criar um branch simplesmente gera um novo ponteiro que aponta para o commit atual; o branch original permanece totalmente inalterado. Os dois branches podem evoluir de forma independente.
P: Como posso saber a partir de qual branch um branch foi criado?
R: Use
git log --oneline --graph --allpara visualizar o gráfico do histórico do ramo ou usegit merge-base <branch1> <branch2>para visualizar o ponto de bifurcação entre os dois ramos.
P: Os commits serão perdidos após a exclusão de um branch?
R: Se um commit tiver sido referenciado por outro branch (por exemplo, se tiver sido mesclado no
main), a exclusão do branch não resultará na perda desse commit. Se um commit existir apenas no branch que está sendo excluído, ele será perdido com a exclusão, mas poderá ser recuperado usando ogit reflog.
P: Qual é a diferença entre “checkout” e “switch”?
R:
git switché um novo comando introduzido no Git 2.23, projetado especificamente para alternar entre ramos e que oferece uma semântica mais clara.git checkoutoferece funcionalidades mais abrangentes, incluindo alternar entre ramos, restaurar arquivos e criar ramos. Recomendamos usargit switchpara alternar entre ramos.
P: Como faço para comparar as diferenças entre as ramificações?
R: Use
git diff main featurepara comparar as diferenças entre dois ramos e usegit diff main...featurepara visualizar as alterações no ramo de recurso em relação ao ramo principal.
📖 Resumo
- Um branch é um ponteiro móvel para um commit, e o custo de criá-lo é extremamente baixo.
- Visualizar ramificação:
git branchpara listar as ramificações locais,-apara exibir todas as ramificações - Crie um branch:
git branch <name>ougit switch -c <name>; em seguida, crie-o e mude para ele - Mudar de branch:
git switch <name>Atualizar o HEAD e o diretório de trabalho - Excluir ramificação:
git branch -dExcluir uma ramificação mesclada;-DExclusão forçada - Estratégias de ramificação: Git Flow, GitHub Flow, etc. Escolha a estratégia que melhor se adapta à sua equipe.
📝 Exercícios
-
Exercício básico: Crie um repositório Git e crie vários branches (main, develop, feature). Faça commits de alterações diferentes em cada branch e use
git branchegit log --graphpara visualizar a estrutura dos branches. -
Exercício avançado: Simule um fluxo de trabalho completo com ramificações: crie um branch de recurso a partir de
main, desenvolva o recurso, mantenha-o sincronizado commaine, por fim, faça a fusão de volta paramaine exclua o branch de recurso. -
Desafio: Implemente a estratégia de ramificação Git Flow em um projeto real, criando ramificações como
develop,feature,releaseehotfix, e experimente todo o processo de gerenciamento de ramificações.