How to fail a Bazel build on a rule failure?

795 views Asked by At

I am using Bazel rules in NodeJS in my application. The aim is to simply lint a set of files and fail the build if linting fails. What I'm currently experiencing is that the build is successful despite lint errors.

Here's a part of my BUILD file:

load("@npm//htmlhint:index.bzl", "htmlhint")

filegroup(
    name = "htmldata",
    srcs = glob(["**/*.html"]),
)

htmlhint(
  name = "compile",
  data = [
      "htmlhint.conf",
      "//:htmldata"
  ],
  args = [
      "--config",
      "htmlhint.conf",
      "$(locations //:htmldata)"
  ]
)

I first load the hinting library, then I define a filegroup for all the HTML files that I want to lint. Afterward, I use the rule with its data and arguments.

To run the build, I use the default option via npm script: bazel build //...

1

There are 1 answers

0
ant_Ti On

Your build file is working as expected. Unfortunately it doesn't do what you want, because when you load the macro from @npm//htmlhint:index.bzl it sets up the nodejs binary which is a runnable target, which means that it will only create runfiles + executable when building. In this case, the build will not run the library.

There are several options to do what you want:

  1. Use the htmlhint_test macro to create a test target.
  2. Create a custom rule that will use the nodejs binary to build some artefacts. In this case, you can force the build to fail.

However, I suggest using the first approach, because if htmlhint is a linting tool, it won't produce any meaningful outputs and is best to keep it as part of the test suite.

Here's what you need to do to set up the compile target as a test target

diff --git a/BUILD.bazel b/BUILD.bazel
index 4e58ac5..3db5dbb 100644
--- a/BUILD.bazel
+++ b/BUILD.bazel
@@ -1,11 +1,11 @@
-load("@npm//htmlhint:index.bzl", "htmlhint")
+load("@npm//htmlhint:index.bzl", "htmlhint_test")
 
 filegroup(
     name = "htmldata",
     srcs = glob(["**/*.html"]),
 )
 
-htmlhint(
+htmlhint_test(
   name = "compile",
   data = [
       "htmlhint.conf",

Then you can check it with bazel test //....

If you want to see the output just run your compile target with bazel run //path/to:compile