Search code examples
nix

Importing a nix file results in an error of anonymous function called with unexpected argument 'system'


I'm trying to set a variable to the result of a function defined in an external file.

Within my nixos config I have something like:

let 
  phpFile = import ./tgsend.nix (pkgs);
in
{
...
}

Where phpFile = import ./tgsend.nix (pkgs); is the new line I added. Calling this function results in an error of:

error: anonymous function at /etc/nixos/tgsend.nix:1:1 called with unexpected argument 'system'

   at /etc/nixos/services.nix:8:13:

        7|   myxmonad = import sources.XMonadLayouts {}; #
        8|   phpFile = import ./tgsend.nix (pkgs);
         |             ^
        9|   in (use '--show-trace' to show detailed location information)

What am I doing wrong?

The contents of tgsend.nix is:

{pkgs}: pkgs.writeText "test.php" "<?php echo 'hello world'; "

Solution

  • There are multiple ways to resolve this, but the core of the issue is that you are calling a function with more arguments that required

    {pkgs}: pkgs.writeText
    

    This line means, a function is accepting an attribute set argument with a property pkgs (attribute set is a dictionary/map). It cannot have anything more (if you want more, should use {pkgs, ...}

    There is a standard way to declare functions that require items from pkgs however which is pkgs.callPackage

    Example with repl:

    nix-repl> pkgs = import <nixpkgs> {}
    nix-repl> myPackage = { lib }: lib.strings.toLower "HELLO WORLD"
    nix-repl> pkgs.callPackage myPackage {}
    "hello world"
    

    callPackage will inject any dependencies in the pkgs for you and the second argument is for overrides. In your example it can be changed as follows:

    tgsend.nix

    { writeText }: 
      writeText "test.php" "<?php echo 'hello world'; "
    
    let 
      phpFile = pkgs.callPackage (import ./tgsend.nix) {};
    in
    {
    ...
    }