我想在使用 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
)。
关于c++ - 如何在提交时自动格式化 Rust(和 C++)代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71222422/