使用Bazel为C++配置静态分析或linter

5
我正在自学C++,并使用Bazel进行小项目开发。我希望确保自己编写的代码安全并遵循合理的最佳实践,但我不确定该如何做到。我知道有几种静态分析工具,例如tsan和其他分析器, clang-tidy, 或者cpplint

然而,我不确定如何使用Bazel设置这些工具。经过一番搜索,发现了一些看起来很自定义的解决方案,例如Drake(参见cpplint.bzl)或Apollo,但需要编写大量自定义构建工具链逻辑才能使其正常工作,这似乎有些奇怪。是否有正确的设置方法?

2个回答

0

我需要添加文件//cpplint.BUILD并设置可见性,以使@dimo414的解决方案起作用。

//cpplint.BUILD

package(default_visibility = ["//visibility:public"])

py_binary(
    name = "cpplint",
    srcs = ["cpplint.py"],
)

//工作区

load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")

http_archive(
    name = "cpplint_archive",
    build_file = "@//:cpplint.BUILD",
    sha256 = "b2979ff630299293f23c52096e408f2b359e2e26cb5cdf24aed4ce53e4293468",
    strip_prefix = "cpplint-1.2.2",
    url = "https://pypi.python.org/packages/source/c/cpplint/cpplint-1.2.2.tar.gz",
)

最后是Python测试目标。

//solution/BUILD

py_test(
    name = "solution_cpplint_test",
    srcs = ["@cpplint_archive//:cpplint"],
    args = ["solution/%s" % f for f in glob([
        "**/*.cc",
        "**/*.h",
    ])],
    data = [":solution_filegroup"],
    main = "cpplint.py",
)

运行:

$ bazel test solution_cpplint_test

0

我还没有一个很好的答案,而我仍然感到惊讶的是这么手动,但我至少已经让 cpplint.pyclang-tidy 像这样工作:

cpplint

我向我的 src/BUILD 文件添加了这个目标(您需要根据需要配置 --filter):

py_test(
    name = "cpplint",
    srcs = ["@google_styleguide//:cpplint/cpplint.py"],
    data = [":all_cpp_files"],
    # Not sure if there's a better way to express the paths to the src/ dir
    # Drake uses the location oparator, but needs to jump through hoops to get the list of targets
    args = ["--root=src", "--linelength=100", "--counting=detailed",
            "--filter=..."] +
        ["src/%s" % f for f in glob(["**/*.cc", "**/*.h"])],
    main = "cpplint.py",
    python_version = "PY2",
)

@google_styleguide 工作区的定义如下:

new_git_repository(
    name = "google_styleguide",
    remote = "https://github.com/google/styleguide",
    commit = "26470f9ccb354ff2f6d098f831271a1833701b28",
    build_file = "@//:google_styleguide.BUILD",
)

clang-tidy

我创建了一个自定义的shell脚本,大致如下(您需要调整要启用/禁用的checks):

execution_root=$(bazel info execution_root) || exit

clang-tidy \
  -warnings-as-errors=* \
  -header-filter=src/.* \
  -checks="${checks}" \
  "src/"*.cc \
  -- \
    -I "${execution_root}/external/googletest/googletest/include/" \
    -I "${execution_root}/external/absl/" \
    -I "${execution_root}/external/gsl/include/" \
    -I .

你是否在styleguide存储库中手动添加了BUILD文件。我看到以下内容:读取时出错:无法为//:google_styleguide.BUILD加载软件包:在以下目录中找不到BUILD文件。将BUILD文件添加到目录中以将其标记为软件包。 - edc
这已经有一段时间了,我曾经与此进行过斗争,所以我可能会忘记这个,但我不认为我对Google Styleguide repo进行了任何本地更改;我只是将其用作参考。 - dimo414

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接