Git: hook commit-msg pour adopter les conventional commits


22/09/2020 git commit conventional commit

Les “conventional commits” apportent une formalisation des messages de commit git. Ils sont de la forme :

<type>[optional scope]: <description>

[optional body]

[optional footer(s)]

Pour reprendre quelques exemples :

# Commit message with no body
feat: allow provided config object to extend other configs

# Commit message with scope
feat(lang): add polish language

# Commit message with ! to draw attention to breaking change
refactor!: drop support for Node 6

# Commit message with both ! and BREAKING CHANGE footer
refactor!: drop support for Node 6

BREAKING CHANGE: refactor to use JavaScript features not available in Node 6.

En forçant ce formalisme, le développeur est un peu moins tenté d’avoir un historique de commit du style :

fix  button
typo
add some tests
add some tests
...

Au lieu de faire un commit à chaque sauvegarde du fichier ou presque, il va commencer à “raconter une histoire” :

fix: button on home page does not work on IE6
docs: typo in the README file
feat: add some tests for module XXX

Cela a le mérite aussi de générer un changelog plus agréable à lire. Si en plus, on rajoute par ex un identifiant de ticket, on peut alors facilement retracer l’historique d’un changement et sa raison d’être :

fix(123): button on home page does not work on IE6
docs(211): typo in the README file
feat(175): add some tests for module XXX

Un peu à la manière de “Properly managing your .gitignore file”, on peut vouloir que le hook git s’applique à tous nos dépôts présents et à venir et ne pas avoir à contribuer le hook à chaque dépôt git.

# Create ~/.git-templates/hooks
mkdir -p ~/.git-templates/hooks
# Create commit-msg file and make it executable
touch ~/.git-templates/hooks/commit-msg
chmod +x ~/.git-templates/hooks/commit-msg

Ajoutons ensuite notre hooks dans ~/.git-templates/hooks/commit-msg :

#!/usr/bin/env python3
# Original source: https://github.com/prahladyeri/enforce-git-message/
# Extended with BREAKING CHANGE, exclamation mark support (!) and space before " : " for French people

import re, sys, os

examples = """+ 61c8ca9 fix: navbar not responsive on mobile
+ 479c48b test: prepared test cases for user authentication
+ a992020 chore: moved to semantic versioning
+ b818120 fix: button click even handler firing twice
+ c6e9a97 fix: login page css
+ dfdc715 feat(auth): added social login using twitter
+ b235677 BREAKING CHANGE: remove support for XXX
+ a234556 revert!: back to version X.Y.Z for component ZZZ
+ b123456 feat : we support space before : for French people :-)
"""

def main():
    pattern = r'(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test|BREAKING CHANGE)(\([\w\-\s]+\))?!?\s?:\s.*'
    filename = sys.argv[1]
    ss = open(filename, 'r').read()
    m = re.match(pattern, ss)
    if m == None:
        print("\nCOMMIT FAILED!")
        print("\nPlease enter commit message in the conventional format and try to commit again. Examples:")
        print("\n" + examples)
        sys.exit(1)

if __name__ == "__main__":
    main()

Il faut ensuite indiquer à git que vos templates sont dans ce dossier :

git config --global init.templatedir '~/.git-templates'

Pour les dépots git existants, il faut réinitialiser votre dépôt git :

cd /path/to/git/repo
git init
Dépôt Git existant réinitialisé dans /path/to/git/repo/.git/

Vous pouvez alors commencer à travailler dans votre repo et valider le bon fonctionnement du hook.

Syndication

Restez informé(s) de notre actualité en vous abonnant au flux du blog (Atom)

Nuage de tags

kubernetes docker timeseries influxdb warp10 grafana traefik elasticsearch kafka postgres python ansible aws sécurité terraform mysql redis telegraf git ovh tick chronograf cloud dashboard docker-compose hashicorp timescaledb cassandra helm podman ptsm swarm test vector flux iot kapacitor rancher timescale cérénit influxdata log machine-learning monitoring postgresql raspberrypi s3 spark sql vscode arm bilan comptabilité confluent devops gitlab gitlab-ci iac java ksql microservice nomad perspective prometheus serverless service-mesh angularjs api bigdatahebdo cli cncf consul container discovery dns flows gcp gke graphql influxace ingress javascript npm opensource operator rook scaleway ssh stream vault warpscript windows architecture cert-manager containerd csp documentation elastic forecast geospatial golang hpkp json kafka-streams kibana kubedb lambda lean licence maesh mariadb microsoft mqtt nginx orientdb quasardb redhat registry rest rethinkdb reverse-proxy rgpd warpstudio wireguard agile anomalie apm arima azure bash big-data ceph certificat challenge cluster co2 continous-delivery continous-integration cookie datatask dataviz dbt deployment diff django edge esp32 facebook fec fluxlang gdpr google-analytics grav hsts http/3 https hypriot ia influxdays istio jq k3s lets-encrypt linux load-balancer longhorn meetup metabase mobile molecule mongodb nosql nvidia openebs openhab openssh ovhcloud pandas parquet percona performance php pip pipeline questdb reaper replication rootless rpi rsyslog runc résilience scale secrets société solr sre systemd tempo timezone tinygo tls virtualenv vitess vue.js wagtail warpfleet yarn accessibilité acme adoptopenjdk agpl akka alerte alertes alibaba amazon-emr amqp anonymisation anthos apache-pulsar ara arduino arrow artefact asgi automation automatisation automl awstats banque bastion beam beat bi bme680 bootstrap bounded-context branche brigade browser buildah buildkit calico cd cdc cdk centos certificats cgroups chart check checklist chrome ci cilium cio circuitpython clever-cloud clickhouse cloud-init cloud-native cloud-storage cloudflare clusterip cnab cni cockroachdb code codeurs-en-seine commit confluence conftest consul-connect context continous-deployment conventional-commit coreos cors covid19 cqrs crash cri cron crontab csi csrf css cto curl d3.js daemonset data data-engineer data-pipelining data.gouv.fr databricks datacenter date date-scientist ddd debezium debian delta deprek8 desktop devoxx dig distributed-systems dive docker-app docker-hub docker-registry dockerfile dockershim documentdb dog dokcer données-personnelles draft dredd drop-in dsi duckdb duration déploiement ebs ec2 elassandra electron elk engineering entreprise etcd euclidia event-sourcing faas falco falcor feature-policy fedora feed filebeat firebase firefox fish flash flask fleet flink flovea fluentd font foundation framework frenchtech frontend fsync fugue fullstack git-filter-repo github gitignore gitpod glacier glowroot goaccess google google-cloud-next gpg gpu grep grid géospatial hacker hadoop haproxy harbor hdfs header holt-winters html html5 http httpx hue iaac ibm iiot immutable incident index indluxdata influxcloud infrastructure-as-code ingénierie inspec jenkins jless jquery jvm jwt k3d k6 k8s k9s kaniko katz kubeadm kubecon kubectl label laravel leap-second lens letsencrypt libssh linky linter liste-de-diffusion lmap loadbalancer logstash logstatsh loi loki lstm mailing-list management matomo maturité mesh mesos message metallb micro-service minio mot-de-passe multi-cloud médecine métrique n8n nebula network newsletter nodejs nodeport notebook notifications nrtsearch null numérique object-storage observability observabilité opa opendata openmetrics openshit openstack openweb opnsense over-engineering packaging partiql password persistent-volume-claim pico pipenv pivot pod portainer portworx prediction prescience privacy-shield production promql prophet prévision psp ptyhon publicité pubsub pulsar push pyenv pérénnité qualité quay queue quic ram rambleed raml react readme recaptcha recherche redistimeseries reindex reinvent reliability remote-execution repository responsive retention-policy revocation revue-de-code rexec rhel rkt robotframework rolespec root rpo rto rust rwd réseau résultat safe-harbor sarima scanner schema scp search select semiconducteur serverless-architecture service service-account service-worker setuptools sftp sha1 shard shard-duration shard-group sharding shell shipyard sidecar singer socket souveraineté-numérique spectre spinnaker sqlite sri ssh-agent ssl stabilité stash statistique stm32 storage sudo superset suse sympa sysdig syslog-ng sérénité task tavern template terracost terrascan test-unitaire thingspeak tidb tiers time timecale timer timestream training transformation travail trésorerie tsfel tsfr tsl ubuntu unikernel unit ux velero vendredi victoria-metrics vie-privée virtualbox virtualisation vm vnc volume voxxeddays vpc vpn wasm workflow yaml yield yq yubikey zip