Low-level derivations: Difference between revisions

DoggoBit (talk | contribs)
Second example
DoggoBit (talk | contribs)
aaaand done
Line 48: Line 48:
{{File|example.nix|nix|highlight=1-3,7,11|<nowiki>
{{File|example.nix|nix|highlight=1-3,7,11|<nowiki>
let
let
   pkgs = import '</nowiki><<nowiki>nixpkgs</nowiki>><nowiki>'
   pkgs = import </nowiki><<nowiki>nixpkgs</nowiki>><nowiki> { };
in
in
derivation {
derivation {
Line 95: Line 95:


The SHA is the same, because our inputs haven't changed. This is the essence to why derivations are ''pure functions'' of their inputs.
The SHA is the same, because our inputs haven't changed. This is the essence to why derivations are ''pure functions'' of their inputs.
In rewriting our derivation, we need to import <code>chmod</code>, which is part of the <code>coreutils</code> package. We could point to the binary similarly to how we did it before, but for variation, let's modify our <code>PATH</code> variable instead:
{{File|example.nix|nix|highlight=11|<nowiki>
let
  pkgs = import </nowiki><<nowiki>nixpkgs</nowiki>><nowiki> { };
in
derivation {
  name = "hello-world";
  system = builtins.currentSystem;
  builder = "${pkgs.bash}/bin/bash";
  args = [
    "-c"
    ''
      export PATH="$PATH:${pkgs.coreutils}/bin"
      echo '#!${pkgs.bash}/bin/bash' </nowiki>><nowiki> $out
      echo 'echo "Hello, World!"' </nowiki>>><nowiki> $out
      chmod +x $out
    ''
  ];
}</nowiki>}}
Let's rebuild it again, noticing how the SHA will change again, as we changed our derivation's inputs:
{{code|lang=console|line=no|highlight=3|
$ nix-build example.nix
this derivation will be built:
  /nix/store/ipjigfvbj371a5g966xbnj790sjvq5hp-hello-world.drv
building '/nix/store/ipjigfvbj371a5g966xbnj790sjvq5hp-hello-world.drv'...
/nix/store/lsm49a32nmc3ihi3f119p17lvwadr5ms-hello-world
}}
This time it built successfully. Finally, let's run our script:
{{code|lang=console|line=no|highlight=3|
$ ./result
Hello, world!
}}
As mentioned above, building derivations this way can be unwieldy. But working through this example should shed some light onto why the community has built the [[standard environment]], providing utility functions to build derivations for the most common use cases.