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

标签 c++ rust githooks pre-commit-hook rustfmt

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

最佳答案

可以通过以下方式使用 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
  • 在您的存储库文件夹中运行:
  • 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/

    相关文章:

    c++ - 为 AVR 编译 c++0x

    rust - 是否可以在 Rust for 循环中声明变量的类型?

    git - 从命令行可以,但是钩子(Hook)(git)

    git - 在某些条件下使用钩子(Hook)自动将一个分支 merge 到另一个基础上?

    C++ typedef 和 struct 问题

    c++ - 模板值 `defValue' 不能出现在常量表达式中

    c++ - 使用 OpenSSL 进行 Base64 编码和解码

    rust - 比较相等性时如何帮助推断通用向量的类型

    rust - "pub use"和 "pub mod"之间的区别?

    node.js - 如何在 "npm install"上安装 git Hook ?