如何在提交时自动格式化 Rust(和 C++)代码?

问题描述 投票:0回答:2

我想在使用

rustfmt
提交时自动格式化代码,就像我之前为
clang-format -i
所做的那样。 IE。仅格式化已在提交中更新的代码行,而不触及其他代码。怎么办?

c++ rust githooks pre-commit-hook rustfmt
2个回答
4
投票

可以通过以下方式使用 git pre-commit hook 来完成:

  1. 使用以下文本将文件
    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
  1. 在您的存储库文件夹中运行:
chmod +x .githooks/pre-commit
git config core.hooksPath .githooks

要使其适用于

clang-format
,您需要将
rustfmt
替换为
clang-format -i
,并在检查文件扩展名(
cpp\h\hpp\etc
)中进行相应的修改。


0
投票
#!/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/

© www.soinside.com 2019 - 2024. All rights reserved.