⚡ GIT CHEAT SHEET - AUDIOLAB¶
Comandos Esenciales con Ejemplos Prácticos¶
Quick Reference - Bookmarkea esta página para consultas rápidas
📋 TABLA DE CONTENIDOS¶
- Setup Inicial
- Operaciones Diarias
- Branching
- Merging
- Stashing
- History
- Recovery
- Remote
- Advanced
- AudioLab Workflows
🔧 SETUP INICIAL¶
Primera Vez (hacer una vez por máquina)¶
# Configurar identidad
git config --global user.name "Tu Nombre"
git config --global user.email "tu.email@audiolab.com"
# Editor preferido
git config --global core.editor "code --wait" # VS Code
# git config --global core.editor "vim" # Vim
# Line endings (IMPORTANTE para cross-platform)
git config --global core.autocrlf input # Linux/Mac
# git config --global core.autocrlf true # Windows
# Default branch name
git config --global init.defaultBranch main
# Colores en terminal
git config --global color.ui auto
# Rebase por default en pull
git config --global pull.rebase true
Clonar Repositorio¶
# HTTPS (recomendado para comenzar)
git clone https://github.com/audiolab/audio-lab.git
# SSH (recomendado para trabajo diario)
git clone git@github.com:audiolab/audio-lab.git
# Clonar branch específico
git clone -b develop https://github.com/audiolab/audio-lab.git
📦 OPERACIONES DIARIAS¶
Ciclo Básico (90% de tu trabajo)¶
# 1. SINCRONIZAR con remote
git fetch # Traer cambios sin aplicar
git pull # = fetch + merge (o rebase si configurado)
# 2. VER ESTADO
git status # Ver cambios actuales
git status -s # Versión corta
# 3. AÑADIR CAMBIOS
git add archivo.cpp # Añadir archivo específico
git add src/ # Añadir directorio
git add . # Añadir todo (usar con cuidado)
git add -p # Añadir interactivamente (chunk por chunk)
# 4. COMMIT
git commit -m "tipo: descripción corta"
git commit # Abre editor para mensaje largo
git commit --amend # Modificar último commit (solo si NO pusheado)
# 5. PUSH
git push # Pushear a remote
git push -u origin feature-x # Primera vez (set upstream)
Ver Diferencias¶
# Cambios no staged
git diff # Ver cambios en working directory
git diff archivo.cpp # Diff de archivo específico
# Cambios staged
git diff --staged # Ver lo que vas a commitear
git diff --cached # Sinónimo de --staged
# Entre branches
git diff main..feature-x # Comparar branches
git diff HEAD~1 # Diff con commit anterior
🌿 BRANCHING¶
Crear y Cambiar Branches¶
# Ver branches
git branch # Listar branches locales
git branch -a # Listar todos (incluye remote)
git branch -v # Ver con último commit
# Crear branch
git branch feature/reverb-algo # Crear (no cambia a él)
git checkout -b feature/reverb-algo # Crear y cambiar
git switch -c feature/reverb-algo # Nuevo comando (Git 2.23+)
# Cambiar branch
git checkout main # Cambiar a branch existente
git switch main # Nuevo comando
# Borrar branch
git branch -d feature-x # Borrar (safe, solo si merged)
git branch -D feature-x # FORZAR borrar (¡cuidado!)
AudioLab Naming Convention¶
# FORMATO: tipo/scope/descripción
git checkout -b feature/dsp/reverb-algorithm
git checkout -b fix/audio/buffer-underrun
git checkout -b experiment/ml/source-separation
git checkout -b refactor/core/memory-pool
git checkout -b hotfix/plugin/vst3-crash
# TIPOS:
# - feature/ : Nueva funcionalidad
# - fix/ : Bug fix
# - hotfix/ : Emergencia en producción
# - experiment/: Research, puede fallar
# - refactor/ : Mejora interna
# - perf/ : Optimización
# - test/ : Mejoras de testing
# - docs/ : Documentación
🔀 MERGING¶
Merge Básico¶
# Mergear feature a main
git checkout main # Ir a branch destino
git merge feature/reverb-algo # Mergear feature
# Merge con mensaje custom
git merge feature/x -m "Merge reverb feature"
# Abortar merge si hay conflictos
git merge --abort # Volver a estado pre-merge
Resolver Conflictos¶
# 1. Ver archivos en conflicto
git status # Lista archivos CONFLICT
# 2. Abrir archivo, verás:
# <<<<<<< HEAD
# tu versión
# =======
# su versión
# >>>>>>> feature-x
# 3. Editar manualmente, eliminar markers
# 4. Marcar como resuelto
git add archivo-resuelto.cpp
# 5. Completar merge
git commit # Mensaje auto-generado de merge
Estrategias de Merge¶
# Squash merge (todos commits en uno)
git merge --squash feature/x
git commit -m "Add feature X"
# No fast-forward (siempre crear merge commit)
git merge --no-ff feature/x
# Aceptar su versión para conflictos
git merge -X theirs feature/x
# Aceptar nuestra versión
git merge -X ours feature/x
💾 STASHING¶
Guardar Trabajo Temporal¶
# Guardar cambios sin commitear
git stash # Stash working directory
git stash -u # Incluir archivos untracked
git stash save "WIP: fixing audio bug" # Con mensaje descriptivo
# Ver stashes
git stash list # Listar todos
# stash@{0}: WIP: fixing audio bug
# stash@{1}: On main: experiments
# Aplicar stash
git stash pop # Aplicar último y borrar
git stash apply # Aplicar último sin borrar
git stash apply stash@{1} # Aplicar específico
# Borrar stash
git stash drop stash@{0} # Borrar específico
git stash clear # Borrar TODOS (¡cuidado!)
Casos de Uso¶
# Caso 1: Cambio de branch urgente
git stash # Guardar trabajo
git checkout hotfix # Cambiar a hotfix
# ... arreglar bug ...
git checkout feature # Volver a feature
git stash pop # Continuar trabajo
# Caso 2: Pull con cambios locales
git stash # Guardar cambios
git pull # Actualizar
git stash pop # Aplicar sobre nuevo código
📜 HISTORY¶
Ver Log¶
# Log básico
git log # Log completo
git log --oneline # Una línea por commit
git log --graph # Con grafo ASCII
git log --all --graph --oneline # Todo junto (útil!)
# Log limitado
git log -5 # Últimos 5 commits
git log --since="2 weeks ago" # Últimas 2 semanas
git log --author="Juan" # Por autor
# Log de archivo específico
git log -- src/audio.cpp # Historia de un archivo
git log -p -- audio.cpp # Con diffs
# Buscar en log
git log --grep="reverb" # Buscar en mensajes
git log -S "function_name" # Buscar código específico
Blame (¿Quién escribió esto?)¶
# Ver autor de cada línea
git blame archivo.cpp # Toda la file
git blame -L 10,20 archivo.cpp # Líneas 10-20
git blame -e archivo.cpp # Mostrar emails
Bisect (Encontrar Bug)¶
# Encontrar commit que introdujo bug
git bisect start # Iniciar bisect
git bisect bad # Commit actual es malo
git bisect good v1.0.0 # v1.0.0 era bueno
# Git checkoutea punto medio, tú pruebas:
make test
git bisect good # Si funciona
# O:
git bisect bad # Si está roto
# Repetir hasta encontrar el commit culpable
git bisect reset # Terminar bisect
🚨 RECOVERY¶
Deshacer Cambios¶
# UNSTAGE archivos (quitar de staging)
git reset HEAD archivo.cpp # Unstage específico
git reset # Unstage todo
# DISCARD cambios en working directory (¡DESTRUCTIVO!)
git checkout -- archivo.cpp # Volver a versión commiteada
git restore archivo.cpp # Nuevo comando (Git 2.23+)
git restore . # Restaurar todo (¡cuidado!)
# LIMPIAR archivos untracked (¡DESTRUCTIVO!)
git clean -n # Dry-run (ver qué borraría)
git clean -f # Forzar borrar
git clean -fd # Borrar files + directories
Reset (TIME TRAVEL)¶
# SOFT: Deshacer commits, mantener cambios staged
git reset --soft HEAD~1 # Volver 1 commit
git reset --soft abc1234 # Volver a commit específico
# MIXED (default): Deshacer commits, cambios unstaged
git reset HEAD~1 # Volver 1 commit
git reset HEAD~3 # Volver 3 commits
# HARD: DESTRUIR todo (commits + staged + working) ⚠️
git reset --hard HEAD~1 # ¡CUIDADO! Pérdida permanente
git reset --hard origin/main # Sincronizar con remote
Revert (Deshacer SIN reescribir historia)¶
# Crear nuevo commit que deshace cambios
git revert abc1234 # Revertir commit específico
git revert HEAD # Revertir último commit
git revert HEAD~3..HEAD # Revertir últimos 3
# Revert de merge commit
git revert -m 1 merge-commit-sha # -m 1 = mantener parent 1
Reflog (MÁQUINA DEL TIEMPO)¶
# Ver TODA tu historia (incluso commits "perdidos")
git reflog # Ver reflog
git reflog show HEAD # Explícito
# Recuperar commit "perdido"
git reflog # Encontrar SHA
# HEAD@{5} abc1234: commit: Feature importante
git checkout abc1234 # O crear branch:
git branch feature-recovered abc1234 # Recuperar como branch
🌐 REMOTE¶
Ver Remotes¶
# Listar remotes
git remote -v # Ver URLs
git remote show origin # Info detallada
# Añadir remote
git remote add upstream https://github.com/original/repo.git
git remote add backup git@gitlab.com:backup/repo.git
Fetch vs Pull¶
# FETCH: Traer sin aplicar
git fetch origin # Traer de origin
git fetch --all # Traer de todos remotes
# PULL: Fetch + Merge (o Rebase)
git pull # = fetch + merge
git pull --rebase # = fetch + rebase
git pull origin main # Específico
Push¶
# Push básico
git push # Push a upstream
git push origin feature-x # Push a branch específico
git push -u origin feature-x # Set upstream tracking
# Force push (¡PELIGROSO!)
git push --force # ⚠️ Reescribe historia
git push --force-with-lease # Más seguro (verifica remote)
# Borrar branch remoto
git push origin --delete feature-x # Borrar del remote
Tracking Branches¶
# Ver tracking
git branch -vv # Ver qué trackea cada branch
# Set upstream
git branch -u origin/feature-x # Set upstream de branch actual
git push -u origin feature-x # Set al pushear
🧙 ADVANCED¶
Rebase¶
# Rebase básico
git checkout feature # Ir a feature branch
git rebase main # Rebasar sobre main
# Rebase interactivo (reescribir historia)
git rebase -i HEAD~5 # Últimos 5 commits
# Opciones en editor:
# pick = usar commit
# reword = cambiar mensaje
# edit = pausar para enmendar
# squash = combinar con anterior
# drop = eliminar commit
# Continuar/abortar rebase
git rebase --continue # Después de resolver conflictos
git rebase --abort # Cancelar rebase
Cherry-Pick¶
# Aplicar commits específicos
git cherry-pick abc1234 # Aplicar un commit
git cherry-pick abc1234 def5678 # Aplicar múltiples
git cherry-pick abc1234..def5678 # Aplicar rango
Submodules (Para dependencias)¶
# Añadir submodule
git submodule add https://github.com/lib/repo.git libs/repo
# Clonar repo con submodules
git clone --recursive https://github.com/audiolab/repo.git
# Update submodules
git submodule update --init --recursive # Inicializar
git submodule update --remote # Actualizar a latest
Tags (Versiones)¶
# Crear tag
git tag v1.0.0 # Tag ligero
git tag -a v1.0.0 -m "Release 1.0.0" # Tag anotado (recomendado)
# Listar tags
git tag # Listar todos
git tag -l "v1.*" # Filtrar
# Push tags
git push origin v1.0.0 # Push tag específico
git push --tags # Push todos los tags
# Checkout tag
git checkout v1.0.0 # Ver código de versión
🎵 AUDIOLAB WORKFLOWS¶
Workflow 1: Feature Development¶
# 1. Sincronizar con develop
git checkout develop
git pull
# 2. Crear feature branch
git checkout -b feature/dsp/new-reverb
# 3. Desarrollar (ciclo repetido)
# ... editar código ...
git add src/reverb.cpp
git commit -m "feat(dsp): implement Schroeder reverb algorithm"
# ... más edits ...
git commit -m "feat(dsp): add reverb parameters"
# 4. Sincronizar con develop (si ha cambiado)
git fetch origin
git rebase origin/develop # Mantener historia limpia
# 5. Push para backup / code review
git push -u origin feature/dsp/new-reverb
# 6. Crear Pull Request en GitHub
# (desde UI de GitHub)
# 7. Después de merge, limpiar
git checkout develop
git pull
git branch -d feature/dsp/new-reverb # Borrar local
Workflow 2: Hotfix Urgente¶
# 1. Desde main (producción)
git checkout main
git pull
# 2. Crear hotfix branch
git checkout -b hotfix/crash-on-startup
# 3. Fix rápido
# ... arreglar bug ...
git commit -m "fix: resolve crash on startup with null buffer"
# 4. Push y PR a main
git push -u origin hotfix/crash-on-startup
# Crear PR target=main
# 5. Después de merge, backport a develop
git checkout develop
git cherry-pick <hotfix-commit-sha>
git push
Workflow 3: Code Review Updates¶
# Después de feedback en PR
git checkout feature/my-feature
# Opción A: Commits adicionales
git commit -m "review: address feedback on error handling"
git push
# Opción B: Amend último commit (si feedback es menor)
git commit --amend --no-edit # Sin cambiar mensaje
git push --force-with-lease # Update PR
🎨 ALIASES ÚTILES¶
Agregar a ~/.gitconfig:
[alias]
# Status y log
st = status -s
lg = log --oneline --graph --all --decorate
last = log -1 HEAD
# Branches
br = branch -v
co = checkout
sw = switch
# Commit
ci = commit
amend = commit --amend --no-edit
# Diff
df = diff
dfs = diff --staged
# Reset safe
unstage = reset HEAD
undo = reset --soft HEAD~1
# Stash
save = stash save
pop = stash pop
# Remote
sync = !git fetch --all && git pull --rebase
# Cleanup
cleanup = !git branch --merged | grep -v '\\*\\|main\\|develop' | xargs -n 1 git branch -d
Uso:
git st # En vez de git status -s
git lg # Log bonito
git undo # Deshacer último commit (safe)
git cleanup # Borrar branches mergeados
🚨 COMANDOS DE EMERGENCIA¶
# "Cometí error, quiero volver!"
git reflog # Ver historia completa
git reset --hard HEAD@{2} # Volver a estado anterior
# "Commiteé a branch equivocado"
git reset HEAD~1 # Deshacer commit
git stash # Guardar cambios
git checkout branch-correcto # Cambiar
git stash pop # Aplicar y commitear
# "Force pusheé por error a main"
git reflog # Encontrar SHA correcto
git reset --hard abc1234 # Volver localmente
git push --force-with-lease # Restaurar remote (COORDINAR CON EQUIPO)
# "No puedo hacer pull, tengo conflictos"
git stash # Guardar cambios
git pull # Actualizar
git stash pop # Re-aplicar (resolver conflictos si hay)
# "Quiero cancelar TODO y empezar de cero"
git fetch origin
git reset --hard origin/main # ⚠️ DESTRUCTIVO
git clean -fd # Borrar untracked
📚 MÁS INFORMACIÓN¶
- Ver documentación completa: README.md
- Emergencias: DISASTER_RECOVERY_PHILOSOPHY.md
- Workflows avanzados: ADVANCED_WORKFLOWS_MASTERY.md
💡 TIP: Imprime esta página o guárdala como PDF para referencia rápida.
⚠️ RECUERDA:
- --force es peligroso en branches compartidos
- Siempre fetch antes de push
- Commit frecuentemente, push regularmente
- Cuando dudes, crea backup branch primero
Última actualización: 2025-10-09