14 min de lecture · 2 934 mots

Git & GitHub : Commandes essentielles

Configuration initiale

Configuration utilisateur

# Configuration globale (tous les repos)
git config --global user.name "Votre Nom"
git config --global user.email "votre.email@example.com"

# Configuration locale (repo spécifique)
git config user.name "Nom Projet"
git config user.email "email.projet@example.com"

# Éditeur par défaut
git config --global core.editor "nano"
git config --global core.editor "vim"
git config --global core.editor "code --wait"  # VS Code

# Alias utiles
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.lg "log --oneline --graph --all"
git config --global alias.last "log -1 HEAD"
git config --global alias.unstage "reset HEAD --"

# Voir configuration
git config --list
git config --global --list
git config user.name

# Éditer configuration
git config --global --edit

# Couleurs
git config --global color.ui auto

# Comportement push
git config --global push.default simple

# Auto-correction
git config --global help.autocorrect 1

# Fin de ligne (Windows/Unix)
git config --global core.autocrlf true   # Windows
git config --global core.autocrlf input  # Mac/Linux

# Ignorer permissions
git config core.fileMode false

Initialisation et clonage

# Initialiser nouveau dépôt
git init
git init mon-projet
git init --bare  # Dépôt distant

# Cloner dépôt existant
git clone https://github.com/user/repo.git
git clone https://github.com/user/repo.git mon-dossier
git clone --depth 1 https://github.com/user/repo.git  # Clone superficiel (dernier commit)
git clone --branch develop https://github.com/user/repo.git  # Clone branche spécifique

# SSH
git clone git@github.com:user/repo.git

# Remote
git remote -v                           # Voir remotes
git remote add origin https://github.com/user/repo.git
git remote set-url origin git@github.com:user/repo.git
git remote rename origin upstream
git remote remove origin
git remote show origin                  # Infos détaillées

Workflow de base

Status et différences

# Status
git status
git status -s                          # Format court
git status --branch                    # Avec info branche

# Différences
git diff                               # Changements non stagés
git diff --staged                      # Changements stagés
git diff HEAD                          # Tous changements vs dernier commit
git diff fichier.txt                   # Différences fichier spécifique
git diff branche1 branche2            # Différences entre branches
git diff commit1 commit2              # Différences entre commits
git diff --stat                        # Statistiques
git diff --cached                      # Alias de --staged
git diff --color-words                 # Différences par mot

# Comparer avec commit précédent
git diff HEAD~1 HEAD
git diff HEAD^                         # Commit parent
git diff HEAD~3                        # 3 commits avant

Add (staging)

# Ajouter fichiers
git add fichier.txt
git add .js
git add .                              # Tous fichiers modifiés
git add -A                             # Tous fichiers (nouveaux, modifiés, supprimés)
git add -u                             # Fichiers suivis uniquement

# Ajout interactif
git add -p                             # Par chunk
git add -i                             # Mode interactif

# Annuler staging
git reset HEAD fichier.txt
git restore --staged fichier.txt       # Git 2.23+

Commit

# Commit simple
git commit -m "Message du commit"

# Commit avec description
git commit -m "Titre" -m "Description détaillée"

# Commit tous fichiers modifiés (skip staging)
git commit -am "Message"

# Ouvrir éditeur pour message
git commit

# Modifier dernier commit
git commit --amend
git commit --amend -m "Nouveau message"
git commit --amend --no-edit           # Garde message actuel

# Commit vide (utile pour CI)
git commit --allow-empty -m "Trigger build"

# Ajouter fichier au dernier commit
git add fichier-oublie.txt
git commit --amend --no-edit

# Bonnes pratiques messages
# Type: feat, fix, docs, style, refactor, test, chore
# Format: type(scope): message
git commit -m "feat(auth): add login functionality"
git commit -m "fix(api): resolve null pointer exception"
git commit -m "docs: update README with installation steps"

Log (historique)

# Historique basique
git log
git log -5                             # 5 derniers commits
git log --oneline                      # Format compact
git log --graph                        # Graphe branches
git log --all                          # Toutes branches
git log --oneline --graph --all        # Combiné

# Filtres
git log --author="Jean"
git log --since="2024-01-01"
git log --until="2024-12-31"
git log --since="2 weeks ago"
git log --after="2024-01-01" --before="2024-06-01"
git log --grep="fix"                   # Recherche dans messages

# Par fichier
git log fichier.txt
git log -p fichier.txt                 # Avec différences
git log --follow fichier.txt           # Suit renommages

# Formats personnalisés
git log --pretty=format:"%h - %an, %ar : %s"
git log --pretty=format:"%h %s" --graph
git log --pretty=format:"%C(yellow)%h%Creset %C(blue)%ad%Creset | %s %C(green)(%an)%Creset" --date=short

# Statistiques
git log --stat                         # Fichiers modifiés
git log --shortstat
git log --name-only                    # Noms fichiers uniquement
git log --name-status                  # Noms + status (A/M/D)

# Recherche dans code
git log -S "fonction"                  # Commits ajoutant/supprimant "fonction"
git log -G "regex"                     # Recherche regex

# Commits d'un fichier
git blame fichier.txt                  # Qui a modifié chaque ligne
git blame -L 10,20 fichier.txt        # Lignes 10 à 20

# Références
git show HEAD                          # Dernier commit
git show HEAD~2                        # 2 commits avant
git show abc123                        # Commit spécifique
git show v1.0                          # Tag

Branches

Gestion des branches

# Lister branches
git branch                             # Branches locales
git branch -r                          # Branches distantes
git branch -a                          # Toutes branches
git branch -v                          # Avec dernier commit
git branch -vv                         # Avec tracking

# Créer branche
git branch nouvelle-branche
git branch nouvelle-branche abc123     # Depuis commit spécifique

# Changer de branche
git checkout nom-branche
git switch nom-branche                 # Git 2.23+

# Créer et changer
git checkout -b nouvelle-branche
git switch -c nouvelle-branche         # Git 2.23+

# Créer depuis distant
git checkout -b locale origin/distante

# Renommer branche
git branch -m ancien-nom nouveau-nom
git branch -m nouveau-nom              # Branche courante

# Supprimer branche
git branch -d nom-branche              # Si merged
git branch -D nom-branche              # Force

# Supprimer branche distante
git push origin --delete nom-branche
git push origin :nom-branche           # Syntaxe alternative

# Branche par défaut
git branch -u origin/main              # Set upstream
git branch --set-upstream-to=origin/main

# Comparer branches
git diff main..feature
git diff main...feature                # Depuis point de divergence
git log main..feature                  # Commits dans feature mais pas main

Merge (fusion)

# Merge branche dans branche courante
git merge nom-branche

# Merge avec message
git merge nom-branche -m "Message merge"

# Options de merge
git merge --no-ff nom-branche          # Force commit de merge
git merge --ff-only nom-branche        # Seulement si fast-forward possible
git merge --squash nom-branche         # Squash commits en 1

# Annuler merge en cours
git merge --abort

# Stratégies de merge
git merge -X ours nom-branche          # Préfère notre version en conflit
git merge -X theirs nom-branche        # Préfère leur version

# Voir si branche est merged
git branch --merged
git branch --no-merged

# Merge commit spécifique
git cherry-pick abc123
git cherry-pick abc123 def456          # Multiple
git cherry-pick abc123..def456         # Range

Rebase

# Rebase branche courante sur main
git rebase main

# Rebase interactif
git rebase -i HEAD~3                   # 3 derniers commits
git rebase -i abc123                   # Depuis commit

# Dans l'éditeur interactif:
# pick   = utiliser commit
# reword = utiliser commit mais éditer message
# edit   = utiliser commit mais s'arrêter pour amender
# squash = fusionner avec commit précédent
# fixup  = comme squash mais ignore message
# drop   = supprimer commit

# Continuer rebase
git rebase --continue

# Skipper commit
git rebase --skip

# Annuler rebase
git rebase --abort

# Rebase sur distant
git pull --rebase origin main

# Auto-stash pendant rebase
git rebase --autostash main

# Ne JAMAIS rebase des commits publics/poussés

Annuler et corriger

Reset

# Reset soft - garde changements en staging
git reset --soft HEAD~1

# Reset mixed (défaut) - garde changements non stagés
git reset HEAD~1
git reset --mixed HEAD~1

# Reset hard - supprime changements
git reset --hard HEAD~1
git reset --hard abc123

# Reset fichier spécifique
git reset HEAD fichier.txt

# Retour état distant
git reset --hard origin/main

Restore

# Restaurer fichier (Git 2.23+)
git restore fichier.txt                # Annule modifications
git restore --staged fichier.txt       # Unstage
git restore --source=HEAD~2 fichier.txt  # Depuis commit

# Restaurer tous fichiers
git restore .

Revert

# Créer commit inverse (sûr pour historique public)
git revert abc123
git revert HEAD
git revert HEAD~3

# Revert sans commit (staging)
git revert --no-commit abc123

# Revert merge
git revert -m 1 abc123                 # 1 = parent à garder

Checkout (anciennes versions)

# Checkout fichier depuis commit
git checkout abc123 -- fichier.txt

# Checkout commit entier (detached HEAD)
git checkout abc123

# Retour à branche
git checkout main

# Créer branche depuis commit
git checkout -b nouvelle-branche abc123

Clean

# Supprimer fichiers non suivis
git clean -n                           # Dry run (prévisualisation)
git clean -f                           # Force suppression
git clean -fd                          # Force + dossiers
git clean -fx                          # Force + fichiers ignorés
git clean -fxd                         # Tout nettoyer

# Interactif
git clean -i

Stash

# Sauvegarder changements temporaires
git stash
git stash save "Message descriptif"

# Avec fichiers non suivis
git stash -u
git stash --include-untracked

# Lister stash
git stash list

# Appliquer stash
git stash apply                        # Dernier stash (garde stash)
git stash apply stash@{2}             # Stash spécifique
git stash pop                          # Applique et supprime
git stash pop stash@{1}

# Voir contenu stash
git stash show
git stash show -p                      # Avec diff

# Supprimer stash
git stash drop stash@{1}
git stash clear                        # Tous stash

# Créer branche depuis stash
git stash branch nouvelle-branche stash@{1}

Remote et synchronisation

Push (envoyer)

# Push basique
git push origin main

# Push première fois (set upstream)
git push -u origin main
git push --set-upstream origin main

# Push toutes branches
git push --all origin

# Push tags
git push --tags
git push origin v1.0

# Force push (DANGER - écrase historique distant)
git push --force
git push --force-with-lease            # Plus sûr (vérifie updates)

# Supprimer branche distante
git push origin --delete nom-branche
git push origin :nom-branche

# Push branche locale vers nom différent distant
git push origin locale:distante

Pull (récupérer)

# Pull = fetch + merge
git pull origin main

# Pull avec rebase
git pull --rebase origin main

# Pull toutes branches
git pull --all

# Pull sans merge automatique
git fetch origin
git merge origin/main

# Stratégies pull
git pull --ff-only                     # Fast-forward seulement
git pull --no-ff                       # Force commit de merge

# Pull et nettoyer branches distantes supprimées
git pull --prune

Fetch

# Récupérer sans merger
git fetch origin
git fetch --all                        # Tous remotes

# Récupérer branche spécifique
git fetch origin main

# Nettoyer références
git fetch --prune                      # Supprime refs distantes supprimées

# Récupérer tags
git fetch --tags

Tags (étiquettes)

# Lister tags
git tag
git tag -l "v1."                      # Filtre

# Tag léger
git tag v1.0
git tag v1.0 abc123                    # Sur commit spécifique

# Tag annoté (recommandé)
git tag -a v1.0 -m "Version 1.0"
git tag -a v1.0 abc123 -m "Version 1.0"

# Voir tag
git show v1.0

# Supprimer tag local
git tag -d v1.0

# Supprimer tag distant
git push origin --delete v1.0
git push origin :refs/tags/v1.0

# Push tags
git push origin v1.0
git push --tags                        # Tous tags

# Checkout tag
git checkout v1.0                      # Detached HEAD
git checkout -b branche-v1.0 v1.0     # Créer branche depuis tag

Inspection et recherche

# Recherche dans code
git grep "fonction"
git grep -n "fonction"                 # Avec numéros lignes
git grep -c "fonction"                 # Compte occurrences
git grep "fonction" -- ".js"          # Dans fichiers spécifiques

# Voir contenu fichier ancien
git show abc123:chemin/fichier.txt

# Lister fichiers
git ls-files
git ls-files --others --ignored --exclude-standard  # Fichiers ignorés

# Informations commit
git show abc123
git show HEAD~2
git show HEAD:fichier.txt              # Fichier à un commit

# Différences avancées
git diff --word-diff
git diff --color-words
git diff --cached
git diff --check                       # Vérifie whitespace errors

# Voir qui a introduit bug (binaire search)
git bisect start
git bisect bad                         # Commit actuel est mauvais
git bisect good v1.0                   # Commit connu bon
# Git checkout commits, vous testez:
git bisect good    # Si OK
git bisect bad     # Si bugué
# Répéter jusqu'à trouver commit fautif
git bisect reset   # Fin

.gitignore

# Syntaxe .gitignore

# Fichiers spécifiques
fichier.txt
dossier/fichier.txt

# Tous fichiers d'un type
.log
.tmp

# Tous fichiers dans dossier
nodemodules/
dist/
build/

# Exception (ne pas ignorer)
!important.log

# Dossiers seulement
cache/

# Patterns
logs/.log
/temp
/.backup

# Commentaires
# Ceci est un commentaire

# Exemples pratiques:

# Node.js
nodemodules/
npm-debug.log
.env
.env.local
dist/
build/

# PHP
vendor/
composer.lock
.env

# WordPress
wp-config.php
wp-content/uploads/
wp-content/cache/

# IDE
.vscode/
.idea/
.swp
.swo
.DSStore

# Ignorer après ajout (déjà tracké)
git rm --cached fichier.txt
git rm -r --cached dossier/

Sous-modules

# Ajouter sous-module
git submodule add https://github.com/user/repo.git chemin/vers/submodule

# Cloner avec sous-modules
git clone --recursive https://github.com/user/repo.git

# Initialiser sous-modules après clone
git submodule init
git submodule update

# Mettre à jour sous-modules
git submodule update --remote

# Mettre à jour et initialiser
git submodule update --init --recursive

# Lister sous-modules
git submodule status

# Supprimer sous-module
git submodule deinit chemin/vers/submodule
git rm chemin/vers/submodule
rm -rf .git/modules/chemin/vers/submodule

Workflows GitHub

Fork et Pull Request

# 1. Fork sur GitHub (bouton web)

# 2. Cloner votre fork
git clone https://github.com/votre-user/repo.git
cd repo

# 3. Ajouter upstream (original)
git remote add upstream https://github.com/original-user/repo.git

# 4. Créer branche feature
git checkout -b ma-feature

# 5. Faire modifications et commits
git add .
git commit -m "feat: add new feature"

# 6. Push vers votre fork
git push origin ma-feature

# 7. Créer Pull Request sur GitHub (web)

# 8. Synchroniser avec upstream
git fetch upstream
git checkout main
git merge upstream/main
git push origin main

# Mettre à jour feature branch avec main
git checkout ma-feature
git rebase main
git push --force-with-lease origin ma-feature

Releases GitHub

# Créer tag pour release
git tag -a v1.0.0 -m "Release version 1.0.0"
git push origin v1.0.0

# Ou créer release directement sur GitHub (web)
# puis récupérer localement:
git fetch --tags

GitHub CLI (gh)

# Installer: https://cli.github.com/

# Login
gh auth login

# Créer repo
gh repo create mon-projet --public --source=. --remote=origin

# Cloner
gh repo clone user/repo

# Pull Request
gh pr create --title "Titre" --body "Description"
gh pr list
gh pr view 123
gh pr checkout 123
gh pr merge 123

# Issues
gh issue create --title "Bug" --body "Description"
gh issue list
gh issue view 456

# Releases
gh release create v1.0.0 --title "Version 1.0.0" --notes "Notes de version"

# Actions
gh workflow list
gh run list
gh run view 789

# Gists
gh gist create fichier.txt

Astuces et bonnes pratiques

Alias utiles

# Dans ~/.gitconfig ou git config --global

[alias]
    # Status et log
    st = status -sb
    lg = log --oneline --graph --all --decorate
    ll = log --pretty=format:'%C(yellow)%h%Creset %C(blue)%ad%Creset | %s %C(green)(%an)%Creset' --date=short
    last = log -1 HEAD --stat

    # Branches
    br = branch
    co = checkout
    cob = checkout -b
    sw = switch
    swc = switch -c

    # Commit
    ci = commit
    cam = commit -am
    amend = commit --amend --no-edit

    # Diff et merge
    df = diff
    dfs = diff --staged
    mt = mergetool

    # Remote
    pu = push
    puf = push --force-with-lease
    pl = pull
    plu = pull --rebase

    # Stash
    ss = stash save
    sp = stash pop
    sl = stash list

    # Undo
    undo = reset --soft HEAD~1
    unstage = reset HEAD --
    discard = checkout --

    # Alias complexes
    cleanup = "!git branch --merged | grep -v '' | xargs -n 1 git branch -d"
    contributors = shortlog -sn
    aliases = config --get-regexp alias

Commits conventionnels

# Format: (): 

# Types principaux:
feat:     # Nouvelle fonctionnalité
fix:      # Correction bug
docs:     # Documentation
style:    # Formatage, point-virgules manquants, etc
refactor: # Refactorisation code
perf:     # Amélioration performance
test:     # Ajout tests
chore:    # Maintenance, dépendances, etc
ci:       # Configuration CI/CD
build:    # Build system

# Exemples:
git commit -m "feat(auth): add OAuth2 login"
git commit -m "fix(api): resolve null pointer in user service"
git commit -m "docs: update installation instructions"
git commit -m "refactor(utils): simplify date formatting"
git commit -m "perf(db): add index on userid column"

# Breaking change:
git commit -m "feat(api)!: change response format"
git commit -m "feat(api): change response format

BREAKING CHANGE: API now returns data in new format"

Stratégies de branches

# Git Flow
main/master    # Production
develop        # Développement
feature/      # Nouvelles fonctionnalités
release/      # Préparation release
hotfix/       # Corrections urgentes

# GitHub Flow (plus simple)
main           # Production
feature/      # Tout le reste

# Trunk Based Development
main           # Tout le monde travaille ici
feature/*      # Courtes branches (max 2 jours)

Résolution conflits

# Quand conflit apparaît:

# 1. Voir fichiers en conflit
git status

# 2. Ouvrir fichiers et résoudre
# Chercher marqueurs:
# <<<<<<< HEAD
# Votre version
# =======
# Leur version
# >>>>>>> branch

# 3. Ajouter fichiers résolus
git add fichier-resolu.txt

# 4. Continuer merge/rebase
git merge --continue
# ou
git rebase --continue

# Outils de merge
git mergetool
git config --global merge.tool vimdiff
git config --global merge.tool meld

# Choisir version
git checkout --ours fichier.txt        # Notre version
git checkout --theirs fichier.txt      # Leur version

Performance

# Nettoyer et optimiser
git gc                                 # Garbage collection
git gc --aggressive --prune=now        # Nettoyage agressif

# Vérifier intégrité
git fsck

# Statistiques repo
git count-objects -vH

# Fichiers volumineux
git rev-list --objects --all | 
  git cat-file --batch-check='%(objecttype) %(objectname) %(objectsize) %(rest)' | 
  awk '/^blob/ {print substr($0,6)}' | 
  sort --numeric-sort --key=2 | 
  tail -10

# Shallow clone (pour économiser espace)
git clone --depth 1 https://github.com/user/repo.git

Sécurité

# Signer commits (GPG)
git config --global user.signingkey YOURGPGKEY
git config --global commit.gpgsign true
git commit -S -m "Signed commit"

# Vérifier signatures
git log --show-signature
git verify-commit abc123

# Credentials
git config --global credential.helper cache
git config --global credential.helper 'cache --timeout=3600'
git config --global credential.helper store  # ATTENTION: stocke en clair

# SSH
ssh-keygen -t ed25519 -C "votre.email@example.com"
eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519
# Ajouter clé publique sur GitHub

Dépannage

# Annuler dernier commit
git reset --soft HEAD~1

# Annuler push (DANGER)
git push --force-with-lease

# Récupérer commit perdu
git reflog
git checkout abc123

# Détacher HEAD
git switch -                           # Retour branche précédente
git switch main

# Corriger message commit
git commit --amend -m "Nouveau message"

# Changer auteur dernier commit
git commit --amend --author="Nom "

# Supprimer fichier de tous commits (DANGER)
git filter-branch --tree-filter 'rm -f fichier.txt' HEAD
# Ou avec BFG:
bfg --delete-files fichier.txt

# Récupérer branche supprimée
git reflog
git checkout -b branche-recuperee abc123

# Nettoyer historique
git rebase -i HEAD~10

# Problème de fin de ligne
git config core.autocrlf true         # Windows
git config core.autocrlf input        # Mac/Linux
git add --renormalize .

# Réparer repo corrompu
git fsck --full
git reflog expire --expire=now --all
git gc --prune=now --aggressive

Version: Git 2.43+ | Ressources: git-scm.com, docs.github.com

Une remarque, un retour ?

Cet article est vivant - corrections, contre-arguments et retours de production sont les bienvenus. Trois canaux, choisissez celui qui vous convient.

Laisser un commentaire