Wat is Git? Complete Gids voor Versiebeheer en Collaboration
Leer Git van de basis tot geavanceerde workflows. Ontdek hoe versiebeheer je development process kan transformeren en team collaboration verbeteren.
Zoek je Git Experts?
Vind ervaren Developers en DevOps Engineers met Git expertise voor je projecten
Inhoudsopgave
1. Wat is Git en waarom is het belangrijk?
Git Definitie
Git is een gedistribueerd versiebeheersysteem (DVCS) ontworpen door Linus Torvalds in 2005. Het trackt wijzigingen in broncode tijdens software development en stelt meerdere ontwikkelaars in staat om samen te werken aan projecten.
Versiebeheer
Bewaart complete geschiedenis van alle wijzigingen
Collaboration
Meerdere ontwikkelaars werken simultaan aan dezelfde codebase
Branching
Creëer geïsoleerde omgevingen voor features en fixes
Revert
Keer terug naar vorige versies bij fouten
| Eigenschap | Traditioneel Bestandsbeheer | Git Versiebeheer |
|---|---|---|
| Geschiedenis | Alleen huidige versie | Complete wijzigingsgeschiedenis |
| Collaboration | Bestanden delen via email/drive | Gedistribueerd samenwerken |
| Conflict Resolutie | Handmatig overschrijven | Geautomatiseerd merge tools |
| Experimenteren | Gevaarlijk in productiecode | Veilig via branches |
| Backup | Externe backup nodig | Elke clone is volledige backup |
Waarom Git essentieel is voor moderne ontwikkeling
Code Quality
- Trackt wie wat heeft gewijzigd
- Code reviews via pull requests
- Automatische testing integratie
Development Speed
- Parallelle ontwikkeling
- Snelle context switching
- Minimaliseert merge conflicts
Team Collaboration
- Wereldwijde samenwerking
- Transparante communicatie
- Knowledge sharing
DevOps Integration
- CI/CD pipeline trigger
- Infrastructure as Code
- Automated deployments
2. Git Basis Concepten
Git Architecture
Git werkt met drie belangrijkste gebieden die samen de workflow bepalen:
Working Directory, Staging Area, Repository
Git Workflow Architecture
┌─────────────────┐ git add ┌─────────────────┐ git commit ┌─────────────────┐
│ │ ────────────────▶│ │ ────────────────▶│ │
│ Working Directory│ │ Staging Area │ │ Repository │
│ (Workspace) │ │ (Index) │ │ (.git) │
│ │ ◀─────────────── │ │ ◀─────────────── │ │
│ Modificeer │ git restore │ Prepare │ git checkout │ Sla op │
│ bestanden │ │ voor commit │ │ geschiedenis │
└─────────────────┘ └─────────────────┘ └─────────────────┘
Working Directory
- Je lokale projectmap
- Waar je bestanden bewerkt
- Zichtbaar in file explorer
- Contains modified/untracked files
Staging Area
- Voorbereidingsgebied
- Selecteer wat gecommit wordt
- Commit "snapshot"
- Kan gewijzigd worden voor commit
Repository
- Git database (.git folder)
- Complete geschiedenis
- Branches, tags, commits
- Lokaal en remote opslag
Git Object Model
# Git slaat vier type objecten op:
# 1. BLOB (Binary Large Object)
# • Bewaart bestandsinhoud
# • Gecomprimeerd en versleuteld
# • SHA-1 hash als identifier
# 2. TREE
# • Representeert directory structuur
# • Bevat blobs en sub-trees
# • Slaat bestandsnamen en permissies op
# 3. COMMIT
# • Snapshot van project op bepaald moment
# • Bevat: parent commit(s), tree, author, message
# • Onveranderlijk (immutable)
# 4. TAG
# • Vastzetten van specifieke commit
# • Lightweight (wijst naar commit)
# • Annotated (volledig object met metadata)
# Voorbeeld structuur:
Commit: abc123
├── Tree: def456
│ ├── Blob: 789abc (README.md)
│ ├── Tree: 123def (src/)
│ │ ├── Blob: 456ghi (main.py)
│ │ └── Blob: 789jkl (utils.py)
│ └── Blob: 012mno (requirements.txt)
└── Parent: xyz789
# Elke wijziging creëert nieuwe objecten
# Oude objecten blijven behouden (geschiedenis)
3. Installatie en Configuratie
Git Setup voor Verschillende Platforms
Start met Git door het correct te installeren en configureren voor jouw ontwikkelomgeving.
Installatie Commando's
# ========== INSTALLATIE ==========
# Ubuntu/Debian
sudo apt update
sudo apt install git
# macOS met Homebrew
brew install git
# Windows (download van git-scm.com)
# Of gebruik Chocolatey:
choco install git
# ========== CONFIGURATIE ==========
# Globale configuratie (één keer per machine)
git config --global user.name "Jouw Naam"
git config --global user.email "jouw.email@voorbeeld.com"
# Default editor instellen
git config --global core.editor "code --wait" # VS Code
# Alternatieven:
# git config --global core.editor "vim"
# git config --global core.editor "nano"
# Kleur output inschakelen
git config --global color.ui auto
# Default branch naam (moderne Git)
git config --global init.defaultBranch main
# ========== HANDIGE ALIASES ==========
# Korte aliases voor vaak gebruikte commando's
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
git config --global alias.unstage "reset HEAD --"
# Visuele log
git config --global alias.lg "log --oneline --graph --decorate --all"
# ========== CONFIGURATIE BEKIJKEN ==========
# Alle configuratie zien
git config --list
# Specifieke configuratie
git config user.name
git config user.email
# Configuratie bestanden locatie
# Global: ~/.gitconfig of ~/.config/git/config
# Local: .git/config in project
# System: /etc/gitconfig
# ========== SSH KEY SETUP ==========
# Genereer SSH key (als je die nog niet hebt)
ssh-keygen -t ed25519 -C "jouw.email@voorbeeld.com"
# Toon publieke key (kopieer naar GitHub/GitLab)
cat ~/.ssh/id_ed25519.pub
# Test SSH verbinding
ssh -T git@github.com
Git Configuration Bestand
# ~/.gitconfig (Global Configuration)
[user]
name = Jouw Naam
email = jouw.email@voorbeeld.com
[core]
editor = code --wait
autocrlf = input # Voor Linux/macOS
# autocrlf = true # Voor Windows
excludesfile = ~/.gitignore_global
[alias]
co = checkout
br = branch
ci = commit
st = status
unstage = reset HEAD --
last = log -1 HEAD
lg = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
[pull]
rebase = false # Of true voor rebase strategy
[push]
default = current
[init]
defaultBranch = main
[credential]
helper = store # Of cache, osxkeychain, wincred
# Platform-specifieke configuratie
# macOS:
[credential]
helper = osxkeychain
# Windows:
[credential "wincred"]
helper = wincred
# Linux:
[credential]
helper = cache --timeout=3600 # Cache credentials voor 1 uur
# Global .gitignore bestand
# ~/.gitignore_global
.DS_Store
*.log
*.tmp
*.swp
.vscode/
.idea/
node_modules/
__pycache__/
*.pyc
.env
.env.local
Git Expert nodig voor je team?
Vind ervaren Developers en DevOps Engineers gespecialiseerd in Git workflows
4. Basis Git Commando's
Dagelijkse Git Commando's
Deze commando's vormen de basis van je dagelijkse Git workflow.
Repository Initialisatie en Cloning
# ========== REPOSITORY CREATIE ==========
# Nieuw lokaal repository initialiseren
git init
# Creëert .git folder met alle Git metadata
# Repository clonen van remote server
git clone https://github.com/gebruiker/repository.git
# Of met SSH:
git clone git@github.com:gebruiker/repository.git
# Clonen in specifieke map
git clone https://github.com/gebruiker/repository.git mijn-project
# Alleen specifieke branch clonen
git clone --branch develop --single-branch https://github.com/gebruiker/repository.git
# ========== STATUS EN LOGS ==========
# Bekijk status van working directory
git status
git status --short # Compacte weergave
# Bekijk commit geschiedenis
git log
git log --oneline # Één regel per commit
git log --graph --oneline --decorate --all # Visuele weergave
git log --since="2024-01-01" --until="2024-12-31"
git log --author="JouwNaam"
git log --grep="bugfix" # Zoek in commit messages
# ========== WIJZIGINGEN TRACKEN ==========
# Voeg specifiek bestand toe aan staging
git add bestand.py
git add src/ # Voeg hele directory toe
# Voeg alle wijzigingen toe
git add .
git add --all # Inclusief verwijderde bestanden
# Interactive staging
git add -p # Stapsgewijs wijzigingen toevoegen
# Verwijder bestand uit staging (niet uit working directory)
git reset bestand.py
# Wijzigingen zien (unstaged)
git diff
# Wijzigingen zien (staged)
git diff --staged
# Verschil tussen branches
git diff main..feature-branch
# ========== COMMITS ==========
# Commit staged wijzigingen
git commit -m "Korte beschrijving van wijzigingen"
# Commit met uitgebreid bericht (opent editor)
git commit
# Voeg alle tracked wijzigingen toe en commit
git commit -a -m "Commit alle wijzigingen"
# Wijzig laatste commit (als nog niet gepushed)
git commit --amend
# Amend met nieuw bericht
git commit --amend -m "Nieuw commit bericht"
# ========== BRANCHES ==========
# Lijst van branches
git branch # Lokale branches
git branch -a # Alle branches (inclusief remote)
git branch -r # Alleen remote branches
# Nieuwe branch maken
git branch nieuwe-feature
# Branch maken en er direct naartoe switchen
git checkout -b nieuwe-feature
# Moderne syntax (Git 2.23+)
git switch -c nieuwe-feature
# Naar branch switchen
git checkout main
git switch main # Moderne syntax
# Branch verwijderen
git branch -d oude-branch # Veilige delete
git branch -D oude-branch # Geforceerde delete
# ========== REMOTE REPOSITORIES ==========
# Remote repositories bekijken
git remote -v
# Remote repository toevoegen
git remote add origin https://github.com/gebruiker/repo.git
# Wijzigingen ophalen van remote
git fetch origin # Haalt op maar merge niet
git fetch --all # Haalt van alle remotes
# Wijzigingen ophalen en mergen
git pull origin main
# Pull met rebase:
git pull --rebase origin main
# Wijzigingen pushen naar remote
git push origin main
# Push nieuwe branch:
git push -u origin nieuwe-branch # -u stelt upstream in
# Alle branches pushen:
git push --all origin
# Tags pushen:
git push --tags
Praktische Voorbeelden
# ========== TYPISCHE WORKFLOW ==========
# Scenario: Nieuwe feature ontwikkelen
# 1. Update lokale main branch
git checkout main
git pull origin main
# 2. Nieuwe feature branch maken
git checkout -b feature/user-authentication
# 3. Wijzigingen maken...
# - Bestanden bewerken
# - Nieuwe bestanden toevoegen
# 4. Wijzigingen stage en commit
git add .
git commit -m "Implement user authentication"
# 5. Meer wijzigingen...
git add .
git commit -m "Add password reset functionality"
# 6. Wijzigingen naar remote pushen
git push -u origin feature/user-authentication
# 7. Pull request maken op GitHub/GitLab
# 8. Code review ontvangen
# 9. Wijzigingen aanbrengen na review
git add .
git commit -m "Fix review comments"
# 10. Updates pushen
git push origin feature/user-authentication
# 11. Na merge, branch opruimen
git checkout main
git pull origin main
git branch -d feature/user-authentication
# ========== ONDERHOUD TAAK ==========
# Verouderde remote branches opruimen
git fetch --prune
# Ongepubliceerde branches vinden
git branch -vv | grep ': gone]' | awk '{print $1}' | xargs git branch -d
# Wijzigingen stashen (tijdelijk opslaan)
git stash # Wijzigingen opslaan
git stash list # Lijst van stashes
git stash pop # Laatste stash toepassen en verwijderen
git stash apply # Toepassen maar niet verwijderen
git stash drop # Verwijderen
# Wijzigingen ongedaan maken
# Laatste commit ongedaan maken (nieuwe commit)
git revert HEAD
# Wijzigingen in working directory ongedaan maken
git checkout -- bestand.py # Voor specifiek bestand
git restore bestand.py # Moderne syntax
# ========== TAGGEN ==========
# Lightweight tag
git tag v1.0.0
# Annotated tag (met bericht)
git tag -a v1.0.0 -m "Release version 1.0.0"
# Tag naar remote pushen
git push origin v1.0.0
# Alle tags pushen:
git push origin --tags
5. Branching Strategieën
Populaire Branching Modellen
Kies de juiste branching strategie voor jouw team en project omgeving.
Git Flow
# ========== GIT FLOW STRATEGIE ==========
# Geschikt voor: Grote teams, regelmatige releases, enterprise projecten
# BRANCH STRUCTUUR:
# main - Productie code (alleen release commits)
# develop - Integratie branch voor volgende release
# feature/* - Nieuwe features
# release/* - Release voorbereiding
# hotfix/* - Kritieke fixes voor productie
# WORKFLOW:
# 1. Feature ontwikkeling
git checkout develop
git checkout -b feature/user-dashboard
# ... werk aan feature ...
git add .
git commit -m "Add user dashboard components"
git push origin feature/user-dashboard
# 2. Feature terug naar develop
git checkout develop
git merge --no-ff feature/user-dashboard
# --no-ff behoudt feature branch geschiedenis
git branch -d feature/user-dashboard
# 3. Release voorbereiden
git checkout develop
git checkout -b release/1.2.0
# ... bug fixes, version bump, docs ...
git commit -m "Bump version to 1.2.0"
# 4. Release naar main en develop
git checkout main
git merge --no-ff release/1.2.0
git tag -a v1.2.0 -m "Release 1.2.0"
git checkout develop
git merge --no-ff release/1.2.0
git branch -d release/1.2.0
# 5. Hotfix voor productie
git checkout main
git checkout -b hotfix/critical-bug
# ... fix implementeren ...
git add .
git commit -m "Fix critical security bug"
# 6. Hotfix terug naar main en develop
git checkout main
git merge --no-ff hotfix/critical-bug
git tag -a v1.2.1 -m "Hotfix 1.2.1"
git checkout develop
git merge --no-ff hotfix/critical-bug
git branch -d hotfix/critical-bug
# VOORDELEN:
# • Duidelijke structuur
# • Goed voor geplande releases
# • Parallelle ontwikkeling mogelijk
# NADELEN:
# • Complex voor kleine teams
# • Veel branches te onderhouden
GitHub Flow
# ========== GITHUB FLOW STRATEGIE ==========
# Geschikt voor: Continuous deployment, web applicaties, kleine teams
# BRANCH STRUCTUUR:
# main - Altijd deployable
# feature/* - Elke feature in aparte branch
# WORKFLOW:
# 1. Feature branch van main
git checkout main
git pull origin main # Zorg dat je up-to-date bent
git checkout -b add-search-feature
# 2. Regelmatige commits
git add .
git commit -m "Add search API endpoint"
git push origin add-search-feature
# 3. Pull request maken zodra feature klaar is
# • Ga naar GitHub/GitLab
# • Create Pull Request
# • Request review van teamgenoten
# 4. Code review en discussie
# • Reviewers geven feedback
# • Wijzigingen aanbrengen
# • Updates pushen naarzelfde branch
git add .
git commit -m "Fix search results pagination"
git push origin add-search-feature
# 5. Merge na approved review
# • Klik "Merge pull request"
# • Delete branch optie
# 6. Direct deployen (CI/CD)
# • Automatische deployment na merge
# • Monitoring en rollback indien nodig
# EXTRA'S VOOR GITHUB FLOW:
# Protected branches
# • main branch beschermen
# • Require pull request reviews
# • Require status checks
# Issue linking
# Commit messages: "Add search feature #123"
# Auto-closes issue bij merge
# VOORDELEN:
# • Eenvoudig en snel
# • Goed voor continuous deployment
# • Minder overhead dan Git Flow
# NADELEN:
# • Minder geschikt voor lange release cycles
# • Geen formal release process
Trunk-Based Development
# ========== TRUNK-BASED DEVELOPMENT ==========
# Geschikt voor: High-performance teams, monorepos, CI/CD pipelines
# PRINCIPE: Allen werken op main (trunk)
# Korte-lived branches (< 1-2 dagen)
# Feature flags voor onafgemaakt werk
# WORKFLOW:
# 1. Kleine, incrementele changes
git checkout main
git pull --rebase origin main
# 2. Korte feature branch (optioneel)
git checkout -b add-login-validation
# ... klein stukje werk ...
git add .
git commit -m "Add email validation for login"
# 3. Snel terug naar main
git checkout main
git pull --rebase origin main
git merge --squash add-login-validation
git commit -m "Add email validation for login"
git push origin main
git branch -d add-login-validation
# ALTERNATIEF: Direct op main (met feature flags)
# 1. Feature flag toevoegen
git checkout main
git pull --rebase origin main
git add .
git commit -m "Add new dashboard behind feature flag"
# 2. Feature flag configureren
# config.py:
# NEW_DASHBOARD_ENABLED = os.getenv('NEW_DASHBOARD', 'false') == 'true'
# 3. Incrementeel feature bouwen
# Elke commit werkt en is deployable
# 4. Feature flag verwijderen als feature compleet is
git add .
git commit -m "Remove feature flag for new dashboard"
# CI/CD PIPELINE:
# • Automatische tests op elke commit
# • Automatische deployment naar staging
# • Canary releases / progressive rollout
# BEST PRACTICES:
# 1. Keep commits small
# • Één logische wijziging per commit
# • Commit messages: "Wat en waarom"
# 2. Continuous integration
# • Testen op elke commit
# • Snelle feedback loop
# 3. Feature flags
# • Onafgemaakt werk verbergen
# • A/B testing mogelijkheden
# VOORDELEN:
# • Minimale merge conflicts
# • Snelle feedback cycles
# • Eenvoudige rollback
# NADELEN:
# • Discipline vereist
# • Complexe feature flags management
# • Minder geschikt voor open source
6. Merging vs Rebasing
De Grote Discussie
Wanneer gebruik je merge en wanneer rebase? Beide hebben hun voor- en nadelen.
Git Merge
- Doel: Combineer branches via nieuwe merge commit
- Geschiedenis: Behoudt volledige branch historie
- Complexiteit: Eenvoudig, minder foutgevoelig
- Gebruik: Wanneer branch historie belangrijk is
Git Rebase
- Doel: Herschrijf commits op nieuwe base
- Geschiedenis: Lineaire, schonere historie
- Complexiteit: Complexer, kan conflicten veroorzaken
- Gebruik: Voor lokale branches, voor publicatie opruimen
Praktische Voorbeelden
# ========== MERGE VOORBEELD ==========
# Situatie: Feature branch die moet worden gemerged in main
# Start situatie:
# main: A -- B -- C
# feature: A -- B -- D -- E
# 1. Switchen naar main en updaten
git checkout main
git pull origin main
# 2. Feature branch mergen
git merge feature-branch
# Resultaat: A -- B -- C -- F (merge commit)
# \ /
# D -- E
# 3. Push naar remote
git push origin main
# Merge opties:
git merge --no-ff feature-branch # Altijd merge commit
git merge --squash feature-branch # Alle commits in één
# ========== REBASE VOORBEELD ==========
# Situatie: Feature branch updaten met recente main wijzigingen
# Start situatie:
# main: A -- B -- C
# feature: A -- B -- D -- E
# 1. Naar feature branch gaan
git checkout feature-branch
# 2. Rebase op main
git rebase main
# Stappen:
# 1. Feature branch wordt tijdelijk verwijderd
# 2. Commits D en E worden opnieuw toegepast op C
# 3. Nieuwe commits D' en E' worden gemaakt
# Resultaat: A -- B -- C -- D' -- E'
# Lineaire geschiedenis
# 3. Force push (als al gepushed was)
git push origin feature-branch --force-with-lease
# ========== INTERACTIVE REBASE ==========
# Krachtig tool voor commit geschiedenis bewerken
# Laatste 3 commits bewerken
git rebase -i HEAD~3
# Editor opent met:
pick d123456 Add user model
pick a789abc Add authentication
pick b456def Fix typo in readme
# Mogelijke acties:
# pick - Behoud commit
# reword - Wijzig commit message
# edit - Stop voor wijzigingen
# squash - Combineer met vorige commit
# fixup - Combineer en verwerp message
# drop - Verwijder commit
# Voorbeeld: Commits samenvoegen
pick d123456 Add user model
squash a789abc Add authentication
pick b456def Fix typo in readme
# ========== GOLDEN RULES ==========
# WEL rebasen:
# • Lokale branches die nog niet gepushed zijn
# • Private feature branches
# • Voor pull requests (schone geschiedenis)
# NIET rebasen:
# • Public branches (main, develop)
# • Branches waar anderen op werken
# • Als je niet zeker weet wat je doet
# ========== COMMON SCENARIOS ==========
# Scenario 1: Feature branch updaten
git checkout feature-branch
git fetch origin
git rebase origin/main
# Scenario 2: Commits reorganiseren voor PR
git rebase -i HEAD~5 # Laatste 5 commits
# Squash kleine commits, reword messages
# Scenario 3: Merge conflict tijdens rebase
# 1. Conflict oplossen in bestanden
# 2. git add .
# 3. git rebase --continue
# 4. Of abort: git rebase --abort
# Scenario 4: Verkeerde branch gemerged
# 1. Zoek de merge commit: git log --oneline --graph
# 2. Revert de merge: git revert -m 1 MERGE_COMMIT_HASH
7. GitHub en GitLab Workflows
Cloud-based Git Hosting
Platforms zoals GitHub en GitLab bieden krachtige features bovenop standaard Git.
Pull Request Workflow
# ========== COMPLETE PULL REQUEST WORKFLOW ==========
# STAP 1: Repository voorbereiden
# Fork repository (voor open source contributie)
# Of clone team repository
git clone https://github.com/team/project.git
cd project
# STAP 2: Feature branch maken
git checkout main
git pull origin main
git checkout -b feature/new-api-endpoint
# STAP 3: Wijzigingen maken en committen
# ... code schrijven ...
git add .
git commit -m "Add new API endpoint for user data"
# STAP 4: Push naar remote
git push -u origin feature/new-api-endpoint
# STAP 5: Pull Request maken op GitHub
# • Ga naar repository op GitHub
# • Klik "Compare & pull request"
# • Vul template:
## Beschrijving
# Voegt nieuwe API endpoint toe voor user data retrieval
## Type wijziging
# - [ ] Bug fix
# - [x] Nieuwe feature
# - [ ] Breaking change
# - [ ] Documentatie update
## Checklist
# - [x] Mijn code volgt de style guidelines
# - [x] Ik heb zelf mijn code gereviewed
# - [x] Ik heb comments toegevoegd waar nodig
# - [x] Ik heb tests toegevoegd
# - [ ] Alle tests slagen
## Gerelateerde issues
# Fixes #123
# STAP 6: Code Review Proces
# Reviewers kunnen:
# • Comments toevoegen op specifieke regels
# • Request changes
# • Approven
# Als wijzigingen nodig zijn:
git add .
git commit -m "Address review comments"
git push origin feature/new-api-endpoint
# PR update automatisch
# STAP 7: Continuous Integration Checks
# GitHub Actions / GitLab CI voeren automatisch uit:
# • Unit tests
# • Linting
# • Build checks
# • Security scans
# STAP 8: Merge Strategieën
# Optie 1: Create a merge commit
# • Behoudt complete historie
# • Merge commit met alle PR commits
# Optie 2: Squash and merge
# • Alle PR commits in één commit
# • Schone main branch historie
# • Verliest individuele commit historie
# Optie 3: Rebase and merge
# • Lineaire historie
# • Behoudt individuele commits
# • Kan conflicten veroorzaken
# STAP 9: Post-Merge Cleanup
# • Branch automatisch verwijderen (optie)
# • Issue automatisch sluiten
# • Deployment triggeren
# ========== GITLAB MERGE REQUEST FEATURES ==========
# 1. Merge Request Templates
# .gitlab/merge_request_templates/default.md
## Wat verandert er?
<!-- Beschrijf de wijzigingen -->
## Waarom is dit nodig?
<!-- Leg de business case uit -->
## Screenshots
<!-- Voeg screenshots toe indien relevant -->
## Test instructies
1.
2.
3.
# 2. Review Apps
# Automatische staging omgeving per MR
# .gitlab-ci.yml:
review:
stage: deploy
script:
- deploy-review.sh
environment:
name: review/$CI_COMMIT_REF_NAME
url: https://$CI_ENVIRONMENT_SLUG.example.com
only:
- merge_requests
# 3. Approvers
# • Vereiste approvers configureren
# • Code owner reviews
# 4. Fast-forward merges only
# Project instelling: "Merge method: Fast-forward merge"
# Vereist rebase voor merging
8. Geavanceerde Git Technieken
Voor Gevorderde Gebruikers
Deze technieken maken je Git workflow efficiënter en krachtiger.
Git Hooks
# ========== GIT HOOKS ==========
# Automatische scripts die worden uitgevoerd bij Git events
# Locatie: .git/hooks/
# Client-side hooks (lokaal)
# Server-side hooks (op remote server)
# BELANGRIJKE HOOKS:
# pre-commit - Voordat commit wordt gemaakt
# • Linting
# • Format checking
# • Testen
# prepare-commit-msg - Na commit message wordt gemaakt
# • Auto-issue linking
# • Template toevoegen
# commit-msg - Commit message validatie
# • Convention check (Conventional Commits)
# • Min/max length check
# pre-push - Voordat naar remote gepushed wordt
# • Integration tests
# • Build check
# post-merge - Na merge of pull
# • Dependency install
# • Cache cleanup
# VOORBEELD: pre-commit hook
# .git/hooks/pre-commit (maak uitvoerbaar: chmod +x)
#!/bin/bash
echo "Running pre-commit checks..."
# Run linter
if ! flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics; then
echo "❌ Flake8 found errors"
exit 1
fi
# Run tests
if ! python -m pytest tests/ -v; then
echo "❌ Tests failed"
exit 1
fi
# Check for debug statements
if grep -r "console.log" src/; then
echo "❌ Found console.log statements"
exit 1
fi
echo "✅ All checks passed!"
exit 0
# VOORBEELD: commit-msg hook voor Conventional Commits
#!/bin/bash
commit_msg_file=$1
commit_msg=$(cat "$commit_msg_file")
# Pattern: type(scope): description
pattern="^(feat|fix|docs|style|refactor|test|chore|perf|build|ci)(\([a-z]+\))?: .+"
if ! [[ $commit_msg =~ $pattern ]]; then
echo "❌ Invalid commit message format"
echo "✅ Use: type(scope): description"
echo "✅ Types: feat, fix, docs, style, refactor, test, chore, perf, build, ci"
exit 1
fi
# TOOLS VOOR HOOK MANAGEMENT:
# 1. pre-commit framework
# pip install pre-commit
# .pre-commit-config.yaml:
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- repo: https://github.com/psf/black
rev: 23.1.0
hooks:
- id: black
# 2. husky (voor Node.js projecten)
# npm install husky --save-dev
# package.json:
{
"husky": {
"hooks": {
"pre-commit": "npm test",
"commit-msg": "commitlint -E HUSKY_GIT_PARAMS"
}
}
}
# 3. lefthook (multi-language)
# brew install lefthook
# lefthook.yml:
pre-commit:
parallel: true
commands:
lint:
run: npm run lint
test:
run: npm test
Git Bisect en Debugging
# ========== GIT BISECT ==========
# Binair zoeken naar bug-introducerende commit
# Situatie: Bug gevonden in huidige code
# Wil weten welke commit de bug introduceerde
# STAP 1: Bisect starten
git bisect start
# STAP 2: Markeer huidige commit als "bad"
git bisect bad HEAD
# STAP 3: Markeer bekende goede commit als "good"
git bisect good v1.0.0
# Of specifieke commit hash
git bisect good abc123def
# STAP 4: Git checkt automatisch een commit
# Test of bug aanwezig is
# • Run tests
# • Manueel testen
# STAP 5: Markeer als good of bad
# Als bug aanwezig:
git bisect bad
# Als bug niet aanwezig:
git bisect good
# STAP 6: Herhaal tot buggy commit gevonden
# Git blijft halveren tot één commit overblijft
# STAP 7: Bisect beëindigen
git bisect reset
# AUTOMATISCH BISECT:
git bisect start HEAD v1.0.0
git bisect run npm test
# Of met custom script:
git bisect run ./test-bug.sh
# VOORBEELD SCRIPT: test-bug.sh
#!/bin/bash
# Return 0 if good, 1-125 if bad, 126-127 to skip
# Run specific test
if python -m pytest tests/test_bug.py::test_specific_case; then
exit 0 # good
else
exit 1 # bad
fi
# ========== GIT BLAME ==========
# Zie wie welke regels heeft gewijzigd
# Basic blame
git blame bestand.py
# Blame met commit hash en date
git blame -l bestand.py
# Blame specifieke regels
git blame -L 10,20 bestand.py
# Blame oudere versie
git blame v1.0.0 -- bestand.py
# GUI blame (VS Code)
# • Open bestand
# • Ctrl+Shift+P → "Git: Blame"
# ========== GIT GREP ==========
# Zoeken in codebase over tijd
# Zoeken in huidige code
git grep "functionName"
# Zoeken in specifieke commit
git grep "functionName" v1.0.0
# Zoeken in hele historie
git log -p --all -S "functionName"
# ========== RELEASE MANAGEMENT ==========
# Semantic Versioning tags
git tag v1.0.0 # Major release
git tag v1.1.0 # Minor feature release
git tag v1.1.1 # Patch bugfix release
# Generate changelog from tags
git log --oneline v1.0.0..v1.1.0
# Create signed tags
git tag -s v1.0.0 -m "Release 1.0.0"
# Verify signed tag
git tag -v v1.0.0
Git Expert nodig voor CI/CD Pipeline?
Vind ervaren DevOps Engineers gespecialiseerd in Git workflows en automation
9. Git Best Practices
Essentiële Richtlijnen
Volg deze best practices voor effectief en professioneel Git gebruik.
Commit Messages
- Gebruik Conventional Commits
- Eerste regel max 50 karakters
- Beschrijf "wat" en "waarom"
- Referentie issue/ticket nummers
Branch Management
- Korte-lived branches (< 1 week)
- Duidelijke naming: feature/, fix/, hotfix/
- Verwijder branches na merge
- Regular prune van remote branches
Workflow
- Commit vaak, push regelmatig
- Pull met rebase voor clean history
- Resolve conflicts vroeg
- Use .gitignore voor build artifacts
Team Collaboration
- Code reviews voor alle wijzigingen
- Pair programming voor complexe changes
- Documenteer branching strategie
- Train nieuwe teamleden
Praktische Tips
# TIP 1: Atomic Commits
# Elke commit moet één logische wijziging bevatten
# ❌ SLECHT:
git commit -m "Added user auth and fixed navbar and updated README"
# ✅ GOED:
git commit -m "feat(auth): add user authentication"
git commit -m "fix(ui): correct navbar alignment"
git commit -m "docs: update installation instructions"
# TIP 2: Interactive Staging
# Selecteer specifieke wijzigingen voor commit
git add -p
# • y - stage deze hunk
# • n - skip deze hunk
# • s - split in kleinere hunks
# • e - edit handmatig
# TIP 3: Stash Strategie
# Gebruik stash voor tijdelijke wijzigingen
git stash save "WIP: user profile feature"
git stash list
git stash pop stash@{0}
# TIP 4: .gitignore Best Practices
# Project-specifiek .gitignore
# Global .gitignore voor editor files
# .gitignore voorbeeld:
# Dependencies
node_modules/
vendor/
__pycache__/
# Build outputs
dist/
build/
*.class
*.jar
# Environment
.env
.env.local
# IDE
.vscode/
.idea/
*.swp
*.swo
# OS
.DS_Store
Thumbs.db
# TIP 5: Regular Maintenance
# Wekelijks:
git gc --auto # Garbage collection
git prune # Verwijder dangling objects
git remote prune origin # Verwijder remote tracking branches
# TIP 6: Security
# Nooit credentials committen
# Gebruik environment variables
# Scan voor secrets met gitleaks
10. Git in DevOps Pipelines
Continuous Integration en Deployment
Git is de kern van moderne CI/CD pipelines en DevOps workflows.
GitOps Workflow
# ========== GITOPS PRINCIPLES ==========
# Infrastructure as Code via Git
# Git als single source of truth
# REPOSITORY STRUCTUUR:
# infrastructure/
# ├── kubernetes/
# │ ├── production/
# │ │ ├── deployment.yaml
# │ │ └── service.yaml
# │ └── staging/
# │ └── ...
# ├── terraform/
# │ └── main.tf
# └── ansible/
# └── playbooks/
# application/
# ├── src/
# └── Dockerfile
# .github/workflows/
# └── ci-cd.yaml
# GITHUB ACTIONS WORKFLOW:
# .github/workflows/ci-cd.yml
name: CI/CD Pipeline
on:
push:
branches: [ main, develop ]
pull_request:
branches: [ main ]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0 # Haal complete geschiedenis voor Git commands
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '18'
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
- name: Run linting
run: npm run lint
build:
needs: test
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Build Docker image
run: docker build -t myapp:${{ github.sha }} .
- name: Push to registry
run: |
echo "${{ secrets.DOCKER_PASSWORD }}" | docker login -u "${{ secrets.DOCKER_USERNAME }}" --password-stdin
docker push myapp:${{ github.sha }}
deploy-staging:
needs: build
if: github.ref == 'refs/heads/develop'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Deploy to staging
run: |
kubectl apply -f infrastructure/kubernetes/staging/
kubectl rollout status deployment/myapp-staging
deploy-production:
needs: build
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Check commit message for release
id: check_commit
run: |
if [[ "${{ github.event.head_commit.message }}" =~ ^release: ]]; then
echo "is_release=true" >> $GITHUB_OUTPUT
else
echo "is_release=false" >> $GITHUB_OUTPUT
fi
- name: Deploy to production
if: steps.check_commit.outputs.is_release == 'true'
run: |
kubectl apply -f infrastructure/kubernetes/production/
kubectl rollout status deployment/myapp-production
- name: Create Git tag
if: steps.check_commit.outputs.is_release == 'true'
run: |
git config user.name "GitHub Actions"
git config user.email "actions@github.com"
git tag -a v1.0.${{ github.run_number }} -m "Release ${{ github.run_number }}"
git push origin --tags
# ========== VERSIONING STRATEGY ==========
# Semantic Versioning via Git tags
git tag -a v1.2.3 -m "Release v1.2.3"
# Automatic version bump via commits
# conventional-commits + semantic-release
# package.json:
{
"scripts": {
"release": "semantic-release"
}
}
# .releaserc.json:
{
"branches": ["main"],
"plugins": [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release/github",
"@semantic-release/git"
]
}
# Commit types trigger version bumps:
# • feat: → minor version (1.2.0)
# • fix: → patch version (1.2.1)
# • BREAKING CHANGE: → major version (2.0.0)
11. Tools en Extensies
Essentiële Git Tools
Verbeter je Git workflow met deze tools en extensies.
GUI Clients
- GitHub Desktop: Eenvoudig, GitHub geïntegreerd
- GitKraken: Krachtig, cross-platform
- Sourcetree: Atlassian product, gratis
- Tower: Premium, macOS
CLI Tools
- tig: Text-mode interface voor Git
- lazygit
- diff-so-fancy: Betere git diff output
- delta: Syntax highlighting voor diffs
Editor Integratie
- VS Code GitLens: Krachtige Git features
- Git Graph: Visuele branch weergave
- Git History: Commit historie browser
- Git Blame: Inline blame annotaties
Security Tools
- gitleaks: Detecteer secrets in repo
- truffleHog: Zoek credentials in Git historie
- git-secrets: AWS secrets prevention
- pre-commit: Pre-commit hooks framework
Essentiële VS Code Extensies
# VS Code settings.json voor Git
{
"git.enableSmartCommit": true,
"git.confirmSync": false,
"git.autofetch": true,
"git.fetchOnPull": true,
"git.postCommitCommand": "sync",
// GitLens settings
"gitlens.currentLine.enabled": false,
"gitlens.hovers.currentLine.over": "line",
"gitlens.codeLens.enabled": false,
// Git Graph
"git-graph.repository.commits.showSignatureStatus": true,
// Integrated terminal Git aliases
"terminal.integrated.shellArgs.linux": [
"--init-file",
"${workspaceFolder}/.vscode/git-aliases.sh"
]
}
# .vscode/git-aliases.sh
alias gs="git status"
alias ga="git add"
alias gc="git commit"
alias gcm="git commit -m"
alias gco="git checkout"
alias gb="git branch"
alias gl="git log --oneline --graph --decorate --all"
alias gp="git pull"
alias gpush="git push"
alias gd="git diff"
alias gdc="git diff --cached"
Conclusie
Git is meer dan alleen een versiebeheersysteem - het is een essentieel tool voor moderne software ontwikkeling en team collaboration. Door Git effectief te gebruiken, kun je code kwaliteit verbeteren, development snelheid verhogen, en betere samenwerking bereiken binnen je team.
Key Takeaways:
- Begrijp de drie gebieden: Working Directory, Staging Area, Repository
- Kies de juiste branching strategie voor jouw team en project
- Gebruik pull requests voor code reviews en kwaliteitscontrole
- Implementeer Git hooks voor automatische kwaliteitschecks
- Integreer Git in je CI/CD pipeline voor automatische deployments
Klaar om je Git skills toe te passen?
Vind development vacatures of plaats je eigen vacature voor €25