Skip to content

Instantly share code, notes, and snippets.

@Machou
Last active November 16, 2023 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Machou/ed35c7be23d6ffa448f5778d363ea33a to your computer and use it in GitHub Desktop.
Save Machou/ed35c7be23d6ffa448f5778d363ea33a to your computer and use it in GitHub Desktop.

Aide-mémoire Git

Ajouter une clé publique Linux / Windows > Serveur / VPS

Réconcilier HEAD détaché sur un commit avec une branche

  1. git checkout -b temp
  2. git branch -f branch_base temp
  3. git checkout branch_base
  4. git branch -d temp
  5. git push origin main

Les remotes

  • Lister le dépôt distant

git remote -v

  • Changer le dépôt distant

git remote set-url origin url_depot

Cloner une branche spécifique

  1. Cloner la branche souhaitée

git clone --branch nom_branch url_depot

  1. Direction le répertoire de la branche clonée précédemment

cd nom_projet

  1. Vérifier que tout est ok et sur quelle branche tu es

git status

Cloner un commit spécifique

  1. Cloner le projet initial

git clone url_depot

  1. Passer sur le commit

git reset --hard 2c61e4cfcf0bd893898c323895bc504afaa9a0a6

Réinitialiser le dépôt au dernier commit

git reset --hard

Annuler le git reset --hard

  1. Lancer reflog

git reflog

  1. Passer sur le bon commit

git reset --hard f6e5064

Restaurer un fichier pour résoudre des conflits sur git pull

git restore fichier

Lister les branches du dépôt

git branch -a

git branch

Créer une branche et se placer dessus

git checkout -b nom_branch

Créer une branche

git brannch nom_branch

Changer de branche

git checkout branch

Supprimer une branche

git checkout -d nom_branch

Lister les tags du dépôt

git tag

Créer un tag

git brannch nom_branch

Supprimer un tag

git tag -d nom_tag

Vérifier le statut du dépôt

git status

Cloner un dépôt

git clone url_depot

Afficher la liste des commits

git log

Afficher la liste des commit du fichier

git log -p fichier

Annuler des modifications d'un fichier

git checkout fichier

Afficher les modifications des fichiers non indexé

git diff

Ajouter tous les fichiers

git add .

git add fichier1 fichier2

Supprimer des fichiers / répertoires de l'index dans Git

git rm --cached -r cache/

git rm --cached -r fichier.php

Fusionner les branches récursivement en créant un nouveau commit

git merge branche

Annuler la fusion

git merge --abort

Changer de branche et annuler les modifications

git checkout -f branch

Afficher les dépôts

git remote -v

Supprimer un dépôt

git remote rm nom

Initiliser un projet distant

  1. Initialiser le projet

git init

  1. Ajouter les fichiers

git add .

  1. Commit le tout

git commit -m "First commit"

  1. Ajouter la branche

git branch -M main

  1. Ajouter le dépôt GitHub

git remote add main git@github.com:nom/depot.git

  1. Pousser le tout sur GitHub

git push -u origin main

Participer sur un projet

  1. Forker le dépôt

  2. Cloner le dépôt

git remote add upstream url_depot

git branch nom_branche

git fetch upstream

git checkout -b my-patch upstream/development

  1. Appliquer les changements

git commit -m "Changements"

git push -u origin my-patch:mypatch

git merge my-branch

Global

git init                            # initiates git in the current directory
git clone <address>                 # creates a git repo from given address (get the address from your git-server)
git clone <address> -b <branch_name> <path/to/directory>    # clones a git repo from the address into the given directory and checkout's the given branch
git clone <address> -b <branch_name> --single-branch        # Clones a single branch

git add file.txt                    # adds(stages) file.txt to the git
git add *                           # adds(stages) all new modifications, deletions, creations to the git
git reset file.txt                  # Removes file.txt from the stage
git reset --hard                    # Throws away all your uncommitted changes, hard reset files to HEAD
git rm file.txt                     # removes file.txt both from git and file system
git rm --cached file.txt            # only removes file.txt both from git index
git status                          # shows the modifications and stuff that are not staged yet

git branch                          # shows all the branches (current branch is shown with a star)
git branch my-branch                # creates my-branch
git branch -d my-branch             # deletes my-branch
git checkout my-branch              # switches to my-branch
git merge my-branch                 # merges my-branch to current branch
git push origin --delete my-branch  # delete remote branch
git branch -m <new-branch-name>     # rename the branch
git checkout --orphan <branch_name> # checkout a branch with no commit history
git branch -vv                      # list all branches and their upstreams, as well as last commit on branch
git branch -a                       # List all local and remote branches

git cherry-pick <commit_id>             # merge the specified commit
git cherry-pick <commit_id_A>^..<commit_id_B>   # pick the entire range of commits where A is older than B ( the ^ is for including A as well )

git remote                          # shows the remotes
git remote -v                       # shows the remote for pull and push
git remote add my-remote <address>  # creates a remote (get the address from your git-server)
git remote rm my-remote             # Remove a remote

git log                             # shows the log of commits
git log --oneline                   # shows the log of commits, each commit in a single line
git log -p <file_name>              # change over time for a specific file
git log <Branch1> ^<Branch2>        # lists commit(s) in branch1 that are not in branch2
git log -n <x>                      # lists the last x commits
git log -n <x> --oneline            # lists the last x commits, each commit in single line
git grep --heading --line-number "<string/regex>"   # Find lines matching the pattern in tracked files
git log --grep="<string/regex>"     # Search Commit log

git commit -m "msg"                 # commit changes with a msg
git commit --amend                  # combine staged changes with the previous commit, or edit the previous commit message without changing its snapshot
git commit --amend --no-edit        # amends a commit without changing its commit message
git commit --amend --author="Author Name <email@address.com>"    # Amend the author of a commit
git push my-remote my-branch        # pushes the commits to the my-remote in my-branch (does not push the tags)
git revert <commit-id>              # Undo a commit by creating a new commit

git show                            # shows one or more objects (blobs, trees, tags and commits).
git diff                            # show changes between commits, commit and working tree
git diff --color                    # show colored diff
git diff --staged                   # Shows changes staged for commit

git tag                             # shows all the tags
git tag -a v1.0 -m "msg"            # creates an annotated tag
git show v1.0                       # shows the description of version-1.0 tag
git tag --delete v1.0               # deletes the tag in local directory
git push --delete my-remote v1.0    # deletes the tag in my-remote (be carefore to not delete a branch)
git push my-remote my-branch v1.0   # push v1.0 tag to my-remote in my-branch
git fetch --tags                    # pulls the tags from remote

git pull my-remote my-branch        # pulls and tries to merge my-branch from my-remote to the current branch

git stash                           # stashes the staged and unstaged changes (git status will be clean after it)
git stash -u                        # stash everything including new untracked files (but not .gitignore)
git stash save "message"            # stash with a msg
git stash list                      # list all stashes
git stash pop                       # delete the recent stash and applies it
git stash pop stash@{2}             # delete the {2} stash and applies it
git stash show                      # shows the description of stash
git stash apply                     # keep the stash and applies it to the git
git stash branch my-branch stash@{1}    # creates a branch from your stash
git stash drop stash@{1}            # deletes the {1} stash
git stash clear                     # clears all the stash

git rebase -i <commit_id>           # Rebase commits from a commit ID
git rebase --abort                  # Abort a running rebase
git rebase --continue               # Continue rebasing after fixing all conflicts

git clean -f                        # clean untracked files permanently
git clean -f -d/git clean -fd       # To remove directories permanently
git clean -f -X/git clean -fX       # To remove ignored files permanently
git clean -f -x/git clean -fx       # To remove ignored and non-ignored files permanently

git config --global --list          # lists the git configuration for all repos
git config --global --edit          # opens an editor to edit the git config file
git config --global alias.<handle> <command> # add git aliases to speed up workflow , eg. if  handle is st and command is status then running git st would execute git status 

git help -a

Référez-vous à 'git help <commande>' pour des informations sur une sous-commande spécifique

Commandes Porcelaine Principales
   add                  Ajouter le contenu de fichiers dans l'index
   am                   Appliquer une série de patchs depuis une boîte mail
   archive              Créer une archive des fichiers depuis un arbre nommé
   bisect               Trouver par recherche binaire la modification qui a introduit un bogue
   branch               Lister, créer ou supprimer des branches
   bundle               Déplacer les objets et références par archive
   checkout             Basculer de branche ou restaurer la copie de travail
   cherry-pick          Appliquer les modifications introduites par des commits existants
   citool               Alternative graphique à git-commit
   clean                Supprimer les fichiers non-suivis de l'arbre de travail
   clone                Cloner un dépôt dans un nouveau répertoire
   commit               Enregistrer les modifications dans le dépôt
   describe             Baptiser un objet avec un nom lisible à partir d'une référence disponible
   diff                 Afficher les changements entre les validations, entre validation et copie de travail, etc
   fetch                Télécharger les objets et références depuis un autre dépôt
   format-patch         Préparer les patchs pour soumission par courriel
   gc                   Effacer les fichiers non-nécessaires et optimiser le dépôt local
   gitk                 Le navigateur de dépôt Git
   grep                 Afficher les lignes correspondant à un motif
   gui                  Une interface graphique portable pour Git
   init                 Créer un dépôt Git vide ou réinitialiser un existant
   log                  Afficher l'historique des validations
   maintenance          Lancer les tâches pour optimiser les données du depôt Git
   merge                Fusionner deux ou plusieurs historiques de développement ensemble
   mv                   Déplacer ou renommer un fichier, un répertoire, ou un lien symbolique
   notes                Ajouter ou inspecter les notes d'un objet
   pull                 Rapatrier et intégrer un autre dépôt ou une branche locale
   push                 Mettre à jour les références distantes ainsi que les objets associés
   range-diff           Comparer deux plages de commits (par exemple deux versions d'une branche)
   rebase               Réapplication des commits sur le sommet de l'autre base
   reset                Réinitialiser la HEAD courante à l'état spécifié
   restore              Restaurer les fichiers l'arbre de travail
   revert               Inverser des commits existants
   rm                   Supprimer des fichiers de la copie de travail et de l'index
   shortlog             Résumer la sortie de 'git log'
   show                 Afficher différents types d'objets
   sparse-checkout      Initialiser et modifier l'extraction clairsemée
   stash                Remiser les modifications d'un répertoire de travail sale
   status               Afficher l'état de la copie de travail
   submodule            Initialiser, mettre à jour et inspecter les sous-modules
   switch               Basculer de branche
   tag                  Créer, lister, supprimer ou vérifier un objet d'étiquette signé avec GPG
   worktree             Gérer des arbres de travail multiples

Commandes Auxiliaires / Manipulateurs
   config               Voir et régler les options globales ou de dépôt
   fast-export          Exporteur de données Git
   fast-import          Moteur pour les importateurs rapides de données Git
   filter-branch        Réécrire les branches
   mergetool            Lancer les outils de résolution de conflit de fusion pour résoudre les conflits de fusion
   pack-refs            Empaqueter les têtes et les étiquettes pour un accès efficace au dépôt
   prune                Éliminer les objets inatteignables depuis la base de données des objets
   reflog               Gérer l'information de reflog
   remote               Gérer un ensemble de dépôts suivis
   repack               Empaqueter les objets non-empaquetés d'un dépôt
   replace              Créer, lister, supprimer des référence pour remplacer des objets

Commandes Auxiliaires / Interrogateurs
   annotate             Annoter les lignes du fichier avec l'information de commit
   blame                Montrer la révision et l'auteur qui ont modifié en dernier chaque ligne d'un fichier
   bugreport            Collecter l'information pour l'utilisateur pour remplir un rapport de bogue
   count-objects        Compter le nombre d'objets non-empaquetés et leur consommation d'espace disque
   difftool             Afficher les modifications en utilisant les outils habituel de diff
   fsck                 Vérifier la connectivité et la validité des objets dans la base de données
   gitweb               Interface web de Git
   help                 Afficher l'information d'aide à propos de Git
   instaweb             Naviguer instantanément votre dépôt de travail dans gitweb
   merge-tree           Afficher la fusion à trois points sans modifier l'index
   rerere               Réutiliser une résolution enregistrée de fusions conflictuelles
   show-branch          Afficher les branches et leurs commits
   verify-commit        Vérifier la signature GPG de commits
   verify-tag           Vérifier la signature GPG d'étiquettes
   whatchanged          Afficher les journaux avec la différence que chaque commit introduit

Interaction avec d'autres développeurs
   archimport           Importer dans Git un dépôt GNU Arch
   cvsexportcommit      Exporter un commit unique en extraction CVS
   cvsimport            Sauver vos données depuis un autre SCM qu'on aime à haïr
   cvsserver            Un émulateur de serveur CVS pour Git
   imap-send            Envoyer un ensemble de rustines depuis stdin vers un répertoire IMAP
   p4                   Importer et soumettre à des dépôt Perforce
   quiltimport          Appliquer un patchset quilt sur la branche courante
   request-pull         Générer une résumé des modifications en attentes
   send-email           Envoyer un ensemble de patchs comme courriels
   svn                  Opération Bidirectionnelle entre un dépôt Subversion et Git

Commandes bas-niveau / Manipulateurs
   apply                Appliquer une patch à des fichiers ou à l'index
   checkout-index       Copier les fichiers depuis l'index dans la copie de travail
   commit-graph         Écrire et vérifier les fichiers de graphe de commit Git
   commit-tree          Créer un nouvel objet commit
   hash-object          Calculer l'ID d'objet et créer optionnellement un blob depuis un fichier
   index-pack           Construire un fichier d'index pack depuis une archive compactée existante
   merge-file           Lancer une fusion à 3 points
   merge-index          Lancer une fusion à 3 points pour les fichiers à fusionner
   mktag                Créer un objet étiquette avec validation supplémentaire
   mktree               Construire un objet arbre depuis une texte formaté comme ls-tree
   multi-pack-index     Écrire et vérifier les index multi-paquet
   pack-objects         Créer une archive compactée d'objets
   prune-packed         Éliminer les objets qui sont déjà présents dans les fichiers pack
   read-tree            Lire l'information d'arbre dans l'index
   symbolic-ref         Lire, modifier et supprimer les références symboliques
   unpack-objects       Dépaqueter les objets depuis une archive empaquetée
   update-index         Enregistrer le contenu d'un fichier de l'arbre de travail dans l'index
   update-ref           Mettre à jour le nom d'objet stocké dans une référence en toute sécurité
   write-tree           Créer un objet arbre depuis l'index courant

Commandes bas niveau / Interrogateurs
   cat-file             Fournir le contenu ou l'information de type et taille pour les objets du dépôt
   cherry               Trouver les commits à appliquer en amont
   diff-files           Compare des fichiers de l'arbre de travail et de l'index
   diff-index           Comparer un arbre avec l'arbre de travail ou l'index
   diff-tree            Compare le contenu et le mode des blobs trouvés via deux objets arbre
   for-each-ref         Afficher de l'information sur chaque référence
   for-each-repo        Lance une commande Git sur une liste de dépôts
   get-tar-commit-id    Extraire l'ID du commit depuis une archive créée par git-archive
   ls-files             Afficher l'information à propos des fichiers dans l'index ou l'arbre de travail
   ls-remote            Lister les références dans un dépôt distant
   ls-tree              Afficher le contenu d'un objet arbre
   merge-base           Trouver un ancêtre aussi bon que possible pour une fusion
   name-rev             Trouver les noms symboliques pour des révisions données
   pack-redundant       Trouver les fichiers pack redondants
   rev-list             Afficher les objets commit dans l'ordre chronologique inverse
   rev-parse            Analyser et préparer les paramètres
   show-index           Afficher l'index de l'archive empaquetée
   show-ref             Lister les références du dépôt local
   unpack-file          Créer un fichier temporaire avec le contenu d'un blob
   var                  Afficher un variable logique de Git
   verify-pack          Valider des fichiers d'archive Git empaquetés

Commandes bas niveau / Synchronisation de dépôts
   daemon               Un serveur vraiment simple pour les dépôts Git
   fetch-pack           Télécharger les objets manquants depuis un autre dépôt
   http-backend         Implantation côté serveur de Git sur HTTP
   send-pack            Pousser les objets sur un autre dépôt via le protocole Git
   update-server-info   Mettre à jour le fichier d'informations auxiliaires pour aider les serveurs idiots

Commandes bas niveau / Assistants internes
   check-attr           Afficher les informations gitattributes
   check-ignore         Déboguer gitignore / les fichiers d'exclusion
   check-mailmap        Afficher les noms canoniques et les adresses courriel des contacts
   check-ref-format     S'assurer qu'un nom de référence est bien formé
   column               Afficher les données en colonnes
   credential           Récupérer et sauvegarder les certificats d'utilisateur
   credential-cache     Assistant pour maintenir temporairement en mémoire les mots de passe
   credential-store     Assistant pour sauvegarder les certificats sur disque
   fmt-merge-msg        Produire un message de validation de fusion
   interpret-trailers   Ajouter ou analyser l'information structurée dans les messages de validation
   mailinfo             Extraire le patch et l'information de d'auteur depuis un simple message de courriel
   mailsplit            Programme simple de découpage de mbox UNIX
   merge-one-file       Le programme assistant standard à utiliser avec git-merge-index
   patch-id             Calculer l'ID unique d'un patch
   sh-i18n              Le code d'initialisation i18n pour les scripts shell
   sh-setup             Le code d'initialisation commun aux scripts shell Git
   stripspace           Retirer les espaces inutiles
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment