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.

100%
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:

É por isso que o Git cria ramificações tão rapidamente.

BASH
# View Branch Files
cat .git/refs/heads/main

# Output:
# a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0

(3) Ponteiro HEAD

HEAD é um ponteiro especial que aponta para o ramo atual:

100%
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


2. Visualizar ramificações

(1) Exibir ramificações locais

▶ Exemplo: Listar ramificações

BASH
# 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

BASH
# 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

BASH
# 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

BASH
# 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

100%
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

TEXT 📖 Somente leitura
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

BASH
# 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

100%
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á:

  1. Atualize o HEAD para que aponte para o novo branch
  2. Atualizar a área de preparação para refletir o status do novo branch
  3. 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

BASH
# 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

BASH
# 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

BASH
# 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

BASH
# 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:

100%
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:

(2) Recomendações para a nomenclatura de ramificações

▶ Exemplo: Convenções de nomenclatura de ramificações

BASH
# 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

BASH
# 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 --all para visualizar o gráfico do histórico do ramo ou use git 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 o git 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 checkout oferece funcionalidades mais abrangentes, incluindo alternar entre ramos, restaurar arquivos e criar ramos. Recomendamos usar git switch para alternar entre ramos.

P: Como faço para comparar as diferenças entre as ramificações?

R: Use git diff main feature para comparar as diferenças entre dois ramos e use git diff main...feature para visualizar as alterações no ramo de recurso em relação ao ramo principal.


📖 Resumo


📝 Exercícios

  1. 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 branch e git log --graph para visualizar a estrutura dos branches.

  2. 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 com main e, por fim, faça a fusão de volta para main e exclua o branch de recurso.

  3. Desafio: Implemente a estratégia de ramificação Git Flow em um projeto real, criando ramificações como develop, feature, release e hotfix, e experimente todo o processo de gerenciamento de ramificações.

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%