Skip to content

tools/bazel wrapper to provide tools from nixpkgs #665

@oliverlee

Description

@oliverlee

Hi,

I'm fairly new to Nix and have been recently trying to integrate it into a Bazel build to only provide system dependencies.

I've had a lot of issues with direnv. While copying the entire git directory can be avoided by defining the flake in a subdirectory and specifying path:<subdir>, it is incredibly annoying that it re-evaluates the flake derivation.

I ended up coming up with an alternative using the tools/bazel1 wrapper2. This wrapper creates a shell application that pulls in the nixpkgs dependencies needed for the Bazel build and automatically uses it. The flake file hash is used to cache the derivation so that it doesn't need to happen on every Bazel build, but only if the nixpkgs dependencies have changed.

As a user, you simply run commands as normal provided you have bash, nix, and bazelisk in the PATH.

The desired tools can be defined in a flake

{
  description = "flake defining tools needed by this repo";

  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs/nixos-25.05";
  };

  outputs =
    {
      self,
      nixpkgs,
    }:
    let
      systems = [
        "x86_64-linux"
        "aarch64-linux"
        "aarch64-darwin"
      ];
      forAllSystems = f: nixpkgs.lib.genAttrs systems (system: f system);
    in
    {
      packages = forAllSystems (
        system:
        let
          pkgs = nixpkgs.legacyPackages.${system};
          tools =
            with pkgs;
            [
              bash
              bazelisk
              coreutils
              ...
            ];
        in
        {
          default = pkgs.writeShellApplication {
            name = "bazel-wrapper";
            runtimeInputs = tools;
            inheritPath = false;
            text = ''
              exec bazelisk "$@"
            '';
          };
        }
      );
    };
}
> bazelisk test //... # evals bazel-wrapper derivation
> bazelisk test //... # derivation is cached

Then update the flake (e.g. I add nix to pkgs).

> bazelisk test //... # evals bazel-wrapper derivation

Is this a common enough workflow that rules_nixpkgs could benefit from an example tools/bazel script?

Footnotes

  1. https://github.com/oliverlee/cortex_m/blob/main/tools/bazel

  2. https://github.com/bazelbuild/bazelisk?tab=readme-ov-file#toolsbazel

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions