Generate and install uBlock config file with home manager

I’m trying to manage my uBlock config file with nix and home-manger, but I am new to nix and getting pretty stuck.

I have a list of uBlock filters at ./ublock-filters. I need to use that file as input and run some shell commands to generate a config file and symlink it to ~/.mozilla/managed-storage/uBlock0@raymondhill.net.json. I can already do this manually but I don’t know how to do it with nix and home-manager.

I know about the home.file option, but as far as I know that can only copy files, whereas I need to generate a file first and then copy it.

Ideally I would like that every time I change the ./ublock-filters file and run home-manager switch, a new config file will be generated and installed to the mozilla directory.

I would really appreciate any guidance with this.

3 Likes

In the end I was able to get what I wanted to work by using the Nix built-in functions instead of shell commands.

home.nix:

home.file.ublock = {
  target = ".mozilla/managed-storage/uBlock0@raymondhill.net.json";
  text = with builtins; ''
    {
      ...
           "userFilters": "${replaceStrings ["\n"] ["\\n"] (readFile ./ublock-filters)}"
      ...
    }
  '';
};

I would still be interested to know if there is a way to do this using shell commands, but for now I guess my question is resolved.

builtins.toJSON is a much nicer way of achieving this :slight_smile:

Also, be aware of this antipattern: In the Nix language — nix.dev documentation

Yep, you would create a mini derivation with runCommand, and then use home.file.<>.source instead of text. Something like this:

home.file.ublock = let
  config = pkgs.runCommand "ublock.json" {} ''
      mkdir -p $out
      echo '{"some": "json"}' > $out/ublock.json
  '';
  in {
    target = ".mozilla/managed-storage/uBlock0@raymondhill.net.json";
    source = "${config}/ublock.json";
  };

I think anyway. I believe I’ve done config-file-from-derivation with home-manager before?

1 Like

Aha! That’s the part I was missing: I didn’t know you could reference the output of a derivation as "${config}/ublock.json".

Thank you for the help. That’s very useful.