From 80502064ce8aa56eb7db3bb6552a4253bbf1f3a1 Mon Sep 17 00:00:00 2001 From: Christopher Davis Date: Wed, 29 Sep 2021 00:48:00 -0700 Subject: [PATCH] Add pre-commit hook This is something we can use to check formatting before any commits are pushed. --- build-aux/hooks/pre-commit.hook | 57 +++++++++++++++++++++++++++++++++ meson.build | 6 ++++ 2 files changed, 63 insertions(+) create mode 100755 build-aux/hooks/pre-commit.hook diff --git a/build-aux/hooks/pre-commit.hook b/build-aux/hooks/pre-commit.hook new file mode 100755 index 0000000..452a415 --- /dev/null +++ b/build-aux/hooks/pre-commit.hook @@ -0,0 +1,57 @@ +#!/bin/sh +# Source: https://gitlab.gnome.org/GNOME/fractal/blob/master/hooks/pre-commit.hook + +install_rustfmt() { + if ! which rustup &> /dev/null; then + curl https://sh.rustup.rs -sSf | sh -s -- -y + export PATH=$PATH:$HOME/.cargo/bin + if ! which rustup &> /dev/null; then + echo "Failed to install rustup. Performing the commit without style checking." + exit 0 + fi + fi + + if ! rustup component list|grep rustfmt &> /dev/null; then + echo "Installing rustfmt…" + rustup component add rustfmt + fi +} + +if ! which cargo >/dev/null 2>&1 || ! cargo fmt --help >/dev/null 2>&1; then + echo "Unable to check Fractal’s code style, because rustfmt could not be run." + + if [ ! -t 1 ]; then + # No input is possible + echo "Performing commit." + exit 0 + fi + + echo "" + echo "y: Install rustfmt via rustup" + echo "n: Don't install rustfmt and perform the commit" + echo "Q: Don't install rustfmt and abort the commit" + + echo "" + while true + do + echo -n "Install rustfmt via rustup? [y/n/Q]: "; read yn < /dev/tty + case $yn in + [Yy]* ) install_rustfmt; break;; + [Nn]* ) echo "Performing commit."; exit 0;; + [Qq]* | "" ) echo "Aborting commit."; exit -1 >/dev/null 2>&1;; + * ) echo "Invalid input";; + esac + done + +fi + +echo "--Checking style--" +cargo fmt --all -- --check +if test $? != 0; then + echo "--Checking style fail--" + echo "Please fix the above issues, either manually or by running: cargo fmt --all" + + exit -1 +else + echo "--Checking style pass--" +fi diff --git a/meson.build b/meson.build index c86b463..dd3a4b5 100644 --- a/meson.build +++ b/meson.build @@ -53,4 +53,10 @@ subdir('help') subdir('src') subdir('po') +# Pre-commit hook for rust formatting +if get_option('profile') == 'development' + message('Setting up git pre-commit hook..') + run_command('cp', '-f', 'hooks/pre-commit.hook', '.git/hooks/pre-commit') +endif + meson.add_install_script('build-aux/meson/postinstall.py')