Default.nix that works with nix-build and with callPackage

It looks like there are two mostly-distinct use cases for default.nix: the file that nix-build looks for, and the default file in a directory that import or callPackage will find if passed the directory name, but the required preamble is different in each case

Either I write something like

with import <nixpkgs> {} ; 
stdenv.mkDerivation { 

that I can use standalone, or I write

{ stdenv, someInput, someOtherInput }:
stdenv.mkDerivation {

that I can refer to elsewhere using callPackage

Is there some way to get the same default.nix to serve both purposes? I’ve taken to writing the latter form and then having a separate build.nix which callPackages it, but it’s more typing for nix-build and nix-shell and I wonder if I’m missing a trick

1 Like

I don’t think that’s possible because in the nix-build case it returns a derivation and in the callPackage case a function.

Is using Flakes a possibilty?

Maybe this pill can help you a bit callPackage design pattern. On that, you can jump over the complication of how the callPackage function works. But using as an example the last nix code on that page, you can then build hello derivation with

nix-build -A hello

I tend to use nix-build --expr '(import <nixpkgs> {}).callPackage ./default.nix {}' in those cases.