diff --git a/.githooks/pre-commit b/.githooks/pre-commit new file mode 100755 index 000000000..da1856929 --- /dev/null +++ b/.githooks/pre-commit @@ -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 diff --git a/Makefile b/Makefile index 073b4de27..81515c099 100644 --- a/Makefile +++ b/Makefile @@ -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 diff --git a/docs/dev/quickstart.rst b/docs/dev/quickstart.rst index c45c24491..4cc6feac8 100644 --- a/docs/dev/quickstart.rst +++ b/docs/dev/quickstart.rst @@ -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 diff --git a/manage b/manage index 7edcb1f5a..e7cadf3ac 100755 --- a/manage +++ b/manage @@ -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