Skip to content
Julien Guézennec edited this page Mar 21, 2023 · 2 revisions

Git-Tips for Github

ssh -v git@github.com

# Initialize GIT repository and create initial commit
$ git init
$ git add -A; git commit -am "Awesome Module, day one"

//---
git add .
git status // to see what changes are going to be commited
git commit -m 'Some descriptive commit message'
git push origin master
Now, when I use gh-pages, there are only a few more commands that I have to use after the above:

git checkout gh-pages // go to the gh-pages branch
git rebase master // bring gh-pages up to date with master
git push origin gh-pages // commit the changes
git checkout master // return to the master branch

git push --force origin master // The evil ^^


// Commit linear from orign
git pull --rebase
git rebase origin/master

//---

git status
git fetch origin
git pull origin master

# Commentaire ?
esc + :wq + enter

//---

mkdir FastWebStart
cd FastWebStart
git init
touch README
git add README
git commit -m 'first commit'
git remote add origin git@github.com:molokoloco/FastWebStart.git
git push origin master

//---

git commit 'DOM of sprites elements are now re-used + added options presets too ;)'

declare -x GIT_SSH="C:\Program Files\Git\bin\ssh.exe"
http://help.github.com/troubleshooting-ssh/

git log --pretty=oneline

git config --global user.name "Your Name"
git config --global user.email "your_email@whatever.com"

//---

 http://doc.fedora-fr.org/wiki/Gestion_et_contr%C3%B4le_de_versions_avec_Git

to create a branch (by typing git branch foo)

git@github.com:molokoloco/branding.git

$ git clone git@github.com:dash30/thinktank.git 
$ git remote add upstream git://github.com/ginatrapani/thinktank.git

//---

$ git fetch upstream 
$ git checkout 100-retweet-bugfix
$ git rebase upstream

//---

git add .
git commit -m 'Fixing some code...'
git push ssh://git@github.com/molokoloco/jQuery.boxFx.git master:master

// Committing all changes in a repository

git commit -a -m 'Fixing some code...'

//---
// Undo a commit and redo

// If it's a private branch you can amend the commit:
git commit --amend

// If it's a shared branch you'll have to make a new commit:
git commit -m 'Remove accidental .class files.'
git push

$ git tag -a v0.9 558151a
$ git log --oneline --decorate --graph

$ git checkout develop
$ git push --tags

$ git tag -a v0.94 -m 'Version 0.94'
$ ./git tag -l v1.4.2.*
// v1.4.2.1 v1.4.2.2 ...


FROM : https://medium.com/@thomas_blaymire/git-commands-for-web-developers-6868a34df739#.luzcj9tr6

Basics
1. How to start a git repo? = git init 
2. How to remove a git repo? = rm -rf .git
3. How to add a file to the repo? = git add 
4. How to commit a change? = git commit -m “message”
5. How to edit a commit message? = git commit -amend -m 
6. How to change user config? = git config global edit add dashes 
7. How to commit all changes same line? = git commit -a -m “”
8. How to view the status of a project? = git status
9. What is the staging area? = after git add this is staging location
10. How to log all git commit history? = git log
11. How to log all git commit on one line? = git log — oneline
12. How to display a fancy graphical view of commits? = git log — graph — decorate — pretty=oneline — abbrev-commit
13. How to see the code from a commit? = git checkout 7cb4e 
14. How to see the changes to a specific file? = git cat filename 
15. How to go back to branch master (latest)? = checkout master
16. How to see the difference between versions? = git diff 7cb4e 98541
17. How to undo when a file is wrong (staged)? = git reset HEAD css/custom.css
18. How to undo when a file is wrong (committed)? = git checkout HEAD^ css/custom.css
19. How to show what has changed from last time? = git diff
“Commit often and use relevant short commit messages to what you have changed”
Git Branching
A branch in Git is simply a lightweight movable pointer to an individual commit.
1. How to create a branch? = git branch foo_feature 
2. How to switch to the new branch? = git checkout foo_feature 
3. How to see the commit log of new branch? = git log 
4. How to create a branch and switch to? = git checkout -b bar_feature 
5. How to list all branches? = git branch 
6. How to delete a branch? (must switch branch) = git branch -D bar_feature
Git Merging
“Like the opposite of branching, it will bring all changes and commits into one timeline”
1. How to merge a branch? = git merge foo_feature 
2. How to edit conflicted file? = nano file 1 (will show both changes) remove conflict markers (keep both changes)
3. How to combine conflicted files? = nano file 1 (simply add a comma between changes)
4. After conflict changed? = git add file1 then git commit
Remote Repositories
This is where you can essentially clone a centralised repo then you can work on a specific task within that project the same time as someone thousands of miles away who is working remotely.
How to clone a repo to your local machine? = git clone http:// my_project or local folder 
2. Show all remotes available? = git remote (origin the original copy)
3. How to manually add a remote repo? = git remote add /path 
4. How to push a commit to the remote repo? = git push (remote needs to know name branch) 
5. How to push a commit with a branch? = git push origin new_feature (branch name)
These are just a few of my most used however if you want to learn more useful commands view the official git documentation.

git-tips

Collection of git-tips, want to add your tips? Checkout contributing.md


Workflow - Pipeline

Git

Voici les opérations de base de git:

Au début (une seule fois à priori)

git clone

Récupérer un projet Git, c'est à dire l'ensemble d'un projet, avec toutes les versions précédentes, modifications, tags, etc...

Pour pouvoir participer à un projet tracké par Git, il faut faire ceci afin de rejoindre un nouveau repo, dans notre cas, une seule fois, comme ceci:

git clone https://github.com/hyperteach/git-cheatsheet

On peut éventuellement vous demander votre login et mot de passe GitHub pour continuer

Vous pouvez aussi mettre votre nom d'utilisateur directement dans la commande, ainsi vous n'aurez pas à le retaper à chaque opération distante:

git clone https://MON_PSEUDO@github.com/hyperteach/git-cheatsheet

git init

Créer un nouveau projet Git

Pour créer un nouveau projet Git, il faut placer son terminal dans le dossier qu'on veut utiliser, puis:

git init

Si vous voulez que ce projet soit hébergé sur un serveur distant, il faut mettre ça en place (par exemple sur github.com, puis une fois qu'on a l'adresse du repo distant, faire:

git add origin https://github.com/MON_PSEUDO/NOM_DU_PROJET
git push -u origin master

Opérations distantes

git fetch

Demande au repo distant s'il y a des modifications, et récupère toutes les modifications de la branche actuelle:

git fetch

L'option --all permet de demander aussi s'il y a des modifications sur les autres branches:

git fetch --all

git pull

Cette opération est en fait un mix de git fetch et git merge. Elle est souvent plus utile car il est rare de vouloir faire un git fetchsans faire un git merge tout de suite derrière. Elle sert lorsqu'on souhaite rapatrier les modification des autres membres de l'équipe et elle doit être faite avant l'opération git push (un message d'erreur se chargera de vous prévenir si vous oubliez).

git pull

Elle peut aussi être utilisée avec l'option --all afin de récupérer aussi les autres branches du projet. Je conseille de faire ceci afin d'avoir une meilleure vue d'ensemble du projet lorsque les autres travaillent sur d'autres features.

git pull --all

git push

L'opération git pushprend le travail qui a été fait sur la branche actuelle, et envoie ces données au repo distant. C'est la seule façon de rendre disponible le travail qui a été fait aux autres membres de l'équipe:

git push

Si la branche actuelle n'a jamais été poussée sur le repo distant il faut la faire inscrire au repo distant avec l'option -u (après on fait git push sans options)

git push -u origin nom_de_la_branche

A faire par habitude à la fin de la journée, afin que l'équipe puisse consulter les changements au début de la prochaine journée. A faire aussi lorsqu'on souhaite partager immédiatement les changements en cours (par éxemple un artiste ajoute un modèle à intégrer, ou un codeur répare un bug bloquant).

Opérations locales

Les opérations distantes ne sont pas les opérations les plus importantes d'un projet Git. Git n'est pas seulement un outil de partage, mais surtout un outil de gestion de projet, permettant, s'il est utilisé correctement, de retrouver facilement des bugs, de revenir sur ses pas, et d'avoir une vue claire de la progression historique d'un projet.

La gestion se fait localement, puis est partagée avec le reste de l'équipe avec les commandes git pull et git push.

pour gérer un projet Git, il est important de comprendre que l'atome d'un Git, c'est le Commit. Analogue au "Revisions" de SVN.

Il éxiste trois "types" de Commit:

  • Le Commit initial
    • Il n'a aucun commit précédent. Dans notre cas, c'est un projet Unity vide.
  • Le Commit "normal"
    • Il décrit un ensemble de changements. E.g: Un ajout de fonction à une classe.
  • Le Merge
    • Le Merge a deux parents. Il contient idéalement la somme du meilleur de ceux-ci.

git status

Affiche l'état du projet git. Contient souvent aussi des conseils sur quelles commandes utiliser pour passer à la suite.

Voici le résultat pour moi actuellement:

$ git status
On branch master
Your branch is up-to-date with 'origin/master'.
nothing to commit, working directory clean

Ceci signifie qu'au dernières nouvelles, mon projet Git est synchro avec le repo distant, qu'aucun fichier tracké n'a été modifié, et qu'il n'y a pas de nouveaux fichiers.

N'hésitez pas à user et à abuser de cette commande. Elle ne peut jamais faire de mal, et aide souvent à retrouver son chemin (après tout, comment décider quoi faire si on ne sait pas où on en est?)

git add

Ajoute un fichier nouveau, modifié ou supprimé à l'espace de travail Git (appellé "Staging"). Après avoir travaillé, il faut faire une ou plusieurs commandes git add pour selectionner les fichiers à ajouter à son prochain Commit. git add est toujours utilisé avec des options ou des arguments.

Ajouter un fichier spécifié (Utile si on souhaite selectionner avec précision les fichiers à ajouter au Commit en évitant d'autres, ou alors ajouter un nouveau fichier qui n'éxistait pas auparavant):

git add Chemin/Vers/UnFichierModifie.cs

Ajouter tous les fichiers trackés (Utile si on n'a pas ajouté de nouveaux fichiers, et qu'on souhaite enregistrer tous ses changements, c'est à dire 90% des cas)

git add -u

(Ne pas hésiter à faire un git add -u suivi de quelques git add NouveauFichier.cs pour les nouveaux fichiers)

Et enfin, la commande attrape tout (même quelques trucs qu'on préfèrerait mieux ne pas attraper). On peut s'en servir aussi, mais il devient fortement conseillé de consulter le git status pour vérifier qu'il n'y a pas d'invités surprise:

git add .

git commit

Après avoir fait ses git add, on crée un nouveau Commit:

git commit

Appellée seule, cette commande ouvre un console Vim pour éditer son message. Personellement, je ne comprends rien à Vim, du coup j'édite le message directement dans la comment git commit grâce à l'option -m

git commit -m "Fixes lighting on oversaturated lights"

Petit rappel, git add et git commit sont des opérations locales, mes co-équipiers ne voient pas encore les changements. Si veux partager mon travail, je dois donc faire un git push maintenant. En revanche, comme il est si facile de créer de nouveaux Commits sans embêter personne, il devient super utile de créer plein de petits Commits au fil de la journée de travail, puis de faire un git push quand on a fini.

git merge

Lorsque deux branches ont divergé (en local parce qu'on travaille sur plusieurs branches, ou lorsque plusieurs développeurs travaillent sur la même branche en simultané), on peut rapatrier ces changements dans la branche actuelle grâce à la commande git merge

Rapatrier les changements divergents du repo distant (appellé automatiquement par git pull):

git merge

Rapatrier les changement d'une autre branche vers la branche actuelle:

git merge nom_de_la_branche

S'il y a des conflits que Git ne sait pas résoudre tout seul, il vous indiquera quels fichiers il n'a pas su résoudre. On verra plus bas comment résoudre les conflits.

git checkout

Sert à deux choses (éssentiellement):

  • Récupérer un fichier depuis un autre endroit dans le projet (une version précédente, ou sur une autre branche).
  • Se déplacer sur une autre branche (et en créer une nouvelle au besoin)

Récupérer un fichier depuis une autre branche:

git checkout nom_de_la_branche Chemin/Vers/LeFichierEnQuestion.cs

Récupérer un fichier à un Commit donné (besoin des quelques premiers caractères du code d'un commit, visibles dans git log ou sur la page GitHub):

git checkout 8b1c5d Chemin/Vers/LeFichierEnQuestion.cs

Se déplacer sur une branche éxistante:

git checkout nom_de_la_branche

Se déplacer sur une nouvelle branche (option -b)

git checkout -b nom_de_la_branche

Utilisez git checkout -b pour créer des nouvelles branches dès que vous vous attelez à une nouvelle tâche, même si elle semble être finissable en un ou deux Commits seulement. Ca ne coûte rien, et ça permet beaucoup plus de flexibilité dans son travail.

Exemple d'utilisation:

Je décide d'ajouter une fonction au projet:

git checkout -b fight_mechanics_01

Je commence à travailler, faisant des git add, git commit à chaque étape.

Edgar se retourne, et me dit "Hé Kevin, ton shader là, il marche pas du tout avec les textures transparentes, il me faut fissa un fix!". Mes modifications sur les mécaniques de combat n'étant pas terminés (et peut-être fourré de bugs dangereux), je décide de créer une nouvelle branche depuis le master.

 git checkout master
 git checkout -b shader_transparency_fix

Je suis sur une nouvelle branche qui part du master, ne contenant donc pas mes changements sur fight_mechanics_01.
Je corrige les shaders afin de répondre à la demande d'Edgar, faisant des git add et git commità chaque étape.
Après une heure de travail, je pense avoir réglé le problème. Je pousse la branche au repo distant afin qu'Edgar puisse vérifier.

git push -u origin shader_transparency_fix

Edgar de son coté, récupère cette branche pour voir si ça convient.

git pull --all
git checkout shader_transparency_fix
git pull

"C'est pas mal, mais on a vachement perdu en performances." me dit Edgar.
Je continue encore un peu le travail sur les shaders, puis, satisfait des tests de performance, j'intégre ces changements au master.

git checkout master
git pull
git merge shader_transparency_fix

(Je fais des trucs de ninja décrits plus tard pour résoudre les conflits éventuels).
Ensuite je pousse ces changements au repo distant.

git pull
git push

Je retourne sur ma branche pour le système de combat et je continue à bosser.

git checkout fight_mechanics_01

Une fois que je suis satisfait du système de combat, je l'intègre, lui aussi, au master

git checkout master
git pull
git merge fight_mechanics_01

Le système de combat ne touchant peu aux autres fichiers du projet, ce merge se fait sans encombre, je peux donc tout pousser et rentrer à la maison.

git push

Le merge manuel

Parfois, lors d'un git merge ou d'un git pull un fichier ne peut pas être reconcilié automatiquement. pas de panique, il éxiste des solutions simples.

git checkout --keep-theirs et git checkout --keep-ours

Ces deux commandes écrasent la fichier avec une copie parfaite de la version rapatriée (--keep-theirs) ou de la version qui éxistait avant le début du merge (--keep-ours). Imaginons que Edgar et moi avons tous des modifié une scène .unity et une texture .png
Je décide de garder ma version de la scène, et de récupérer la version d'Edgar de la texture:

git checkout --keep-theirs Assets/Textures/Jacket.png
git checkout --keep-ours Assets/Scenes/Level_01.unity

git mergetool

Le mergetool est un outil permettant de créer une nouvelle version d'un fichier de code source, en fusionnant manuellement deux versions différentes. Il faut installer et configurer un outil de mergetool, je précognise meld. Puis utiliser la commande git mergtool. Utilisée sans options, elle lancera le logiciel de mergetool pour chaque fichier encore en conflit.

git mergetool

Ou on peut l'appeller sur un fichier individuel:

git mergetool Assets/Scripts/Player.cs

git commit

Après avoir corrigé les conflits, on crée le Commit de merge à la main en faisant simplement

git commit

L'interface Vim s'ouvre avec un message de commit par défaut. Faites échap, : puis x pour quitter Vim et finaliser le Commit.


P.S: All these commands are tested on git version 2.7.4 (Apple Git-66).

Everyday Git in twenty commands or so

git help everyday

Show helpful guides that come with Git

git help -g

Overwrite pull

git fetch --all && git reset --hard origin/master

List of all files till a commit

git ls-tree --name-only -r <commit-ish>

Git reset first commit

git update-ref -d HEAD

List all the conflicted files

git diff --name-only --diff-filter=U

List of all files changed in a commit

git diff-tree --no-commit-id --name-only -r <commit-ish>

Unstaged changes since last commit

git diff

Changes staged for commit

git diff --cached

Alternatives:

git diff --staged

Show both staged and unstaged changes

git diff HEAD

List all branches that are already merged into master

git branch --merged master

Quickly switch to the previous branch

git checkout -

Remove branches that have already been merged with master

git branch --merged master | grep -v '^\*' | xargs -n 1 git branch -d

Alternatives:

git branch --merged master | grep -v '^\*\|  master' | xargs -n 1 git branch -d # will not delete master if master is not checked out

List all branches and their upstreams, as well as last commit on branch

git branch -vv

Track upstream branch

git branch -u origin/mybranch

Delete local branch

git branch -d <local_branchname>

Delete remote branch

git push origin --delete <remote_branchname>

Alternatives:

git push origin :<remote_branchname>

Undo local changes with the last content in head

git checkout -- <file_name>

Revert: Undo a commit by creating a new commit

git revert <commit-ish>

Reset: Discard commits, advised for private branch

git reset <commit-ish>

Reword the previous commit message

git commit -v --amend

See commit history for just the current branch

git cherry -v master

Amend author.

git commit --amend --author='Author Name <email@address.com>'

Reset author, after author has been changed in the global config.

git commit --amend --reset-author --no-edit

Changing a remote's URL

git remote set-url origin <URL>

Get list of all remote references

git remote

Alternatives:

git remote show

Get list of all local and remote branches

git branch -a

Get only remote branches

git branch -r

Stage parts of a changed file, instead of the entire file

git add -p

Get git bash completion

curl http://git.io/vfhol > ~/.git-completion.bash && echo '[ -f ~/.git-completion.bash ] && . ~/.git-completion.bash' >> ~/.bashrc

What changed since two weeks?

git log --no-merges --raw --since='2 weeks ago'

Alternatives:

git whatchanged --since='2 weeks ago'

See all commits made since forking from master

git log --no-merges --stat --reverse master..

Pick commits across branches using cherry-pick

git checkout <branch-name> && git cherry-pick <commit-ish>

Find out branches containing commit-hash

git branch -a --contains <commit-ish>

Alternatives:

git branch --contains <commit-ish>

Git Aliases

git config --global alias.<handle> <command> 
git config --global alias.st status

Saving current state of tracked files without commiting

git stash

Alternatives:

git stash save

Saving current state including untracked files

git stash save -u

Alternatives:

git stash save --include-untracked

Show list of all saved stashes

git stash list

Apply any stash without deleting from the stashed list

git stash apply <stash@{n}>

Apply last stashed state and delete it from stashed list

git stash pop

Alternatives:

git stash apply stash@{0} && git stash drop stash@{0}

Delete all stored stashes

git stash clear

Alternatives:

git stash drop <stash@{n}>

Grab a single file from a stash

git checkout <stash@{n}> -- <file_path>

Alternatives:

git checkout stash@{0} -- <file_path>

Show all tracked files

git ls-files -t

Show all untracked files

git ls-files --others

Show all ignored files

git ls-files --others -i --exclude-standard

Create new working tree from a repository (git 2.5)

git worktree add -b <branch-name> <path> <start-point>

Create new working tree from HEAD state

git worktree add --detach <path> HEAD

Untrack files without deleting

git rm --cached <file_path>

Alternatives:

git rm --cached -r <directory_path>

Before deleting untracked files/directory, do a dry run to get the list of these files/directories

git clean -n

Forcefully remove untracked files

git clean -f

Forcefully remove untracked directory

git clean -f -d

Alternatives:

git clean -df

Update all the submodules

git submodule foreach git pull

Show all commits in the current branch yet to be merged to master

git cherry -v master

Alternatives:

git cherry -v master <branch-to-be-merged>

Rename a branch

git branch -m <new-branch-name>

Alternatives:

git branch -m [<old-branch-name>] <new-branch-name>

rebases 'feature' to 'master' and merges it in to master

git checkout feature && git rebase @{-1} && git checkout @{-2} && git merge @{-1}

Archive the master branch

git archive master --format=zip --output=master.zip

Modify previous commit without modifying the commit message

git add --all && git commit --amend --no-edit

Prunes references to remote branches that have been deleted in the remote.

git fetch -p

Alternatives:

git remote prune origin

Retrieve the commit hash of the initial revision.

 git rev-list --reverse HEAD | head -1

Visualize the version tree.

git log --pretty=oneline --graph --decorate --all

Alternatives:

gitk --all

Deploying git tracked subfolder to gh-pages

git subtree push --prefix subfolder_name origin gh-pages

Adding a project to repo using subtree

git subtree add --prefix=<directory_name>/<project_name> --squash git@github.com:<username>/<project_name>.git master

Get latest changes in your repo for a linked project using subtree

git subtree pull --prefix=<directory_name>/<project_name> --squash git@github.com:<username>/<project_name>.git master

Export a branch with history to a file.

git bundle create <file> <branch-name>

Import from a bundle

git clone repo.bundle <repo-dir> -b <branch-name>

Get the name of current branch.

git rev-parse --abbrev-ref HEAD

Ignore one file on commit (e.g. Changelog).

git update-index --assume-unchanged Changelog; git commit -a; git update-index --no-assume-unchanged Changelog

Stash changes before rebasing

git rebase --autostash

Fetch pull request by ID to a local branch

git fetch origin pull/<id>/head:<branch-name>

Alternatives:

git pull origin pull/<id>/head:<branch-name>

Show the most recent tag on the current branch.

git describe --tags --abbrev=0

Show inline word diff.

git diff --word-diff

Don’t consider changes for tracked file.

git update-index --assume-unchanged <file_name>

Undo assume-unchanged.

git update-index --no-assume-unchanged <file_name>

Clean the files from .gitignore.

git clean -X -f

Restore deleted file.

git checkout <deleting_commit>^ -- <file_path>

Restore file to a specific commit-hash

git checkout <commit-ish> -- <file_path>

Always rebase instead of merge on pull.

git config --global branch.autosetuprebase always

List all the alias and configs.

git config --list

Make git case sensitive.

git config --global core.ignorecase false

Auto correct typos.

git config --global help.autocorrect 1

Check if the change was a part of a release.

git name-rev --name-only <SHA-1>

Dry run. (any command that supports dry-run flag should do.)

git clean -fd --dry-run

Marks your commit as a fix of a previous commit.

git commit --fixup <SHA-1>

squash fixup commits normal commits.

git rebase -i --autosquash

skip staging area during commit.

git commit -am <commit message>

List ignored files.

git check-ignore *

Status of ignored files.

git status --ignored

Commits in Branch1 that are not in Branch2

git log Branch1 ^Branch2

reuse recorded resolution, record and reuse previous conflicts resolutions.

git config --global rerere.enabled 1

Open all conflicted files in an editor.

git diff --name-only | uniq | xargs $EDITOR

Count unpacked number of objects and their disk consumption.

git count-objects --human-readable

Prune all unreachable objects from the object database.

git gc --prune=now --aggressive

Instantly browse your working repository in gitweb.

git instaweb [--local] [--httpd=<httpd>] [--port=<port>] [--browser=<browser>]

View the GPG signatures in the commit log

git log --show-signature

Remove entry in the global config.

git config --global --unset <entry-name>

Checkout a new branch without any history

git checkout --orphan <branch_name>

Extract file from another branch.

git show <branch_name>:<file_name>

List only the root and merge commits.

git log --first-parent

Merge previous two commits into one.

git rebase --interactive HEAD~2

List all branch is WIP

git checkout master && git branch --no-merged

Find guilty with binary search

git bisect start                    # Search start 
git bisect bad                      # Set point to bad commit 
git bisect good v2.6.13-rc2         # Set point to good commit|tag 
git bisect bad                      # Say current state is bad 
git bisect good                     # Say current state is good 
git bisect reset                    # Finish search 

Bypass pre-commit and commit-msg githooks

git commit --no-verify

List commits and changes to a specific file (even through renaming)

git log --follow -p -- <file_path>

Clone a single branch

git clone -b <branch-name> --single-branch https://github.com/user/repo.git

Create and switch new branch

git checkout -b <branch-name>

Alternatives:

git branch <branch-name> && git checkout <branch-name>

Ignore file mode changes on commits

git config core.fileMode false

Turn off git colored terminal output

git config --global color.ui false

specific color settings

git config --global <specific command e.g branch, diff> <true, false or always>
Clone this wiki locally