Try build an derivation

Hi,

I been wonder for a while if there is something similar to `builtins.tryEval` for derivations, since I often have packages in my system with fail to build on a regular basis, with tryBuild I could exclude or replace them with something else if that happens.

I’ve tried:

success = runCommandLocal "success" {} "exit 0"
failure = runCommandLocal "fail" {} "exit 1"

builtins.tryEval failure
{
  success = true;
  value = «derivation /nix/store/srvmgdkb1yvbdmx253yhl2vccwi04c15-fail.drv»;
}

Trying to force the build during eval with IFD results in an exception which can’t be caught by tryEval

builtins.tryEval (builtins.readDir fail)
error:
       … while calling the 'tryEval' builtin
         at «string»:1:1:
            1| builtins.tryEval (builtins.readDir fail)
             | ^

       … while calling the 'readDir' builtin
         at «string»:1:19:
            1| builtins.tryEval (builtins.readDir fail)
             |                   ^

       (stack trace truncated; use '--show-trace' to show the full, detailed trace)

       error: Cannot build '/nix/store/srvmgdkb1yvbdmx253yhl2vccwi04c15-fail.drv'.
       Reason: builder failed with exit code 1.
       Output paths:
         /nix/store/38w39g5ahbacybmj6ycfl20dmi6x19js-fail
[0 built (3 failed)]

Is any other way to do is or is it not possible to do so in Nix?

I would write the code in buildPhase for example:

{
  description = "build with faile example";

  inputs = {
    nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
  };

  outputs = { self, nixpkgs }: 
    let
      system = "x86_64-linux";
      pkgs = import nixpkgs { inherit system; };

    in {
      packages.x86_64-linux.default =
        pkgs.stdenv.mkDerivation {
          name = "hello.sh";
          
          buildPhase =let
            default = ''
              exit 1
            '';
            ifFail = ''
              touch hello.sh
              echo "#! /bin/sh" >> hello.sh
              echo "echo \"hello\"" >> hello.sh
            '';
          in
            ''
              if ! (${default}); then ${ifFail} fi;
            '';

          installPhase = ''
            mkdir -p $out/bin; 
            install -t $out/bin hello.sh
          '';
          src = self;
        };
  };
}

But I guess I don’t have to explain that this method isn’t perfect.

As for checking if derivation works, if I’m familiar with nix, you’d need to import the package and check if the import was successful. I’ve never done this before. If you want to learn how, check out Language Constructs - Nix Reference Manual

I hope I helped