pylapp

Git

My Git cheatsheet

🇺🇸 – Friday, September 27th 2024

Keywords: #Git, #commits, #GitHub, #GPG, #CLI

A bit of context

Sometimes I need to get back some commands I used in my terminal so as to work on my Git repositories of GitHub / GitLab projects. But I can have often some doubts about them, so I decided to list here some useful commands as a cheatsheet or a simple reminder to keep and share. I will try to keep it updated. There are nice resources in the bottom of this document!

Applying some common Git configurations

Use also the —global option if you want to apply this configuration everwyhere.

Apply 'git config' command with parameters 'user.name', 'user.email' and 'user.signingKey' and after the value

Showing GPG keys to get ID to use for commits

Useful to remember the ID of the GPG key to use to sign commits. More details in this other publication (in french).

Apply GPG command 'gpg --list-keys --keyid-format=short'

Verify GPG signature of commits

Keep in mind the software forges like GitHub and GitLab provide also some verification process for commits.

'git verify-commit' or 'git log --show-signature'

Display contributors of a commit

You can also filter to get other metadata in commits, find here for example some ideas.

Use options of command 'git show'

Create branch from another and switch

That's not the only command of course, but I like this one.

Apply command 'git checkout -b new-branch source-branch'

Get rid of the last N commits

You can use of course other things instead of HEAD~N.

Apply command 'git reset --hard HEAD~N' then push with option '--force-with-lease'

Reword, reorder or squash last N commits with interactive rebease

You can use of course other things instead of HEAD~N. Beware of fixup and squash, not the same uses with the commit messages.

git rebase -i HEAD~N

Create a Git patch

Allows to generate a Git patch from a diff to apply or send it later.

Use commands 'git diff' or 'git format-patch' then 'git apply'

Keeping somewhere changes temporary

Useful for drafts or temporary changes you don't want to version.

Use variants of command 'git stash' with actions 'push', 'pop', 'apply'

Find someone to blame (maybe you!)

The aim is to display who modified lines of files.

Use command 'git blame' with -p and -e options

Clean the repository

Clean the project, get rid of files, but beware, you may loose things!

Use 'clean -fd' to get rid of unnsaved files and directories, 'reset --hard' to go back to last commit, 'rm --cached' to remove modifications but keeping file and 'checkout' to make a file be reset to last commit

Work on a fork and submit

The workflow is simple: fork, create local develop branch with your dev stuff, make meaningful commits, then cherry-picks from this branch to a virgin one so as to submit a nice and simple pull request.

Add upstream remote, checkout dev branch and rebase, make cherry-pick from working branch to pull request branch

Resources

You have also some online resources like git-cheat-sheet.readthedocs.io.

But, maybe most important, you can refer also to this amazing comic of Julia Evans, available online and also buy her book. Her comic bellow is licensed under CC-BY-NC-SA 4.0.

Add upstream remote, checkout dev branch and rebase, make cherry-pick from cworking branch to pull request branch [Code samples rendered with carbon.now.sh]

— Last update: Wednesday, October 23th 2024 —

Did you enjoy reading this blog? Give me a beer 🍺 or use something else ❤️‍🔥 Licensed under CC-BY-SA 4.0. Opinions are my own. To contact me, feel free to choose the most suitable medium for you, or for example Mastodon.

Au fait, pensez-vous Ă  signer vos commits ?

🇫🇷 – mercredi 8 juin 2022

Mots clés : #Git, #commits, #GPG, #signature, #cryptographie

Au jour d'aujourd'hui il est indéniable que le code source a une valeur concrète, tant pour ce qui est de la propriété intellectuelle et du patrimoine logiciel qui en découle que pour les sommes investies pour son écriture. En 2009, un article de silicon.fr est paru et évoquait le fait que la valeur des logiciels open source est estimée à 400 milliards de dollars américains, explosant les quelques 25 milliards de dollars américains pour l'écosystème Linux !

Le fait est qu'il faut être capable de définir, et surtout certifier, qui est l'auteur des commits pour savoir à qui appartient la contribution induite. Lorsque des entreprises travaillent avec des filiales ou des prestataires, ou quand du code source est cédé à une fondation ou un organisme tiers, voire même si les projets open source sont critiques, certifier l'origine du commit est rassurant.

Certes, on pourrait se contenter de regarder l'identité de l'auteur, avec par exemple la bonne vieille commande git log, permettant de ressortir l'historique Git et d'obtenir des détails sur les derniers commits.

Affichage d'un commit Git. On distingue notamment une section \

Sauf que le champ Author d'un commit est définit par deux éléments : les champs user.name et user.email de la configuration Git (locale ou globale). Or, ces champs peuvent être définis par n'importe qui, avec n'importe quelle valeur, sans vraiment de contrôle naïf et natif sur ça. Ils ne sont donc pas à considérer comme fiables.

On pourrait aussi regarder du côté du Developer Certificate of Origin (DCO), avec notamment l'option -s dans la commande Git de commit. Or le DCO n'est pas dédié à cette question, mais plutôt au fait que l'on confirme avoir les autorisations qui vont bien pour faire ce commit, apporter cette contribution, dans le respect des licences par exemple. C'est intéressant, mais pas adapté.

On peut par contre considérer la signature des commits via... une clé GPG (option -S).

L'idée est simple finalement : on créé une clé GPG, on la dépose dans son compte sur sa forge logicielle (GitHub ou GitLab par exemple), et on définit dans le dépôt en local la clé à utiliser (user.signingkey). Ainsi, on peut plus fortement confirmer que le commit est bien signé par une personne via sa clé GPG avec la même adresse e-mail entre celle du commit et celle de la clé. C'est d'ailleurs très pratique car via sa forge on peut facilement voir que le commit est vérifié (ellipse bleue), avec une clé GPG d'identifiant donné (rectangle vert), et d'ailleurs signé avec le DCO (rectangle rouge). Bon le hic c'est qu'il faut être capable d'avoir une autorité permettant de vérifier les clés, ou alors de placer une confiance aveugle envers la forge logicielle concernée dont peut-être les administrateurs seraient peu scrupuleux et capables d'altérer les clés publiques enregistrées. À creuser en tout cas.

Extrait de l'interface web de GitHub indiquant que le commit concerné est bien cryptographiquement vérifié

Affichage d'un commit Git. On distingue entre autres une rubrique concernant la clé GPG utilisée avec la cryptographie utilisée et l'empreinte de la clé ainsi que l'adresse email utilisée

Ce faisant, il est même possible de vérifier a posteriori la signature d'un commit via la commande git show [commit] —show-signature, ou plus appropriée la commande git verify-commit [commit] qui renvoie le strict nécessaire en terme d'informations.

Message indiquant que le commit concerné est bien cryptographiquement vérifié

Remarque, ce serait intéressant d'avoir des hooks vérifiant au moment du commit s'il est bien signé. Dans des projets critiques ou sensibles, on saura ainsi s'il n'y a pas un contributeur tiers qui aurait commis des commits sans autorisation. Ce n'est pas suffisant, mais ça aide.

On peut ainsi voir que pour le commit donné, il y a bien eu une signature avec une clé GPG de type EDDSA avec l'identifiant indiqué (dont on retrouve une partie à la fin), et une note indiquant que c'est bien la bonne adresse email qui est utilisée.

Bref, pensez à signer vos commits. C'est rigolo et ça fait classe.

Pour en savoir davantage, je vous conseille cet article assez simple et aussi cette page de la documentation GitHub à propos d'une nouvelle fonctionnalité chez eux : “le mode vigilant”.

— Dernière mise à jour : lundi 3 octobre 2022 Précédemment sur paper.wf —

Did you enjoy reading this blog? Give me a beer 🍺 or use something else ❤️‍🔥 Licensed under CC-BY-SA 4.0. Opinions are my own. To contact me, feel free to choose the most suitable medium for you, or for example Mastodon.

Some words about secrets leaks in Git repositories

🇺🇸 – Sunday, March 6th 2022

Keywords: #Git, #GitLeaks, #leaks, #secrets, #repository

We all know it could be quite easy to leak secrets or sensitive data in our Git repositories.

In most of cases we just acted too fast, or were not aware we added in the version control systems (VCS) such sensitive files or objects. Bad SSH configuration with private or public keys in the VCS tree, API keys defined in hard-coded variables in the source code, keystore files with credentials in the Gradle files (including alias, key and password of course), IP addresses, sensitive URL, and so on.

And when we work on public or shared repositories, we have all those sensitive data spread outside!

When people get noticed of these leaks, they may apply bad patterns to fix these issues, for example :

  • Make a commit “just to remove the change”, (useless because the Git history still contains the data)
  • Make the project private (bad, because users won't be able to get it)
  • Delete the repository (useless if there are forks of it)

One tool can be useful, Gitleaks.

Note that Gitleaks looks both in the files tree of the project and the Git history. That's a reason why we must not make such “fix commit” because the history keeps traces of what we do and tried to hide.

So, I would like to share three useful and cool things:

The command to run Gitleaks is very simple:

Shell command to run gitleakswhere. json is the type ouf output for the report called report.json created after the scan of your git repository named folder.

Beware if you scan big repositories (like a fork or a project with an old history), Gitleaks will take long time to run.

In addition, the Git configuration value diff.renameLimit should be updated to allow Gitleaks to work.

Note that the Orange group provides a GitLab CI template dedicated to GitLeaks with the To Be Continous project! Get it here.

Have fun by scanning your projects! — Last update: Wednesday, August, 10th 2022 Previously on Medium and paper.wf —

Did you enjoy reading this blog? Give me a beer 🍺 or use something else ❤️‍🔥 Licensed under CC-BY-SA 4.0. Opinions are my own. To contact me, feel free to choose the most suitable medium for you, or for example Mastodon.