From 4a88a2fc7891d41c612c3bad105ca94963c9c8f0 Mon Sep 17 00:00:00 2001 From: Lucas de Sousa Rosa Date: Wed, 29 Nov 2023 22:47:18 -0300 Subject: [PATCH] Add a post-commit hook for automatic tagging **TL;DR: this post-commit hook ensures that valid versions are automatically tagged based on changes in the `pyproject.toml` file.** This post-commit hook automates the tagging of the project based on changes in the `pyproject.toml` file. Here's a breakdown of what it does: **1. Extracting the version number:** * `git diff HEAD^..HEAD`: This line compares the current commit (`HEAD`) to its immediate predecessor (`HEAD^`). * `-- "$(git rev-parse --show-toplevel)"/pyproject.toml`: This specifies the `pyproject.toml` file within the project root directory. * `grep -m 1 '^\+.*version'`: This searches for the first line starting with a "+" and containing the word "version". * `sed -s 's/[^A-Z0-9\.\-]//g'`: This removes any characters except numbers, letters, dots, and hyphens from the matched line. * `version=`: Finally, the extracted version string is stored in the `version` variable. **2. Validating the version format:** * `if [[ ! $version =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)(\-[A-Z]+\.[0-9]+)?$ ]]; then`: This checks if the extracted version string matches a specific format: * `^`: Starts with the beginning of the string. * `([0-9]+)`: Matches one or more digits (major version). * `\.`: Matches a literal dot. * `([0-9]+)`: Matches one or more digits (minor version). * `\.`: Matches a literal dot. * `([0-9]+)`: Matches one or more digits (patch version). * `(\-[A-Z]+\.[0-9]+)?`: This is optional and matches a hyphen followed by one or more uppercase letters and a dot and another number (pre-release + build information). * `$`: Matches the end of the string. * If the format is invalid, it logs a message and exits with an error code. **3. Creating the tag:** * `git tag -a "v$version"`: This creates a new annotated tag named `v$version` (with the prefix "v") using the extracted version number. * ``-m "`git log -1 --format=%s`"``: This sets the tag message with the full commit message of the current commit. * `echo "Created a new tag, v$version"`: This prints a confirmation message. Co-authored-by: Darwish Ahmad Herati <13837531+daherati@users.noreply.github.com> --- .git-hooks/post-commit | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100755 .git-hooks/post-commit diff --git a/.git-hooks/post-commit b/.git-hooks/post-commit new file mode 100755 index 0000000..043e9ca --- /dev/null +++ b/.git-hooks/post-commit @@ -0,0 +1,10 @@ +#! /bin/bash +version=`git diff HEAD^..HEAD -- "$(git rev-parse --show-toplevel)"/pyproject.toml | grep -m 1 '^\+.*version' | sed -s 's/[^A-Z0-9\.\-]//g'` + +if [[ ! $version =~ ^([0-9]+)\.([0-9]+)\.([0-9]+)(\-[A-Z]+\.[0-9]+)?$ ]]; then + echo -e "Skip tag: invalid version '$version'" + exit 1 +fi + +git tag -a "v$version" -m "`git log -1 --format=%s`" +echo "Created a new tag, v$version" \ No newline at end of file