Los sábados optimizamos nuestros espacios de trabajo. Hoy enfoque en Git: la herramienta de control de versiones que usamos diariamente pero que frecuentemente está suboptimizada. Un workflow de Git bien configurado puede transformar tu velocidad de desarrollo y colaboración en equipo.
Configuración Base Inteligente
Global Git Configuration
# Configuración de identidad
git config --global user.name "Tu Nombre"
git config --global user.email "tu.email@empresa.com"
# Editor preferido
git config --global core.editor "code --wait"
# Configuraciones de rendimiento
git config --global core.preloadindex true
git config --global core.fscache true
git config --global gc.auto 256
# Configuración de colores
git config --global color.ui auto
git config --global color.branch.current "yellow reverse"
git config --global color.branch.local yellow
git config --global color.branch.remote green
git config --global color.diff.meta "yellow bold"
git config --global color.diff.frag "magenta bold"
git config --global color.diff.old "red bold"
git config --global color.diff.new "green bold"
Aliases que Transforman tu Productividad
# Aliases esenciales para workflow diario
git config --global alias.st "status -s"
git config --global alias.co "checkout"
git config --global alias.br "branch"
git config --global alias.ci "commit"
git config --global alias.unstage "reset HEAD --"
git config --global alias.last "log -1 HEAD"
git config --global alias.visual "!gitk"
# Aliases avanzados para power users
git config --global alias.lg "log --oneline --graph --decorate --all"
git config --global alias.lga "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --all"
git config --global alias.contributors "shortlog --summary --numbered"
git config --global alias.amend "commit --amend --no-edit"
git config --global alias.undo "reset --soft HEAD~1"
git config --global alias.wip "commit -am 'WIP: work in progress'"
git config --global alias.unwip "reset HEAD~1"
# Aliases para limpieza y mantenimiento
git config --global alias.cleanup "!git branch --merged | grep -v '\\*\\|master\\|main\\|develop' | xargs -n 1 git branch -d"
git config --global alias.fresh "!git fetch --all --prune && git cleanup"
git config --global alias.overview "!git log --all --since='2 weeks' --oneline --no-merges"
.gitconfig Avanzado
# ~/.gitconfig - Configuración completa optimizada
[user]
name = Tu Nombre
email = tu.email@empresa.com
[core]
editor = code --wait
autocrlf = input
safecrlf = true
preloadindex = true
fscache = true
[push]
default = current
autoSetupRemote = true
[pull]
rebase = true
[rebase]
autoStash = true
[merge]
tool = vscode
conflictstyle = diff3
[mergetool "vscode"]
cmd = code --wait $MERGED
[diff]
tool = vscode
algorithm = patience
[difftool "vscode"]
cmd = code --wait --diff $LOCAL $REMOTE
[branch]
autosetupmerge = always
autosetuprebase = always
[rerere]
enabled = true
[help]
autocorrect = 1
Branch Management Strategy
Git Flow Moderno Simplificado
# Estructura de branches recomendada
main/master # Código en producción
develop # Integración de features
feature/* # Nuevas funcionalidades
hotfix/* # Fixes urgentes para producción
release/* # Preparación de releases
Workflow Commands
# Iniciar nueva feature
git checkout develop
git pull origin develop
git checkout -b feature/nueva-funcionalidad
# Durante desarrollo
git add .
git commit -m "feat: implement user authentication"
git push -u origin feature/nueva-funcionalidad
# Finalizar feature
git checkout develop
git pull origin develop
git merge --no-ff feature/nueva-funcionalidad
git push origin develop
git branch -d feature/nueva-funcionalidad
Scripts de Automatización
#!/bin/bash
# git-new-feature.sh
FEATURE_NAME=$1
if [ -z "$FEATURE_NAME" ]; then
echo "Usage: git-new-feature.sh <feature-name>"
exit 1
fi
echo "🌱 Creating new feature branch: $FEATURE_NAME"
# Asegurar que estamos en develop actualizado
git checkout develop
git pull origin develop
# Crear y cambiar a nueva branch
git checkout -b feature/$FEATURE_NAME
echo "✅ Feature branch created and checked out"
echo "📝 Remember to push with: git push -u origin feature/$FEATURE_NAME"
#!/bin/bash
# git-finish-feature.sh
CURRENT_BRANCH=$(git branch --show-current)
if [[ $CURRENT_BRANCH != feature/* ]]; then
echo "❌ Not on a feature branch"
exit 1
fi
echo "🔄 Finishing feature: $CURRENT_BRANCH"
# Push final changes
git push origin $CURRENT_BRANCH
# Switch to develop and update
git checkout develop
git pull origin develop
# Merge feature
git merge --no-ff $CURRENT_BRANCH
# Push updated develop
git push origin develop
# Clean up
git branch -d $CURRENT_BRANCH
git push origin --delete $CURRENT_BRANCH
echo "✅ Feature merged and cleaned up"
Commit Message Standards
Conventional Commits Format
# Formato estándar
<type>[optional scope]: <description>
[optional body]
[optional footer(s)]
Types y Examples
# Features nuevas
feat: add user authentication system
feat(auth): implement JWT token validation
# Bug fixes
fix: resolve login redirect issue
fix(api): handle null response in user endpoint
# Documentation
docs: update API documentation
docs(readme): add installation instructions
# Refactoring
refactor: extract user service logic
refactor(components): simplify button component structure
# Performance
perf: optimize database queries
perf(frontend): lazy load non-critical components
# Testing
test: add unit tests for user service
test(integration): add API endpoint tests
# Maintenance
chore: update dependencies
chore(build): configure webpack optimization
Commit Message Template
# ~/.gitmessage
# Commit message template
# Type: feat|fix|docs|style|refactor|perf|test|chore
#
# feat: A new feature
# fix: A bug fix
# docs: Documentation only changes
# style: Changes that do not affect the meaning of the code
# refactor: A code change that neither fixes a bug nor adds a feature
# perf: A code change that improves performance
# test: Adding missing tests or correcting existing tests
# chore: Changes to the build process or auxiliary tools
#
# Subject line (try to keep under 50 characters)
#
# Body (wrap at 72 characters)
# Explain what and why vs. how
#
# Footer
# Reference issues and pull requests
# Configurar template
git config --global commit.template ~/.gitmessage
Git Hooks para Automation
Pre-commit Hook
#!/bin/sh
# .git/hooks/pre-commit
echo "🔍 Running pre-commit checks..."
# Check for console.log statements
if git diff --cached --name-only | grep -q "\.js$\|\.ts$\|\.jsx$\|\.tsx$"; then
if git diff --cached | grep -q "console\.log"; then
echo "❌ Found console.log statements. Please remove them."
git diff --cached | grep -n "console\.log"
exit 1
fi
fi
# Run linting
if command -v npm &> /dev/null && [ -f "package.json" ]; then
echo "🔧 Running ESLint..."
npm run lint:check || exit 1
fi
# Run type checking
if [ -f "tsconfig.json" ]; then
echo "📝 Running TypeScript check..."
npx tsc --noEmit || exit 1
fi
echo "✅ Pre-commit checks passed"
Commit-msg Hook
#!/bin/sh
# .git/hooks/commit-msg
# Check commit message format
commit_regex='^(feat|fix|docs|style|refactor|perf|test|chore)(\(.+\))?: .{1,50}'
if ! grep -qE "$commit_regex" "$1"; then
echo "❌ Invalid commit message format!"
echo "Format: type(scope): description"
echo "Types: feat, fix, docs, style, refactor, perf, test, chore"
echo "Example: feat(auth): add login functionality"
exit 1
fi
echo "✅ Commit message format is valid"
Visual Git Tools Integration
VS Code Git Configuration
// settings.json
{
"git.enableSmartCommit": true,
"git.confirmSync": false,
"git.autofetch": true,
"git.autoStash": true,
"gitlens.views.repositories.location": "gitlens",
"gitlens.views.fileHistory.location": "gitlens",
"gitlens.views.lineHistory.location": "gitlens",
"gitlens.codeLens.enabled": true,
"gitlens.currentLine.enabled": true
}
GitLens Power Features
# Comandos útiles de GitLens en VS Code
Ctrl+Shift+P -> Git: View File History
Ctrl+Shift+P -> Git: View Line History
Ctrl+Shift+P -> GitLens: Open Repository on Remote
Ctrl+Shift+P -> GitLens: Compare References
Terminal Git UI
# Instalar herramientas visuales para terminal
brew install tig lazygit
# tig - navegador de history interactivo
tig --all
# lazygit - GUI completa en terminal
lazygit
Advanced Git Techniques
Interactive Rebase Mastery
# Limpiar commits antes de merge
git rebase -i HEAD~3
# Rebase interactivo con autosquash
git commit --fixup <commit-hash>
git rebase -i --autosquash HEAD~5
# Rebase onto latest main
git rebase main feature/my-feature
Time Travel con Git
# Encontrar bug con binary search
git bisect start
git bisect bad # Current commit is bad
git bisect good v1.0 # Version 1.0 was good
# Git checkout commits para testing
git bisect good/bad # Based on testing
git bisect reset # When done
# Reflog para recovery
git reflog # Ver historial de cambios
git reset --hard HEAD@{2} # Volver a estado anterior
# Cherry-pick específico
git cherry-pick <commit-hash> # Aplicar commit específico
git cherry-pick -n <commit-hash> # Sin hacer commit automático
Stash Management
# Stash avanzado
git stash push -m "WIP: user authentication" -- src/auth/
git stash push --include-untracked -m "Complete feature state"
# Gestión de stashes
git stash list
git stash show stash@{1}
git stash apply stash@{1}
git stash drop stash@{1}
git stash pop stash@{1}
# Stash parcial
git stash push -p -m "Partial changes"
Git Analytics y Productivity
Repository Health Check
#!/bin/bash
# git-health-check.sh
echo "📊 Git Repository Health Check"
echo "================================"
# Repository basics
echo "📁 Repository: $(basename $(git rev-parse --show-toplevel))"
echo "🌿 Current branch: $(git branch --show-current)"
echo "📝 Total commits: $(git rev-list --all --count)"
echo "👥 Contributors: $(git shortlog -sn | wc -l)"
# Recent activity
echo ""
echo "📅 Recent Activity (last 2 weeks):"
git log --since="2 weeks ago" --oneline --no-merges | wc -l | xargs echo " Commits:"
git log --since="2 weeks ago" --pretty=format:"%an" | sort | uniq | wc -l | xargs echo " Active contributors:"
# Branch information
echo ""
echo "🌳 Branch Information:"
echo " Local branches: $(git branch | wc -l)"
echo " Remote branches: $(git branch -r | wc -l)"
echo " Merged branches: $(git branch --merged | grep -v "\\*\\|master\\|main\\|develop" | wc -l)"
# Repository size
echo ""
echo "💾 Repository Size:"
echo " Total size: $(du -sh .git | cut -f1)"
echo " Objects: $(git count-objects -v | grep 'count' | cut -d' ' -f2)"
Personal Git Stats
#!/bin/bash
# git-my-stats.sh
AUTHOR=${1:-$(git config user.name)}
SINCE=${2:-"1 month ago"}
echo "📊 Git Stats for $AUTHOR (since $SINCE)"
echo "========================================"
echo "📝 Commits: $(git log --author="$AUTHOR" --since="$SINCE" --oneline | wc -l)"
echo "📁 Files changed: $(git log --author="$AUTHOR" --since="$SINCE" --name-only --pretty=format: | sort -u | wc -l)"
echo "➕ Lines added: $(git log --author="$AUTHOR" --since="$SINCE" --pretty=tformat: --numstat | awk '{add+=$1} END {print add+0}')"
echo "➖ Lines removed: $(git log --author="$AUTHOR" --since="$SINCE" --pretty=tformat: --numstat | awk '{del+=$2} END {print del+0}')"
echo ""
echo "🗓️ Commits by day:"
git log --author="$AUTHOR" --since="$SINCE" --format="%ad" --date=short | sort | uniq -c | sort -nr | head -10
echo ""
echo "📂 Most modified files:"
git log --author="$AUTHOR" --since="$SINCE" --name-only --pretty=format: | sort | uniq -c | sort -nr | head -10
Git Performance Optimization
Large Repository Optimization
# Configuraciones para repos grandes
git config core.preloadindex true
git config core.fscache true
git config gc.auto 256
# Configurar Git LFS para archivos grandes
git lfs install
git lfs track "*.psd"
git lfs track "*.zip"
git lfs track "*.mp4"
# Shallow clone para CI/CD
git clone --depth 1 <repository-url>
# Partial clone (Git 2.19+)
git clone --filter=blob:none <repository-url>
Repository Maintenance
#!/bin/bash
# git-maintenance.sh
echo "🧹 Running Git maintenance..."
# Garbage collection
git gc --aggressive --prune=now
# Repack objects
git repack -ad
# Verify repository integrity
git fsck --full
# Clean up remote-tracking branches
git remote prune origin
# Update all branches
git fetch --all --prune
echo "✅ Maintenance completed!"
Team Collaboration Workflows
Pull Request Checklist
## Pull Request Checklist
### Before Creating PR
- [ ] Branch is up to date with main/develop
- [ ] All tests pass locally
- [ ] Code follows team style guidelines
- [ ] No console.log or debug statements
- [ ] Commit messages follow convention
### PR Description
- [ ] Clear title describing the change
- [ ] Description explains what and why
- [ ] Screenshots for UI changes
- [ ] Related issues referenced
### Code Quality
- [ ] Code is self-documenting
- [ ] Complex logic has comments
- [ ] No duplicate code
- [ ] Error handling implemented
- [ ] Performance considerations addressed
Code Review Best Practices
# Preparar branch para review
git checkout feature/my-feature
git rebase main # Limpiar history
git push --force-with-lease # Push seguro después de rebase
# Review de otros desarrolladores
git fetch origin
git checkout -b review/feature-name origin/feature-name
git log --oneline main..HEAD # Ver commits nuevos
git diff main...HEAD # Ver cambios completos
Pro Tips y Shortcuts
Git Aliases Avanzados
# Aliases de conveniencia
git config --global alias.save '!git add -A && git commit -m "SAVEPOINT"'
git config --global alias.load 'checkout HEAD~1'
git config --global alias.back 'reset --soft HEAD~1'
# Aliases para debugging
git config --global alias.who 'shortlog -s --'
git config --global alias.what 'show --name-only'
git config --global alias.when 'log --oneline --since="1 week ago"'
# Aliases para limpieza
git config --global alias.nuke '!git reset --hard && git clean -fd'
git config --global alias.sync '!git checkout main && git pull origin main && git checkout - && git rebase main'
Quick Commands Reference
# Navegación rápida
git checkout - # Cambiar a branch anterior
git checkout @{-1} # Mismo que anterior
git checkout @{u} # Checkout a upstream branch
# Diferencias útiles
git diff --stat # Solo estadísticas de cambios
git diff --name-only # Solo nombres de archivos
git diff HEAD~2 HEAD # Comparar commits específicos
# Log formatting
git log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset'
git log --oneline --graph --all --decorate
Measuring Git Workflow Success
KPIs de Productividad
# Métricas de un workflow optimizado
- Tiempo promedio de commit: < 2 minutos
- Conflictos de merge: < 5% de PRs
- Branches activos simultáneos: 3-5 por developer
- Tiempo de code review: < 24 horas
- Rollbacks por bugs: < 2% de releases
Checklist de Setup Completado
Git global config optimizada
Aliases productivos configurados
Hooks de pre-commit instalados
Template de commit messages
Scripts de automatización
Visual tools integrados
Team workflow documentado
Optimización Continua
Un workflow de Git optimizado es fundamental para la productividad del desarrollo. La configuración inicial requiere tiempo, pero se amortiza rápidamente en velocidad y calidad de trabajo diario.
Beneficios de un setup optimizado:
Velocidad: Comandos más rápidos y automatización de tareas repetitivas
Calidad: Hooks que previenen errores comunes
Colaboración: Workflows consistentes en todo el equipo
Visibilidad: Mejor tracking de cambios y contribuciones
Mantenibilidad: Repository health y cleanup automático
¿Cuál es su comando de Git más usado que han optimizado con aliases? ¿Qué workflow de branches funciona mejor en sus equipos? ¿Tienen algún hook o script personalizado que no pueden vivir sin él?
Compartamos nuestras configuraciones de Git para crear un arsenal colectivo de productividad.
saturdaysetup git versioncontrol productivity devworkflow automation #TeamCollaboration
