#!/bin/bash
# SPDX-License-Identifier: MIT

rs_files=()

while read -r file; do
	file="./$file"
	if [ ! -f "$file" ]; then
		continue
	fi
	if [[ "$file" == *.rs ]]; then
		rs_files+=( "$file" )
	fi
done < <(git diff-index --cached --name-only HEAD)

if [ ${#rs_files[@]} -ne 0 ]; then
	# cargo fmt can only run on all files
	# and even calling rustfmt manually automatically
	# reformats children (used submodules) unless disabled by
	# a flag only available in nightly, so just give up and format
	# everything... Can be reworked in rustfmt 2.0 maybe someday.
	echo "Running cargo fmt"
	cargo fmt || exit
fi

if [ ${#rs_files[@]} -ne 0 ]; then
	echo "Formatting done, re-add required parts if required (or ^C to abort commit):"
	git add -p "${rs_files[@]}" < /dev/tty || exit
else
	echo "No rust file changed"
fi
