How To Write A File Into Nix Store?

How To Write A File Into Nix Store ?

The following works:

let
  swayConfig = pkgs.writeText "greetd-sway-config" ''
    < CODE >
  '';
in {
  services.greetd.settings.command = "${pkgs.sway}/bin/sway --config ${swayConfig}";
  ...
}

but since <CODE> consists of many line I rather prefer to have them in a file under /etc/nixos.
The following does not work:

let
  mySwayConfig = builtins.readFile config/greetd_sway.conf;
  swayConfig = pkgs.writeTextFile {
    name = "greetd-sway-config";
    text = mySwayConfig;
  };
in { ...

How can I archive what I want?

This should work:

  mySwayConfig = builtins.readFile ./config/greetd_sway.conf;

Yea, @markuskowa is right that you just had the syntax for a relative path literal a little wrong; need that leading ./ in there.

But, the way you have that written, anywhere you would use that swaConfig variable, it’s very likely equivalent to just putting ./config/greetd_swa.conf directly anyway. Whenever you use a path literal like that, nix will automatically copy the file into the store and substitute the resulting path into the nix evaluation.

How can I see if and where nixos-rebuild has written a file into /nix/store?

Nah that’s not right, you don’t need the ./ if the path has a / in it:

nix-repl> foo/bar
/home/tweagysil/foo/bar
1 Like

Thanks for your help!
The following works:

swayConfig = pkgs.writeTextFile {
    name = "greetd-sway-config";
    text = builtins.readFile ./config/greetd_sway.conf;
  };

This does not work:

mySwayConfig = builtins.path {
    path = config/greetd_sway.conf;
    name = "my-greetd-swayConfig";
  };
swayConfig = pkgs.writeTextFile {
    name = "greetd-sway-config";
    text = mySwayConfig;
  };

That creates the file
/nix/store/816lxm632j0p5c2v6r9w6v2fvlv3blkq-greetd-sway-config
which contains only one row:

/nix/store/naghqxapdh1pr5qhyv3hvx7dsr8bwd1b-my-greetd-swayConfig%

The file referenced contains the configuration for sway.
But sway does not understand that reference and throws an error.

As @ElvishJerricco already indicated, you can just use config/greetd_sway.conf directly for swayConfig:

swapConfig = config/greetd_sway.conf;

This should work because paths value get implicitly imported into the Nix store when used in string interpolations. See String interpolation - Nix Reference Manual

1 Like

solution pushed to

Yes, that is even simpler!

let
  prop = import ./properties.nix { };
  swayConfig = config/greetd_sway.conf;
in {
...
}