我想在使用
rustfmt
提交时自动格式化代码,就像我之前为 clang-format -i
所做的那样。 IE。仅格式化已在提交中更新的代码行,而不触及其他代码。怎么办?
可以通过以下方式使用 git pre-commit hook 来完成:
pre-commit
添加到存储库中的文件夹 .githooks
:#!/bin/bash
exe=$(which rustfmt)
if [ -n "$exe" ]
then
# field separator to the new line
IFS=$'\n'
for line in $(git status -s)
do
# if added or modified
if [[ $line == A* || $line == M* ]]
then
# check file extension
if [[ $line == *.rs ]]
then
# format file
rustfmt $(pwd)/${line:3}
# add changes
git add $(pwd)/${line:3}
fi
fi
done
else
echo "rustfmt was not found"
fi
chmod +x .githooks/pre-commit
git config core.hooksPath .githooks
要使其适用于
clang-format
,您需要将rustfmt
替换为clang-format -i
,并在检查文件扩展名(cpp\h\hpp\etc
)中进行相应的修改。
#!/bin/sh
echo "Local Pre-commit Hook...\n"
set -eu
if ! cargo fmt -- --check
then
echo "There are some code style issues."
echo "Run cargo fmt first."
exit 1
fi
if ! cargo clippy --all-targets -- -D warnings
then
echo "There are some clippy issues."
exit 1
fi
if ! cargo test
then
echo "There are some test issues."
exit 1
fi
exit 0
参考:https://deaddabe.fr/blog/2021/09/29/git-pre-commit-hook-for-rust-projects/