Workflows Git avanzados
Explora flujos de trabajo populares como Git Flow, GitHub Flow y Trunk-Based Development.
Workflows Git avanzados
Los workflows de Git definen cómo organizan los equipos su desarrollo con Git. Este tutorial explora las metodologías más populares y te ayuda a elegir la que mejor se adapte a tu equipo y a tu proyecto.
Introducción a los workflows
Un workflow de Git es un conjunto de reglas y convenciones que definen:
- Cómo crear y nombrar las ramas
- Cuándo y cómo fusionar
- Quién puede hacer qué
- Cómo gestionar las releases
Git Flow
Principio
Git Flow es un workflow estructurado con ramas especializadas para distintos tipos de desarrollo.
Estructura de las ramas
Ramas principales
main (o master)
- Código de producción
- Siempre estable
- Cada commit = nueva versión
develop
- Rama de integración
- Últimas funcionalidades desarrolladas
- Base para las nuevas features
Ramas de apoyo
feature/
# Crear una feature branch
git checkout develop
git checkout -b feature/user-authentication
# Desarrollar la funcionalidad
# ... commits ...
# Fusionar en develop
git checkout develop
git merge --no-ff feature/user-authentication
git branch -d feature/user-authentication
release/
# Crear una release branch
git checkout develop
git checkout -b release/1.2.0
# Finalizar la release (bug fixes, version bump)
echo "1.2.0" > VERSION
git commit -am "Bump version to 1.2.0"
# Fusionar en main y 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/
# Crear un hotfix desde main
git checkout main
git checkout -b hotfix/critical-security-fix
# Corregir el bug
# ... commits ...
# Fusionar en main y 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
Herramientas de Git Flow
# Instalación de git-flow
# macOS
brew install git-flow
# Ubuntu
sudo apt-get install git-flow
# Inicialización
git flow init
# Comandos de 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
Ventajas e inconvenientes
✅ Ventajas:
- Estructura clara y predecible
- Separación nítida de los entornos
- Gestión robusta de las releases
- Ideal para productos con ciclos de release
❌ Inconvenientes:
- Complejidad elevada
- Overhead para los equipos pequeños
- No es adecuado para el despliegue continuo
- Ramas de larga duración
GitHub Flow
Principio
Workflow simplificado centrado en la rama main con feature branches de corta duración.
Workflow paso a paso
# 1. Crear una rama desde main
git checkout main
git pull origin main
git checkout -b feature/improve-performance
# 2. Desarrollar y hacer commit
# ... desarrollo ...
git add .
git commit -m "feat: optimize database queries"
# 3. Hacer push con regularidad
git push origin feature/improve-performance
# 4. Abrir una Pull Request
gh pr create --title "Improve database performance" \
--body "Optimizes queries to reduce load time by 50%"
# 5. Review y discusión
# ... code review ...
# 6. Fusionar en main
gh pr merge --squash
# 7. Desplegar
# Despliegue automático desde main
Reglas de GitHub Flow
- main siempre es desplegable
- Ramas descriptivas desde main
- Push frecuente hacia origin
- Pull Request para cualquier modificación
- Review obligatoria antes del merge
- Merge y despliegue inmediatos
Configuración de 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"]
Ventajas e inconvenientes
✅ Ventajas:
- Máxima simplicidad
- Despliegue continuo sencillo
- Feedback rápido
- Ideal para las web apps
❌ Inconvenientes:
- Sin staging explícito
- Difícil para las releases planificadas
- Requiere una CI/CD robusta
- Puede ser caótico sin disciplina
Trunk-Based Development
Principio
Desarrollo directamente sobre la rama principal con ramas de muy corta duración (< 1 día).
Prácticas clave
Commits frecuentes
# Varios commits al día sobre main
git add .
git commit -m "feat: add user validation (partial)"
git push origin main
# Unas horas más tarde
git add .
git commit -m "feat: complete user validation"
git push origin main
Feature Flags
// Usar feature flags para el código sin terminar
function processPayment(amount) {
if (featureFlags.newPaymentSystem) {
return newPaymentProcessor(amount);
}
return legacyPaymentProcessor(amount);
}
Ramas muy cortas
# Rama de un máximo de 1-2 días
git checkout -b quick-fix/typo-correction
# ... corrección rápida ...
git push origin quick-fix/typo-correction
# ... PR y merge inmediato ...
Release desde trunk
# Release branches desde 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 directamente sobre 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
Ventajas e inconvenientes
✅ Ventajas:
- Integración continua máxima
- Sin merge hell
- Feedback inmediato
- Simplicidad extrema
❌ Inconvenientes:
- Requiere una disciplina estricta
- Tests automatizados obligatorios
- Feature flags complejos
- No sirve para todos los tipos de proyectos
GitLab Flow
Principio
Combinación de GitHub Flow con ramas de entorno.
Estructura con entornos
# Ramas de entorno
main # Desarrollo
staging # Tests de integración
production # Producción
# Workflow
git checkout main
git checkout -b feature/new-api
# Desarrollo
git push origin feature/new-api
# ... Pull Request hacia main ...
# Despliegue en staging
git checkout staging
git merge main
git push origin staging
# Tests en staging
# ... validación ...
# Despliegue en producción
git checkout production
git merge staging
git push origin production
Release branches
# Para las releases planificadas
git checkout main
git checkout -b release/2.1.0
# Cherry-pick de las features
git cherry-pick feature-commit-1
git cherry-pick feature-commit-2
# Despliegue de la release
git checkout production
git merge release/2.1.0
git tag v2.1.0
Forking Workflow
Principio
Cada desarrollador tiene su propio fork del repositorio principal.
Workflow completo
# 1. Fork del repositorio principal (vía GitHub)
# 2. Clonar tu fork
git clone https://github.com/VOUS/projet.git
cd projet
# 3. Añadir el upstream
git remote add upstream https://github.com/ORIGINAL/projet.git
# 4. Crear una rama feature
git checkout -b feature/awesome-feature
# 5. Desarrollar
# ... commits ...
# 6. Sincronizar con upstream
git fetch upstream
git rebase upstream/main
# 7. Hacer push a tu fork
git push origin feature/awesome-feature
# 8. Crear una Pull Request hacia el upstream
Mantenimiento del fork
# Sincronización regular
git fetch upstream
git checkout main
git merge upstream/main
git push origin main
# Limpieza de las ramas
git branch -d feature/completed-feature
git push origin --delete feature/completed-feature
Elegir el workflow adecuado
Criterios de decisión
Tabla comparativa
| Workflow | Complejidad | Equipo | Despliegue | Releases |
|---|---|---|---|---|
| GitHub Flow | Baja | Pequeño-Mediano | Continuo | Frecuentes |
| Git Flow | Alta | Mediano-Grande | Planificado | Planificadas |
| Trunk-Based | Baja | Cualquiera | Continuo | Continuas |
| GitLab Flow | Media | Mediano | Mixto | Flexibles |
| Forking | Media | Open Source | Variable | Variables |
Puesta en marcha de un workflow
GitHub Flow - Configuración
# .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
# Crear la 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
# Comprobar que los tests pasan antes del push
npm test
if [ $? -ne 0 ]; then
echo "Tests failed. Push aborted."
exit 1
fi
# Comprobar que el código está formateado
npm run lint
if [ $? -ne 0 ]; then
echo "Linting failed. Push aborted."
exit 1
fi
Ejercicios prácticos
Ejercicio 1: Simular GitHub Flow
# 1. Crear un repositorio de prueba
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 el desarrollo de una 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 una Pull Request (merge)
git checkout main
git merge --no-ff feature/add-calculator
git branch -d feature/add-calculator
# 4. Repetir con otras 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
Ejercicio 2: Experimentar con Git Flow
# 1. Inicializar Git Flow
git flow init
# 2. Crear una 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. Crear una 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 un 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
Buenas prácticas transversales
Mensajes de commit
# Convención 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
Protección de las ramas
# Vía 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}'
Automatización
# .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 adicionales
Herramientas de workflow
- Git Flow AVH: extensión mejorada de Git Flow
- GitHub CLI: automatización de los workflows de GitHub
- GitKraken Glo: gestión de proyectos integrada
- Sourcetree: interfaz gráfica compatible con los workflows
Documentación
Conclusión
La elección del workflow de Git depende de numerosos factores: el tamaño del equipo, el tipo de proyecto, la frecuencia de despliegue y la cultura de la empresa. Lo importante es elegir un workflow adaptado a su contexto y mantenerlo de forma coherente.
En el próximo tutorial exploraremos los submódulos y los subárboles de Git para gestionar proyectos complejos con dependencias externas.
Tiempo de lectura estimado: 35 minutos
Nivel: Avanzado
Etapa anterior: Resolución de conflictos
Siguiente etapa: Submódulos y subárboles de Git