Git Comandi Avanzati: Stash, Reflog e Bisect
Oltre ai comandi base (commit, push, merge), Git offre strumenti avanzati per gestire workflow complessi, recuperare lavoro perso e debuggare problemi. Git stash salva lavoro temporaneo, reflog è il tuo salvavita per recovery, e bisect trova bug con ricerca binaria. Padroneggiare questi comandi ti rende un Git power user.
🎯 Cosa Imparerai
- Git stash per salvare lavoro temporaneo
- Git reflog per recuperare commit "persi"
- Git bisect per trovare commit che hanno introdotto bug
- Worktree e submodules (bonus)
Git Stash: Il Tuo Blocco Note Temporaneo
git stash salva i cambiamenti non committati in una "scorta" temporanea, pulendo
la working directory. Utile quando serve cambiare branch velocemente ma il lavoro corrente non
è pronto per un commit.
# Situazione: stai lavorando su feature ma arriva hotfix urgente
git status
# modified: src/component.ts
# modified: src/style.css
# Salva i cambiamenti in stash
git stash
# Output: Saved working directory and index state WIP on feature: abc1234 last commit
# Working directory ora è pulito
git status
# nothing to commit, working tree clean
# Cambia branch e lavora sull'hotfix
git checkout main
# ... lavoro su hotfix ...
# Torna al feature branch
git checkout feature
# Recupera i cambiamenti da stash
git stash pop
# Riapplica i cambiamenti e rimuove lo stash
Stash Avanzato
# Stash con messaggio descrittivo
git stash save "WIP: refactoring authentication"
# Stash includendo file untracked
git stash -u
# Stash includendo tutto (anche .gitignore)
git stash -a
# Lista tutti gli stash
git stash list
# stashHEAD@{{ '{' }}0{{ '}' }}: WIP on feature: abc1234 refactoring auth
# stashHEAD@{{ '{' }}1{{ '}' }}: On main: def5678 emergency fix
# stashHEAD@{{ '{' }}2{{ '}' }}: WIP on develop: ghi9012 new feature
# Vedere contenuto di uno stash
git stash show stashHEAD@{{ '{' }}0{{ '}' }}
git stash show -p stashHEAD@{{ '{' }}0{{ '}' }} # Con diff completo
# Applicare stash senza rimuoverlo
git stash apply stashHEAD@{{ '{' }}1{{ '}' }}
# Rimuovere stash specifico
git stash drop stashHEAD@{{ '{' }}0{{ '}' }}
# Rimuovere tutti gli stash
git stash clear
# Creare branch da stash
git stash branch new-feature-branch stashHEAD@{{ '{' }}0{{ '}' }}
Stash Parziale
Puoi salvare solo alcuni file in stash, mantenendo altri nella working directory:
# Stash interattivo: scegli cosa salvare
git stash -p
# Per ogni hunk:
# y = stash this hunk
# n = do not stash this hunk
# q = quit
# a = stash this and all remaining hunks
# d = do not stash this or any remaining hunks
# Stash solo file specifici
git stash push -m "Save only component" src/component.ts
# Stash tutto tranne file specifici (path spec)
git stash push -- '*.ts' '!src/test.ts'
Git Reflog: Il Tuo Salvavita
git reflog registra ogni movimento di HEAD, anche commit cancellati,
reset, rebase abortiti. È il backup che ti salva quando pensi di aver perso tutto.
# Vedere reflog di HEAD
git reflog
# abc1234 HEADHEAD@{{ '{' }}0{{ '}' }}: commit: fix bug
# def5678 HEADHEAD@{{ '{' }}1{{ '}' }}: checkout: moving from main to feature
# ghi9012 HEADHEAD@{{ '{' }}2{{ '}' }}: reset: moving to HEAD~1
# jkl3456 HEADHEAD@{{ '{' }}3{{ '}' }}: commit: add feature
# mno7890 HEADHEAD@{{ '{' }}4{{ '}' }}: commit: initial commit
# Reflog di branch specifico
git reflog show feature
# Reflog con date
git reflog --date=relative
git reflog --date=iso
Recovery con Reflog
Esempi pratici di come reflog salva il tuo lavoro:
# Hai fatto reset e perso commit
git reset --hard HEAD~3
# Oh no! Volevo solo HEAD~1
# Trova i commit persi nel reflog
git reflog
# abc1234 HEADHEAD@{{ '{' }}0{{ '}' }}: reset: moving to HEAD~3
# def5678 HEADHEAD@{{ '{' }}1{{ '}' }}: commit: important feature ← VOGLIO QUESTO!
# Recupera il commit
git reset --hard def5678
# Oppure
git reset --hard HEADHEAD@{{ '{' }}1{{ '}' }}
# Commit recuperati!
# Cancelli branch per sbaglio
git branch -D feature-important
# Deleted branch feature-important (was abc1234).
# Oh no! Serve recuperarlo
git reflog
# Trova l'ultimo commit del branch cancellato
# abc1234 HEADHEAD@{{ '{' }}5{{ '}' }}: commit: last commit on feature
# Ricrea il branch
git branch feature-important abc1234
# Branch recuperato!
# Rebase va male, abortisci ma perdi lavoro
git rebase --abort
# Trova lo stato prima del rebase
git reflog
# def5678 HEADHEAD@{{ '{' }}1{{ '}' }}: rebase: aborting ← stato corrotto
# ghi9012 HEADHEAD@{{ '{' }}2{{ '}' }}: checkout: moving from feature to main
# abc1234 HEADHEAD@{{ '{' }}3{{ '}' }}: commit: my work ← STATO BUONO
# Torna allo stato pre-rebase
git reset --hard abc1234
Git Bisect: Debug con Ricerca Binaria
git bisect usa ricerca binaria per trovare quale commit ha introdotto un bug.
Invece di controllare manualmente centinaia di commit, bisect trova il colpevole in log(n) passi.
# Situazione: Il bug esiste ora (HEAD) ma non esisteva 10 giorni fa
# Hai 100 commit in mezzo: quale ha introdotto il bug?
# 1. Inizia bisect
git bisect start
# 2. Marca commit corrente come "bad" (ha il bug)
git bisect bad
# 3. Marca commit vecchio come "good" (non aveva il bug)
git bisect good abc1234
# Git fa checkout del commit a metà
# Bisecting: 50 revisions left to test after this
# 4. Testa se il bug esiste
npm test
# Se test fallisce:
git bisect bad
# Se test passa:
git bisect good
# 5. Ripeti fino a che Git trova il commit colpevole
# Bisecting: 25 revisions left...
# Bisecting: 12 revisions left...
# Bisecting: 6 revisions left...
# Bisecting: 3 revisions left...
# Bisecting: 1 revision left...
# def5678 is the first bad commit
# commit def5678
# Author: Developer <dev@example.com>
# Date: Mon Dec 1 10:00:00 2024
#
# refactor: change authentication logic ← QUESTO È IL COLPEVOLE
# 6. Fine bisect
git bisect reset
# HEAD torna al branch originale
Bisect Automatizzato
Puoi automatizzare bisect con uno script di test:
# test.sh - script che ritorna 0 se OK, 1 se bug presente
#!/bin/bash
npm test | grep "PASS"
exit $?
# Bisect automatico
git bisect start
git bisect bad HEAD
git bisect good abc1234
git bisect run ./test.sh
# Git testa automaticamente ogni commit e trova il colpevole!
# Output finale:
# def5678 is the first bad commit
Git Worktree: Branch Multipli Contemporanei
git worktree permette di avere più branch checked out contemporaneamente in
directory diverse. Utile per lavorare su hotfix senza stashdare il lavoro corrente.
# Situazione: stai su feature branch, serve urgente hotfix
# Invece di stash, crea nuovo worktree
# Crea worktree per hotfix
git worktree add ../hotfix-worktree hotfix/critical-bug
# Ora hai due directory:
# ./project (feature branch)
# ../hotfix-worktree (hotfix branch)
# Vai alla directory hotfix
cd ../hotfix-worktree
# Lavora sul fix
git commit -m "fix: critical bug"
git push
# Torna al progetto principale
cd ../project
# Continua lavoro su feature senza aver toccato nulla
# Lista worktree
git worktree list
# /path/to/project abc1234 [feature]
# /path/to/hotfix-worktree def5678 [hotfix/critical-bug]
# Rimuovi worktree quando finito
git worktree remove ../hotfix-worktree
Best Practices
✅ Stash
- Usa messaggi descrittivi:
git stash save "descrizione" - Non lasciare stash per mesi (committa o scarta)
- Usa
git stash listregolarmente per pulizia
✅ Reflog
- Controlla reflog prima di reset/rebase pericolosi
- Reflog è locale, non viene pushato
- Reflog si pulisce dopo 90 giorni (configurabile)
✅ Bisect
- Automatizza con script per velocità
- Assicurati che "good" commit sia davvero buono
- Usa
git bisect skipse un commit non compila
Comandi Bonus
# Git fsck: verifica integrità repository
git fsck
# Trova oggetti corrotti o dangling
# Git gc: garbage collection (pulizia)
git gc --aggressive
# Git clean: rimuovi file untracked
git clean -fd # -f force, -d directories
git clean -n # Dry run (vedi cosa verrebbe rimosso)
# Git archive: crea archive del codice
git archive --format=zip HEAD > code.zip
# Git blame: vedi chi ha scritto ogni riga
git blame file.ts
git blame -L 10,20 file.ts # Solo righe 10-20
# Git shortlog: summary di contributi
git shortlog -sn # -s summary, -n ordinato per numero
Conclusione
I comandi avanzati di Git trasformano situazioni difficili in problemi risolvibili. Stash gestisce lavoro temporaneo, reflog recupera commit "persi", e bisect trova bug efficientemente. Conoscere questi strumenti ti dà sicurezza per esplorare, sperimentare e recuperare da errori senza paura.
🎯 Punti Chiave
- Stash salva lavoro temporaneo:
git stash/git stash pop - Reflog registra tutto:
git reflogper recovery - Bisect trova bug con ricerca binaria:
git bisect start/good/bad - Worktree per branch multipli contemporanei
- Questi comandi ti salvano in situazioni critiche







