Create a pre-commit hook which is copied on installation

Allow propogating specific files to format for black

Update build messages for black

update hook

Update hook further, add related doc
This commit is contained in:
Grant Lanham 2024-08-24 00:25:58 -04:00
parent 4f7dd05d99
commit bce9669d74
4 changed files with 44 additions and 3 deletions

12
.githooks/pre-commit Executable file
View file

@ -0,0 +1,12 @@
#!/bin/sh
if [ "$SEARXNG_PRECOMMIT" = "true" ]; then
# inspired from: https://prettier.io/docs/en/precommit.html#option-4-shell-script
staged_files=$(git diff --cached --name-only --diff-filter=ACMR | sed 's| |\\ |g')
python_files=$(echo "$staged_files" | grep '\.py$')
# Only attempt to run the formatter if Python files were changes
if [ -n "$python_files" ]; then
echo "$python_files" | xargs ./manage format.python
echo "$python_files" | xargs git add
fi
fi

View file

@ -30,6 +30,7 @@ run: install
PHONY += install uninstall
install uninstall:
$(Q)./manage pyenv.$@
$(Q)./manage git.$@
PHONY += clean
clean: py.clean docs.clean node.clean nvm.clean test.clean

View file

@ -28,6 +28,13 @@ Here is how a minimal workflow looks like:
2. *run* your code: :ref:`make run`
3. *format & test* your code: :ref:`make format.python` and :ref:`make test`
.. tip::
If you run `make install`, and you export the environment variable
`SEARXNG_PRECOMMIT="true"`, a git pre-commit hook will run which will auto format
all python files you check into git for you. If you find this would be
better to enable by default, let us know.
If you think at some point something fails, go back to *start*. Otherwise,
choose a meaningful commit message and we are happy to receive your pull
request. To not end in *wild west* we have some directives, please pay attention

27
manage
View file

@ -94,6 +94,9 @@ pyenv.:
OK : test if virtualenv is OK
format.:
python : format Python code source using black
git.:
install : Installs developer git utilities, such as hooks
uninstall : Removes developer git utilities previously installed
pygments.:
less : build LESS files for pygments
EOF
@ -316,9 +319,27 @@ pyenv.uninstall() {
}
format.python() {
build_msg TEST "[format.python] black \$BLACK_TARGETS"
pyenv.cmd black "${BLACK_OPTIONS[@]}" "${BLACK_TARGETS[@]}"
dump_return $?
if [ -z "$1" ]; then
build_msg TEST "[format.python] black \$BLACK_OPTIONS \$BLACK_TARGETS"
pyenv.cmd black "${BLACK_OPTIONS[@]}" "${BLACK_TARGETS[@]}"
else
build_msg TEST "[format.python] black \$BLACK_OPTIONS $@"
pyenv.cmd black "${BLACK_OPTIONS[@]}" "$@"
fi
}
git.install() {
if [ -d ".git/hooks" ]; then
cp .githooks/pre-commit .git/hooks/pre-commit
else
build_msg INSTALL "Could not find '.git/hooks', hooks were not installed"
fi
}
git.uninstall() {
if [ -f ".git/hooks/pre-commit" ]; then
rm .git/hooks/pre-commit
fi
}
# shellcheck disable=SC2119