I firmly believe that we developers should always strive to make our software behave as a good citizen of the platform on which it runs. This principle is usually associated with user-facing software, such as iOS or Android apps.

Well, this is no less true when writing Bazel rules. A good rule, in my opinion, in addition to being as hermetic as possible, should also give its actions meaningful mnemonics and, where supported, progress messages.

Mnemonic on ctx.actions.write(…)

While ctx.actions.run(...) and ctx.actions.run_shell(...) have long accepted a mnemonic parameter, which makes their actions easily identifiable when inspecting the action graph with bazel aquery, the same wasn’t possible with ctx.actions.write(...).

File write actions were instead assigned the generic FileWrite mnemonic, regardless of their purpose.

Well, starting with Bazel 9, actions created with the native ctx.actions.write(...) API can also be assigned a custom mnemonic, making them easily distinguishable from other file write actions.

There is nothing particularly complicated to explain here, but regardless, here is how it looks now:

def _impl(ctx):
    my_file = ctx.actions.declare_file(ctx.label.name + ".txt")
    ctx.actions.write(
        content = "Hello, world!",
        output = my_file,
        mnemonic = "WriteHelloWorld",
    )
    return [DefaultInfo(files = depset([my_file]))]

As this is a newer Bazel feature, to maintain compatibility with older versions, consider using the bazel_features module to detect its availability and conditionally pass the mnemonic parameter using the bazel_features.rules.write_action_has_mnemonic feature flag, similar to how I did it in this rules_swift pull request.

Conclusion

A very welcome quality-of-life improvement that every Bazel ruleset should take advantage of.