I am super excited that pmbethe09 and lautentlb just put in a bunch of extra work to open source Buildifier. Buildifier is a great tool we use in Google to format BUILD files. It automatically organizes attributes, corrects indentation, and generally makes them more readable and excellent.
To try it out, clone the repo and build it with Bazel:
$ git clone firstname.lastname@example.org:bazelbuild/buildifier.git $ cd buildifier $ bazel build //buildifier Extracting Bazel installation... ... INFO: Found 1 target... Target //buildifier:buildifier up-to-date: bazel-bin/buildifier/buildifier.a bazel-bin/buildifier/buildifier INFO: Elapsed time: 203.309s, Critical Path: 7.54s INFO: Build completed successfully, 8 total actions
Now try it out on an ugly BUILD file:
$ echo 'cc_library(srcs = ["foo.cc", "bar.cc"], name = "foo")' > BUILD $ ~/gitroot/buildifier/bazel-bin/buildifier/buildifier BUILD $ cat BUILD cc_library( name = "foo", srcs = [ "bar.cc", "foo.cc", ], )
Finally, why run commands manually when you can have your editor do it for you? I use emacs, so I can set up a hook like this:
(add-hook 'after-save-hook (lambda() (if (string-match "BUILD" (file-name-base (buffer-file-name))) (progn (shell-command (concat "/path/to/buildifier/bazel-bin/buildifier/buildifier " (buffer-file-name))) (find-alternate-file (buffer-file-name))))))
You could also set up a git hook to run this before committing, if that’s more your style. Regardless, give it a try! It’s a quick, easy way to make your BUILD files more readable.