Git Advanced Workflows: Rebase, Cherry-pick und Interactive History
DevOps19. November 202517 Min. Lesezeit0 Aufrufe
GitVersion ControlDevOpsWorkflowBest PracticesDevelopment
Teilen:
Git Advanced Workflows: Rebase, Cherry-pick und Interactive History
Basic Git (Add, Commit, Push) wird gestartet. Advanced Git macht einen Profi. Meistern wir die Techniken, die Anfänger von Experten trennen. Warum Fortgeschrittene Git Matten
Professionelle Entwickler benötigen:
- 📝 Clean Commit History
- 🔄 Flexible Verzweigungsstrategien
- 🛠️ Fähigkeit, Fehler zu beheben
- 👥 Glatte Teamkollaboration
oder Git Rebase: Geschichte schreiben
Merge vs Rebase
Merge:
main: A---B---C---D
\ \
feature: E---F---G---M
```_
**Rebase:**
main: A---B---C---D
feature: E'--F'--G'
### Grundlegende Rebase ```bash # On feature branch git checkout feature git rebase main # Or in one command git rebase main feature ```_ ** Was passiert:** ANHANG Git findet gemeinsame Vorfahren 2. Speichert Ihre Verpflichtungen (E, F, G) 3. Gilt für Hauptverpflichtungen 4. Replays Ihre Commits auf ### Umgang mit Konflikten ```bash # During rebase, you hit a conflict <<<<<<< HEAD const version = "2.0"; ======= const version = "1.5"; >>>>>>> feature-branch # Fix the conflict manually, then: git add . git rebase --continue # Or abort if needed git rebase --abort ``` Interactive Rebase: Clean Up Commits ### Squash Commits ```bash # Rebase last 3 commits git rebase -i HEAD~3 # Editor opens: pick abc1234 Add user model pick def5678 Fix typo pick ghi9012 Add validation # Change to: pick abc1234 Add user model squash def5678 Fix typo squash ghi9012 Add validation # Save and exit # All 3 commits become 1 ``` ### Reorder Commits ```bash git rebase -i HEAD~4 # Original order: pick abc1234 Add feature A pick def5678 Add feature B pick ghi9012 Fix bug in A pick jkl3456 Add tests # Reorder: pick abc1234 Add feature A pick ghi9012 Fix bug in A pick def5678 Add feature B pick jkl3456 Add tests ```_ ### Commit Nachricht bearbeiten __CODE_BLOCK_6_ ### Commit ```bash git rebase -i HEAD~1 # Change: pick abc1234 Add user and order models # To: edit abc1234 Add user and order models # Git pauses, now: git reset HEAD^ git add user.model.js git commit -m "Add user model" git add order.model.js git commit -m "Add order model" git rebase --continue ``` Cherry-pick: Select Specific Commits ### Basic Cherry-pick __CODE_BLOCK_8_ ### Cherry-pick Range __CODE_BLOCK_9_ Cherry-pick ohne Commit ```bash # Apply changes without committing git cherry-pick -n def5678 # Make changes git add . git commit -m "Custom message" ``` Git Reflog: Recover Lost Commits ```bash # View all actions git reflog # Output: abc1234 HEAD@{0}: commit: Add feature def5678 HEAD@{1}: rebase: Add tests ghi9012 HEAD@{2}: reset: moving to HEAD~1 # Recover deleted commit git reset --hard HEAD@{1} # Or create new branch from it git checkout -b recovered HEAD@{2} ``` Git Stash: Arbeit in Progress speichern ### Basic Stash ```bash # Save current changes git stash # Save with message git stash save "WIP: User authentication" # List stashes git stash list # Apply latest stash git stash pop # Apply specific stash git stash apply stash@{2} ``` ### Spezifische Dateien löschen ```bash # Stash only staged files git stash --staged # Stash including untracked files git stash -u # Stash specific files git stash push -m "Stash config" config.js ``` ### Branch aus Stash erstellen __CODE_BLOCK_14_ Git Bisect: Finde Fehler mit Binary Search ```bash # Start bisect git bisect start # Mark current as bad git bisect bad # Mark known good commit git bisect good abc1234 # Git checks out middle commit # Test it, then mark: git bisect good # or bad # Repeat until bug found # Git will say: "abc1234 is the first bad commit" # Finish bisect git bisect reset ```_ ### Automated Bisect ```bash # Automate with test script git bisect start HEAD abc1234 git bisect run npm test # Git automatically finds bad commit ``` Git Worktree: Mehrere Arbeitsverzeichnisse ```bash # List worktrees git worktree list # Create new worktree git worktree add ../feature-branch feature-branch # Now you have: # /project (main branch) # /feature-branch (feature branch) # Remove worktree git worktree remove ../feature-branch ``` / Advanced Reset Strategies ### Soft Reset (Keep Changes Staged) ```bash # Undo last commit, keep changes staged git reset --soft HEAD~1 # Changes are in staging area git status # Changes to be committed: # modified: file.js ``` ### Gemischt Zurücksetzen (Standard - Ändern bleiben unverändert) ```bash # Undo last commit, keep changes unstaged git reset HEAD~1 # Changes are in working directory git status # Changes not staged for commit: # modified: file.js ``` ### Hard Reset (Discard Changes) ```bash # Undo last commit, discard all changes git reset --hard HEAD~1 # Everything gone! ``` Git Hooks: Automate Workflows ### Hook ```bash # .git/hooks/pre-commit #!/bin/sh # Run linter npm run lint # If fails, prevent commit if [ $? -ne 0 ]; then echo "Linting failed. Fix errors before committing." exit 1 fi # Run tests npm test if [ $? -ne 0 ]; then echo "Tests failed. Fix tests before committing." exit 1 fi ``` ### Nachricht senden ```bash # .git/hooks/commit-msg #!/bin/sh # Enforce commit message format commit_msg=$(cat $1) if ! echo "$commit_msg" | grep -qE "^(feat|fix|docs|style|refactor|test|chore): "; then echo "Invalid commit message format." echo "Use: feat|fix|docs|style|refactor|test|chore: message" exit 1 fi ```_ Git Aliases: Zeit sparen ```bash # Add to ~/.gitconfig [alias] # Shortcuts co = checkout br = branch ci = commit st = status # Log with graph lg = log --graph --oneline --all --decorate # Undo last commit undo = reset --soft HEAD~1 # Amend without editing message amend = commit --amend --no-edit # Show branches sorted by last commit recent = branch --sort=-committerdate # Clean branches (merged to main) cleanup = !git branch --merged main | grep -v "main" | xargs git branch -d ``` Workflow Strategien ### Git Flow ``` main (production) ↓ develop (integration) ↓ feature/user-auth feature/payment hotfix/critical-bug ```__```bash # Start feature git checkout -b feature/user-auth develop # Finish feature git checkout develop git merge --no-ff feature/user-auth git branch -d feature/user-auth # Hotfix git checkout -b hotfix/1.2.1 main # Fix... git checkout main git merge --no-ff hotfix/1.2.1 git checkout develop git merge --no-ff hotfix/1.2.1 git branch -d hotfix/1.2.1 ``` ### Trunk-Based Development ``` main (always deployable) ↓ short-lived feature branches (< 1 day) ```_```bash # Create short-lived branch git checkout -b quick-feature # Work... git add . git commit -m "feat: Add quick feature" # Rebase on main (keep history clean) git rebase main # Merge to main git checkout main git merge quick-feature git branch -d quick-feature ```_ Best Practices 1. ✅ **Commit oft**, perfekt später (interaktive Rebase) 2. ✅ **Bewertung schreiben** 3. ✅ **Rebase-Funktionszweige** vor dem Zusammenbau 4. ✅ **Verwendete Zweige** für alles 5. ✅ **Never rebase public history** 6. ✅ **Review-Änderungen** vor dem Commiting 7. ✅ **Keep begeht atomisch** (eine logische Änderung) **Keine Rebase öffentlicher Filialen** ```bash # Never do this on main/develop git checkout main git rebase feature # ❌ BAD ```_ ❌ **Kräfte nicht auf geteilte Filialen** ```bash # Dangerous on shared branches git push --force origin main # ❌ BAD ``` ❌ **Keine Geheimnisse** ```bash # Remove from history if committed git filter-branch --force --index-filter "git rm --cached --ignore-unmatch config/secrets.yml" --prune-empty --tag-name-filter cat -- --all ```__ Git gibt Ihnen Superkräfte: - Saubere, professionelle Commit-Geschichte - Flexible Workflows - Einfache Bug-Jagd - Vertrauen zum Experimentieren Master diese Techniken, und Git wird ein mächtiger Verbündeter, nicht nur eine versionskontrolle! 🎯