0%
Tutorial 8 de 10
80% concluído

Workflows Git avançados

Explore fluxos de trabalho populares como Git Flow, GitHub Flow e Trunk-Based Development.

Workflows Git avançados

Os workflows Git definem como as equipes organizam seu desenvolvimento com Git. Este tutorial explora as metodologias mais populares e ajuda você a escolher a que melhor se adapta à sua equipe e ao seu projeto.

Introdução aos workflows

Um workflow Git é um conjunto de regras e convenções que definem:

  • Como criar e nomear as branches
  • Quando e como fazer o merge
  • Quem pode fazer o quê
  • Como gerenciar as releases
Produit complexeWeb app agileDéploiement continuÉquipe mixteChoix du WorkflowType de projetGit FlowGitHub FlowTrunk-BasedGitLab Flow

Git Flow

Princípio

Git Flow é um workflow estruturado com branches especializadas para diferentes tipos de desenvolvimento.

Estrutura das branches

maindevelopfeature/loginrelease/1.0InitialDev 1Login 1Login 2Dev 2RC 1v1.0

Branches principais

main (ou master)

  • Código de produção
  • Sempre estável
  • Cada commit = nova versão

develop

  • Branch de integração
  • Últimas funcionalidades desenvolvidas
  • Base para as novas features

Branches de suporte

feature/

# Criar uma feature branch
git checkout develop
git checkout -b feature/user-authentication

# Desenvolver a funcionalidade
# ... commits ...

# Fazer o merge na develop
git checkout develop
git merge --no-ff feature/user-authentication
git branch -d feature/user-authentication

release/

# Criar uma release branch
git checkout develop
git checkout -b release/1.2.0

# Finalizar a release (bug fixes, version bump)
echo "1.2.0" > VERSION
git commit -am "Bump version to 1.2.0"

# Fazer o merge na main e na develop
git checkout main
git merge --no-ff release/1.2.0
git tag -a v1.2.0 -m "Release version 1.2.0"

git checkout develop
git merge --no-ff release/1.2.0
git branch -d release/1.2.0

hotfix/

# Criar um hotfix a partir da main
git checkout main
git checkout -b hotfix/critical-security-fix

# Corrigir o bug
# ... commits ...

# Fazer o merge na main e na develop
git checkout main
git merge --no-ff hotfix/critical-security-fix
git tag -a v1.2.1 -m "Hotfix version 1.2.1"

git checkout develop
git merge --no-ff hotfix/critical-security-fix
git branch -d hotfix/critical-security-fix

Ferramentas do Git Flow

# Instalação do git-flow
# macOS
brew install git-flow

# Ubuntu
sudo apt-get install git-flow

# Inicialização
git flow init

# Comandos git-flow
git flow feature start user-auth
git flow feature finish user-auth

git flow release start 1.2.0
git flow release finish 1.2.0

git flow hotfix start critical-fix
git flow hotfix finish critical-fix

Vantagens e desvantagens

✅ Vantagens:

  • Estrutura clara e previsível
  • Separação nítida dos ambientes
  • Gerenciamento robusto das releases
  • Ideal para produtos com ciclos de release

❌ Desvantagens:

  • Alta complexidade
  • Overhead para equipes pequenas
  • Não adequado para deploy contínuo
  • Branches de longa duração

GitHub Flow

Princípio

Workflow simplificado centrado na branch main, com feature branches de curta duração.

mainfeature/new-uifeature/api-updateInitialFeature AUI 1UI 2API 1Deploy

Workflow passo a passo

# 1. Criar uma branch a partir da main
git checkout main
git pull origin main
git checkout -b feature/improve-performance

# 2. Desenvolver e fazer commits
# ... desenvolvimento ...
git add .
git commit -m "feat: optimize database queries"

# 3. Fazer push regularmente
git push origin feature/improve-performance

# 4. Abrir uma Pull Request
gh pr create --title "Improve database performance" \
             --body "Optimizes queries to reduce load time by 50%"

# 5. Review e discussão
# ... code review ...

# 6. Fazer o merge na main
gh pr merge --squash

# 7. Fazer o deploy
# Deploy automático a partir da main

Regras do GitHub Flow

  1. A main está sempre pronta para deploy
  2. Branches descritivas a partir da main
  3. Push frequente para o origin
  4. Pull Request para qualquer modificação
  5. Review obrigatória antes do merge
  6. Merge e deploy imediatos

Configuração do GitHub

# .github/branch-protection.yml
protection_rules:
  main:
    required_status_checks:
      strict: true
      contexts:
        - continuous-integration
        - security-scan
    enforce_admins: true
    required_pull_request_reviews:
      required_approving_review_count: 2
      dismiss_stale_reviews: true
    restrictions:
      users: []
      teams: ["core-team"]

Vantagens e desvantagens

✅ Vantagens:

  • Simplicidade máxima
  • Deploy contínuo facilitado
  • Feedback rápido
  • Ideal para web apps

❌ Desvantagens:

  • Sem staging explícito
  • Difícil para releases planejadas
  • Exige uma CI/CD robusta
  • Pode ser caótico sem disciplina

Trunk-Based Development

Princípio

Desenvolvimento diretamente na branch principal, com branches de duração muito curta (< 1 dia).

mainshort-featuretiny-changeInitialFeature AQuick fixFeature BFeature CTypo fixFeature D

Práticas-chave

Commits frequentes

# Vários commits por dia na main
git add .
git commit -m "feat: add user validation (partial)"
git push origin main

# Algumas horas depois
git add .
git commit -m "feat: complete user validation"
git push origin main

Feature Flags

// Usar feature flags para código não finalizado
function processPayment(amount) {
    if (featureFlags.newPaymentSystem) {
        return newPaymentProcessor(amount);
    }
    return legacyPaymentProcessor(amount);
}

Branches muito curtas

# Branch de no máximo 1-2 dias
git checkout -b quick-fix/typo-correction
# ... correção rápida ...
git push origin quick-fix/typo-correction
# ... PR e merge imediato ...

Release a partir do trunk

# Release branches a partir da main
git checkout main
git checkout -b release/2024.03.15
git tag v2024.03.15
git push origin release/2024.03.15
git push origin v2024.03.15

# Hotfixes diretamente na main
git checkout main
# ... fix ...
git commit -m "hotfix: critical security patch"
git tag v2024.03.15.1
git push origin main
git push origin v2024.03.15.1

Vantagens e desvantagens

✅ Vantagens:

  • Integração contínua máxima
  • Sem merge hell
  • Feedback imediato
  • Simplicidade extrema

❌ Desvantagens:

  • Exige disciplina rigorosa
  • Testes automatizados obrigatórios
  • Feature flags complexas
  • Não serve para todos os tipos de projeto

GitLab Flow

Princípio

Combinação do GitHub Flow com branches de ambiente.

mainfeature/authstagingproductionInitialAuth 1Auth 2Déploiement stagingDéploiement prodv1.0

Estrutura com ambientes

# Branches de ambiente
main          # Desenvolvimento
staging       # Testes de integração
production    # Produção

# Workflow
git checkout main
git checkout -b feature/new-api

# Desenvolvimento
git push origin feature/new-api
# ... Pull Request para a main ...

# Deploy em staging
git checkout staging
git merge main
git push origin staging

# Testes em staging
# ... validação ...

# Deploy em produção
git checkout production
git merge staging
git push origin production

Release branches

# Para as releases planejadas
git checkout main
git checkout -b release/2.1.0

# Cherry-pick das features
git cherry-pick feature-commit-1
git cherry-pick feature-commit-2

# Deploy da release
git checkout production
git merge release/2.1.0
git tag v2.1.0

Forking Workflow

Princípio

Cada desenvolvedor tem seu próprio fork do repositório principal.

Dépôt PrincipalFork Développeur 1Fork Développeur 2Clone Local 1Clone Local 2Pull Request 1Pull Request 2

Workflow completo

# 1. Fork do repositório principal (via GitHub)

# 2. Clone do seu fork
git clone https://github.com/VOUS/projet.git
cd projet

# 3. Adicionar o upstream
git remote add upstream https://github.com/ORIGINAL/projet.git

# 4. Criar uma branch de feature
git checkout -b feature/awesome-feature

# 5. Desenvolver
# ... commits ...

# 6. Sincronizar com o upstream
git fetch upstream
git rebase upstream/main

# 7. Fazer push para o seu fork
git push origin feature/awesome-feature

# 8. Criar uma Pull Request para o upstream

Manutenção do fork

# Sincronização regular
git fetch upstream
git checkout main
git merge upstream/main
git push origin main

# Limpeza das branches
git branch -d feature/completed-feature
git push origin --delete feature/completed-feature

Escolher o workflow certo

Critérios de decisão

1-3 devs4-10 devs10+ devsWeb appProduitMicroservicesChoisir un WorkflowTaille équipeGitHub FlowType projetGit Flow ou ForkingGitHub FlowGit FlowTrunk-Based

Tabela comparativa

WorkflowComplexidadeEquipeDeployReleases
GitHub FlowBaixaPequena-MédiaContínuoFrequentes
Git FlowAltaMédia-GrandePlanejadoPlanejadas
Trunk-BasedBaixaQualquerContínuoContínuas
GitLab FlowMédiaMédiaMistoFlexíveis
ForkingMédiaOpen SourceVariávelVariáveis

Implementação de um workflow

GitHub Flow - Configuração

# .github/workflows/ci.yml
name: CI/CD
on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Run tests
        run: npm test
      
  deploy:
    needs: test
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    steps:
      - name: Deploy to production
        run: ./deploy.sh

Git Flow - Scripts

#!/bin/bash
# scripts/git-flow-feature.sh

FEATURE_NAME=$1

if [ -z "$FEATURE_NAME" ]; then
    echo "Usage: $0 <feature-name>"
    exit 1
fi

# Criar a feature branch
git checkout develop
git pull origin develop
git checkout -b "feature/$FEATURE_NAME"

echo "Feature branch feature/$FEATURE_NAME created"
echo "When done, run: git-flow-feature-finish.sh $FEATURE_NAME"

Trunk-Based - Hooks

#!/bin/bash
# .git/hooks/pre-push

# Verificar se os testes passam antes do push
npm test
if [ $? -ne 0 ]; then
    echo "Tests failed. Push aborted."
    exit 1
fi

# Verificar se o código está formatado
npm run lint
if [ $? -ne 0 ]; then
    echo "Linting failed. Push aborted."
    exit 1
fi

Exercícios práticos

Exercício 1: Simular o GitHub Flow

# 1. Criar um repositório de teste
mkdir github-flow-demo
cd github-flow-demo
git init
echo "# GitHub Flow Demo" > README.md
git add README.md
git commit -m "Initial commit"

# 2. Simular o desenvolvimento de uma feature
git checkout -b feature/add-calculator
echo "function add(a, b) { return a + b; }" > calculator.js
git add calculator.js
git commit -m "feat: add calculator function"

# 3. Simular uma Pull Request (merge)
git checkout main
git merge --no-ff feature/add-calculator
git branch -d feature/add-calculator

# 4. Repetir com outras features
git checkout -b feature/add-tests
echo "// Tests for calculator" > calculator.test.js
git add calculator.test.js
git commit -m "test: add calculator tests"

git checkout main
git merge --no-ff feature/add-tests
git branch -d feature/add-tests

Exercício 2: Experimentar o Git Flow

# 1. Inicializar o Git Flow
git flow init

# 2. Criar uma feature
git flow feature start user-authentication
echo "function login() { /* auth logic */ }" > auth.js
git add auth.js
git commit -m "feat: add login function"
git flow feature finish user-authentication

# 3. Criar uma release
git flow release start 1.0.0
echo "1.0.0" > VERSION
git add VERSION
git commit -m "bump: version to 1.0.0"
git flow release finish 1.0.0

# 4. Simular um hotfix
git flow hotfix start critical-fix
echo "// Fixed critical bug" >> auth.js
git add auth.js
git commit -m "fix: resolve critical authentication bug"
git flow hotfix finish critical-fix

Boas práticas transversais

Mensagens de commit

# Convenção Conventional Commits
feat: add new user authentication system
fix: resolve login timeout issue
docs: update API documentation
style: format code according to style guide
refactor: restructure user service
test: add unit tests for payment module
chore: update dependencies

Proteção das branches

# Via GitHub CLI
gh api repos/:owner/:repo/branches/main/protection \
  --method PUT \
  --field required_status_checks='{"strict":true,"contexts":["ci"]}' \
  --field enforce_admins=true \
  --field required_pull_request_reviews='{"required_approving_review_count":2}'

Automatização

# .github/workflows/workflow-enforcement.yml
name: Workflow Enforcement
on:
  pull_request:
    branches: [main]

jobs:
  check-branch-name:
    runs-on: ubuntu-latest
    steps:
      - name: Check branch name
        run: |
          if [[ ! "${{ github.head_ref }}" =~ ^(feature|fix|hotfix)/.+ ]]; then
            echo "Branch name must start with feature/, fix/, or hotfix/"
            exit 1
          fi

Recursos adicionais

Ferramentas de workflow

  • Git Flow AVH: Extensão aprimorada do Git Flow
  • GitHub CLI: Automação dos workflows do GitHub
  • GitKraken Glo: Gerenciamento de projetos integrado
  • Sourcetree: Interface gráfica com suporte a workflows

Documentação

Conclusão

A escolha do workflow Git depende de muitos fatores: tamanho da equipe, tipo de projeto, frequência de deploy e cultura da empresa. O importante é escolher um workflow adequado ao seu contexto e segui-lo de forma consistente.

No próximo tutorial, vamos explorar os submódulos e as subárvores do Git para gerenciar projetos complexos com dependências externas.


Tempo de leitura estimado: 35 minutos
Nível: Avançado
Etapa anterior: Resolução de conflitos
Próxima etapa: Git submódulos e subárvores