Merge branch 'NixOS:master' into vim_o_exrc_support

This commit is contained in:
Birdee 2025-05-22 04:05:35 -07:00 committed by GitHub
commit f81e8e68e5
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
12978 changed files with 385489 additions and 320486 deletions

View file

@ -34,7 +34,27 @@ $ nix-build doc
If the build succeeds, the manual will be in `./result/share/doc/nixpkgs/manual.html`.
### devmode
### Development environment
In order to reduce repetition, consider using tools from the provided development environment:
Load it from the Nixpkgs documentation directory with
```ShellSession
$ cd /path/to/nixpkgs/doc
$ nix-shell
```
To load the development utilities automatically when entering that directory, [set up `nix-direnv`](https://nix.dev/guides/recipes/direnv).
Make sure that your local files aren't added to Git history by adding the following lines to `.git/info/exclude` at the root of the Nixpkgs repository:
```
/**/.envrc
/**/.direnv
```
#### `devmode`
The shell in the manual source directory makes available a command, `devmode`.
It is a daemon, that:

View file

@ -20,12 +20,12 @@ Converts Nix values to strings in the way the [`derivation` built-in function](h
```nix
devShellTools.valueToString (builtins.toFile "foo" "bar")
=> "/nix/store/...-foo"
# => "/nix/store/...-foo"
```
```nix
devShellTools.valueToString false
=> ""
# => ""
```
:::
@ -42,16 +42,22 @@ This function does not support `__structuredAttrs`, but does support `passAsFile
devShellTools.unstructuredDerivationInputEnv {
drvAttrs = {
name = "foo";
buildInputs = [ hello figlet ];
buildInputs = [
hello
figlet
];
builder = bash;
args = [ "-c" "${./builder.sh}" ];
args = [
"-c"
"${./builder.sh}"
];
};
}
=> {
name = "foo";
buildInputs = "/nix/store/...-hello /nix/store/...-figlet";
builder = "/nix/store/...-bash";
}
# => {
# name = "foo";
# buildInputs = "/nix/store/...-hello /nix/store/...-figlet";
# builder = "/nix/store/...-bash";
#}
```
Note that `args` is not included, because Nix does not added it to the builder process environment.
@ -69,7 +75,10 @@ Takes the relevant parts of a derivation and returns a set of environment variab
let
pkg = hello;
in
devShellTools.derivationOutputEnv { outputList = pkg.outputs; outputMap = pkg; }
devShellTools.derivationOutputEnv {
outputList = pkg.outputs;
outputMap = pkg;
}
```
:::

View file

@ -491,7 +491,11 @@ It might be useful to manipulate the content downloaded by `fetchurl` directly i
In this example, we'll adapt [](#ex-fetchers-fetchurl-nixpkgs-version) to append the result of running the `hello` package to the contents we download, purely to illustrate how to manipulate the content.
```nix
{ fetchurl, hello, lib }:
{
fetchurl,
hello,
lib,
}:
fetchurl {
url = "https://raw.githubusercontent.com/NixOS/nixpkgs/23.11/.version";
@ -714,9 +718,10 @@ A wrapper around `fetchpatch`, which takes:
Here is an example of `fetchDebianPatch` in action:
```nix
{ lib
, fetchDebianPatch
, buildPythonPackage
{
lib,
fetchDebianPatch,
buildPythonPackage,
}:
buildPythonPackage rec {
@ -768,9 +773,14 @@ Additionally, the following optional arguments can be given:
: Whether to fetch LFS objects.
*`preFetch`* (String)
: Shell code to be executed before the repository has been fetched, to allow
changing the environment the fetcher runs in.
*`postFetch`* (String)
: Shell code executed after the file has been fetched successfully.
: Shell code executed after the repository has been fetched successfully.
This can do things like check or transform the file.
*`leaveDotGit`* (Boolean)
@ -914,7 +924,9 @@ It produces packages that cannot be built automatically.
{ fetchtorrent }:
fetchtorrent {
config = { peer-limit-global = 100; };
config = {
peer-limit-global = 100;
};
url = "magnet:?xt=urn:btih:dd8255ecdc7ca55fb0bbf81323d87062db1f6d1c";
hash = "";
}

View file

@ -33,7 +33,7 @@ let
version = "0.6.30";
src = fetchurl {
url = "https://github.com/nukeop/nuclear/releases/download/v${version}/${pname}-v${version}.AppImage";
url = "https://github.com/nukeop/nuclear/releases/download/v${version}/nuclear-v${version}.AppImage";
hash = "sha256-he1uGC1M/nFcKpMM9JKY4oeexJcnzV0ZRxhTjtJz6xw=";
};
in
@ -66,7 +66,8 @@ let
url = "https://github.com/irccloud/irccloud-desktop/releases/download/v${version}/IRCCloud-${version}-linux-x86_64.AppImage";
hash = "sha256-/hMPvYdnVB1XjKgU2v47HnVvW4+uC3rhRjbucqin4iI=";
};
in appimageTools.wrapType2 {
in
appimageTools.wrapType2 {
inherit pname version src;
extraPkgs = pkgs: [ pkgs.at-spi2-core ];
}
@ -106,7 +107,8 @@ let
appimageContents = appimageTools.extract {
inherit pname version src;
};
in appimageTools.wrapType2 {
in
appimageTools.wrapType2 {
inherit pname version src;
extraPkgs = pkgs: [ pkgs.at-spi2-core ];
@ -150,7 +152,8 @@ let
substituteInPlace $out/irccloud.desktop --replace-fail 'Exec=AppRun' 'Exec=${pname}'
'';
};
in appimageTools.wrapType2 {
in
appimageTools.wrapType2 {
inherit pname version src;
extraPkgs = pkgs: [ pkgs.at-spi2-core ];

View file

@ -35,7 +35,7 @@ The following derivation will construct a flat-file binary cache containing the
```nix
{ mkBinaryCache, hello }:
mkBinaryCache {
rootPaths = [hello];
rootPaths = [ hello ];
}
```

View file

@ -235,7 +235,11 @@ The following package builds a Docker image that runs the `redis-server` executa
The Docker image will have name `redis` and tag `latest`.
```nix
{ dockerTools, buildEnv, redis }:
{
dockerTools,
buildEnv,
redis,
}:
dockerTools.buildImage {
name = "redis";
tag = "latest";
@ -253,7 +257,9 @@ dockerTools.buildImage {
config = {
Cmd = [ "/bin/redis-server" ];
WorkingDir = "/data";
Volumes = { "/data" = { }; };
Volumes = {
"/data" = { };
};
};
}
```
@ -286,7 +292,11 @@ It uses `runAsRoot` to create a directory and a file inside the image.
This works the same as [](#ex-dockerTools-buildImage-extraCommands), but uses `runAsRoot` instead of `extraCommands`.
```nix
{ dockerTools, buildEnv, hello }:
{
dockerTools,
buildEnv,
hello,
}:
dockerTools.buildImage {
name = "hello";
tag = "latest";
@ -320,7 +330,11 @@ This works the same as [](#ex-dockerTools-buildImage-runAsRoot), but uses `extra
Note that with `extraCommands`, we can't directly reference `/` and must create files and directories as if we were already on `/`.
```nix
{ dockerTools, buildEnv, hello }:
{
dockerTools,
buildEnv,
hello,
}:
dockerTools.buildImage {
name = "hello";
tag = "latest";
@ -350,7 +364,11 @@ dockerTools.buildImage {
Note that using a value of `"now"` in the `created` attribute will break reproducibility.
```nix
{ dockerTools, buildEnv, hello }:
{
dockerTools,
buildEnv,
hello,
}:
dockerTools.buildImage {
name = "hello";
tag = "latest";
@ -766,7 +784,11 @@ The closure of `config` is automatically included in the generated image.
The following package shows a more compact way to create the same output generated in [](#ex-dockerTools-streamLayeredImage-hello).
```nix
{ dockerTools, hello, lib }:
{
dockerTools,
hello,
lib,
}:
dockerTools.streamLayeredImage {
name = "hello";
tag = "latest";
@ -1547,11 +1569,15 @@ The Docker image generated will have a name like `hello-<version>-env` and tag `
This example uses [](#ex-dockerTools-streamNixShellImage-hello) as a starting point.
```nix
{ dockerTools, cowsay, hello }:
{
dockerTools,
cowsay,
hello,
}:
dockerTools.streamNixShellImage {
tag = "latest";
drv = hello.overrideAttrs (old: {
nativeBuildInputs = old.nativeBuildInputs or [] ++ [
nativeBuildInputs = old.nativeBuildInputs or [ ] ++ [
cowsay
];
});

View file

@ -52,23 +52,23 @@ A `deterministic` flag is available for best efforts determinism.
To produce a Nix-store only image:
```nix
let
pkgs = import <nixpkgs> {};
pkgs = import <nixpkgs> { };
lib = pkgs.lib;
make-disk-image = import <nixpkgs/nixos/lib/make-disk-image.nix>;
in
make-disk-image {
inherit pkgs lib;
config = {};
additionalPaths = [ ];
format = "qcow2";
onlyNixStore = true;
partitionTableType = "none";
installBootLoader = false;
touchEFIVars = false;
diskSize = "auto";
additionalSpace = "0M"; # Defaults to 512M.
copyChannel = false;
}
make-disk-image {
inherit pkgs lib;
config = { };
additionalPaths = [ ];
format = "qcow2";
onlyNixStore = true;
partitionTableType = "none";
installBootLoader = false;
touchEFIVars = false;
diskSize = "auto";
additionalSpace = "0M"; # Defaults to 512M.
copyChannel = false;
}
```
Some arguments can be left out, they are shown explicitly for the sake of the example.
@ -78,29 +78,36 @@ Building this derivation will provide a QCOW2 disk image containing only the Nix
To produce a NixOS installation image disk with UEFI and bootloader installed:
```nix
let
pkgs = import <nixpkgs> {};
pkgs = import <nixpkgs> { };
lib = pkgs.lib;
make-disk-image = import <nixpkgs/nixos/lib/make-disk-image.nix>;
evalConfig = import <nixpkgs/nixos/lib/eval-config.nix>;
in
make-disk-image {
inherit pkgs lib;
inherit (evalConfig {
make-disk-image {
inherit pkgs lib;
inherit
(evalConfig {
modules = [
{
fileSystems."/" = { device = "/dev/vda"; fsType = "ext4"; autoFormat = true; };
fileSystems."/" = {
device = "/dev/vda";
fsType = "ext4";
autoFormat = true;
};
boot.grub.device = "/dev/vda";
}
];
}) config;
format = "qcow2";
onlyNixStore = false;
partitionTableType = "legacy+gpt";
installBootLoader = true;
touchEFIVars = true;
diskSize = "auto";
additionalSpace = "0M"; # Defaults to 512M.
copyChannel = false;
memSize = 2048; # Qemu VM memory size in megabytes. Defaults to 1024M.
}
})
config
;
format = "qcow2";
onlyNixStore = false;
partitionTableType = "legacy+gpt";
installBootLoader = true;
touchEFIVars = true;
diskSize = "auto";
additionalSpace = "0M"; # Defaults to 512M.
copyChannel = false;
memSize = 2048; # Qemu VM memory size in megabytes. Defaults to 1024M.
}
```

View file

@ -76,7 +76,11 @@ Note that no user namespace is created, which means that you won't be able to ru
This example uses `ociTools.buildContainer` to create a simple container that runs `bash`.
```nix
{ ociTools, lib, bash }:
{
ociTools,
lib,
bash,
}:
ociTools.buildContainer {
args = [
(lib.getExe bash)

View file

@ -91,7 +91,12 @@ See [](#ex-portableService-hello) to understand how to use the output of `portab
The following example builds a Portable Service image with the `hello` package, along with a service unit that runs it.
```nix
{ lib, writeText, portableService, hello }:
{
lib,
writeText,
portableService,
hello,
}:
let
hello-service = writeText "hello.service" ''
[Unit]
@ -151,7 +156,13 @@ To make things available globally, you must specify the `symlinks` attribute whe
The following package builds on the package from [](#ex-portableService-hello) to make `/etc/ssl` available globally (this is only for illustrative purposes, because `hello` doesn't use `/etc/ssl`).
```nix
{ lib, writeText, portableService, hello, cacert }:
{
lib,
writeText,
portableService,
hello,
cacert,
}:
let
hello-service = writeText "hello.service" ''
[Unit]
@ -167,7 +178,10 @@ portableService {
inherit (hello) version;
units = [ hello-service ];
symlinks = [
{ object = "${cacert}/etc/ssl"; symlink = "/etc/ssl"; }
{
object = "${cacert}/etc/ssl";
symlink = "/etc/ssl";
}
];
}
```

View file

@ -26,7 +26,9 @@ To change a normal derivation to a checkpoint based build, these steps must be t
## Example {#sec-checkpoint-build-example}
```nix
{ pkgs ? import <nixpkgs> {} }:
{
pkgs ? import <nixpkgs> { },
}:
let
inherit (pkgs.checkpointBuildTools)
prepareCheckpointBuild
@ -39,5 +41,6 @@ let
sed -i 's/Hello, world!/Hello, Nix!/g' src/hello.c
'';
});
in mkCheckpointBuild changedHello helloCheckpoint
in
mkCheckpointBuild changedHello helloCheckpoint
```

View file

@ -48,12 +48,19 @@ It is useful with functions in `dockerTools` to allow building Docker images tha
This example includes the `hello` binary in the image so it can do something besides just have the extra files.
```nix
{ dockerTools, fakeNss, hello }:
{
dockerTools,
fakeNss,
hello,
}:
dockerTools.buildImage {
name = "image-with-passwd";
tag = "latest";
copyToRoot = [ fakeNss hello ];
copyToRoot = [
fakeNss
hello
];
config = {
Cmd = [ "/bin/hello" ];
@ -70,8 +77,8 @@ The following code uses `override` to add extra lines to `/etc/passwd` and `/etc
```nix
{ fakeNss }:
fakeNss.override {
extraPasswdLines = ["newuser:x:9001:9001:new user:/var/empty:/bin/sh"];
extraGroupLines = ["newuser:x:9001:"];
extraPasswdLines = [ "newuser:x:9001:9001:new user:/var/empty:/bin/sh" ];
extraGroupLines = [ "newuser:x:9001:" ];
}
```
:::

View file

@ -36,22 +36,29 @@ Accepted arguments are:
You can create a simple environment using a `shell.nix` like this:
```nix
{ pkgs ? import <nixpkgs> {} }:
{
pkgs ? import <nixpkgs> { },
}:
(pkgs.buildFHSEnv {
name = "simple-x11-env";
targetPkgs = pkgs: (with pkgs; [
udev
alsa-lib
]) ++ (with pkgs.xorg; [
libX11
libXcursor
libXrandr
]);
multiPkgs = pkgs: (with pkgs; [
udev
alsa-lib
]);
targetPkgs =
pkgs:
(with pkgs; [
udev
alsa-lib
])
++ (with pkgs.xorg; [
libX11
libXcursor
libXrandr
]);
multiPkgs =
pkgs:
(with pkgs; [
udev
alsa-lib
]);
runScript = "bash";
}).env
```

View file

@ -9,7 +9,7 @@ pkgs.makeSetupHook {
name = "something-hook";
propagatedBuildInputs = [ pkgs.commandsomething ];
depsTargetTargetPropagated = [ pkgs.libsomething ];
} ./script.sh;
} ./script.sh
```
### setup hook that depends on the hello package and runs hello and @shell@ is substituted with path to bash {#sec-pkgs.makeSetupHook-usage-example}
@ -42,7 +42,7 @@ pkgs.makeSetupHook
}
preConfigureHooks+=(_printHelloHook)
''
);
)
```
## Attributes {#sec-pkgs.makeSetupHook-attributes}

View file

@ -8,11 +8,16 @@ repetition when using it with `nix-shell` (or `nix develop`).
Here is a common usage example:
```nix
{ pkgs ? import <nixpkgs> {} }:
{
pkgs ? import <nixpkgs> { },
}:
pkgs.mkShell {
packages = [ pkgs.gnumake ];
inputsFrom = [ pkgs.hello pkgs.gnutar ];
inputsFrom = [
pkgs.hello
pkgs.gnutar
];
shellHook = ''
export DEBUG=1

View file

@ -31,25 +31,34 @@ If the build fails and Nix is run with the `-K/--keep-failed` option, a script `
Build the derivation hello inside a VM:
```nix
{ pkgs }: with pkgs; with vmTools;
runInLinuxVM hello
{ pkgs }: with pkgs; with vmTools; runInLinuxVM hello
```
Build inside a VM with extra memory:
```nix
{ pkgs }: with pkgs; with vmTools;
runInLinuxVM (hello.overrideAttrs (_: { memSize = 1024; }))
{ pkgs }:
with pkgs;
with vmTools;
runInLinuxVM (
hello.overrideAttrs (_: {
memSize = 1024;
})
)
```
Use VM with a disk image (implicitly sets `diskImage`, see [`vmTools.createEmptyImage`](#vm-tools-createEmptyImage)):
```nix
{ pkgs }: with pkgs; with vmTools;
runInLinuxVM (hello.overrideAttrs (_: {
preVM = createEmptyImage {
size = 1024;
fullName = "vm-image";
};
}))
{ pkgs }:
with pkgs;
with vmTools;
runInLinuxVM (
hello.overrideAttrs (_: {
preVM = createEmptyImage {
size = 1024;
fullName = "vm-image";
};
})
)
```
## `vmTools.extractFs` {#vm-tools-extractFs}
@ -66,8 +75,7 @@ Takes a file, such as an ISO, and extracts its contents into the store.
Extract the contents of an ISO file:
```nix
{ pkgs }: with pkgs; with vmTools;
extractFs { file = ./image.iso; }
{ pkgs }: with pkgs; with vmTools; extractFs { file = ./image.iso; }
```
## `vmTools.extractMTDfs` {#vm-tools-extractMTDfs}
@ -86,14 +94,12 @@ Generate a script that can be used to run an interactive session in the given im
Create a script for running a Fedora 27 VM:
```nix
{ pkgs }: with pkgs; with vmTools;
makeImageTestScript diskImages.fedora27x86_64
{ pkgs }: with pkgs; with vmTools; makeImageTestScript diskImages.fedora27x86_64
```
Create a script for running an Ubuntu 20.04 VM:
```nix
{ pkgs }: with pkgs; with vmTools;
makeImageTestScript diskImages.ubuntu2004x86_64
{ pkgs }: with pkgs; with vmTools; makeImageTestScript diskImages.ubuntu2004x86_64
```
## `vmTools.diskImageFuns` {#vm-tools-diskImageFuns}
@ -137,8 +143,13 @@ A set of functions that build a predefined set of minimal Linux distributions im
8GiB image containing Firefox in addition to the default packages:
```nix
{ pkgs }: with pkgs; with vmTools;
diskImageFuns.ubuntu2004x86_64 { extraPackages = [ "firefox" ]; size = 8192; }
{ pkgs }:
with pkgs;
with vmTools;
diskImageFuns.ubuntu2004x86_64 {
extraPackages = [ "firefox" ];
size = 8192;
}
```
## `vmTools.diskImageExtraFuns` {#vm-tools-diskImageExtraFuns}

View file

@ -98,7 +98,8 @@ It has two modes:
```nix
{
"https://nix\\.dev/manual/nix/[a-z0-9.-]*" = "${nix.doc}/share/doc/nix/manual";
"https://nixos\\.org/manual/nix/(un)?stable" = "${emptyDirectory}/placeholder-to-disallow-old-nix-docs-urls";
"https://nixos\\.org/manual/nix/(un)?stable" =
"${emptyDirectory}/placeholder-to-disallow-old-nix-docs-urls";
}
```
@ -302,18 +303,22 @@ While `testBuildFailure` is designed to keep changes to the original builder's e
# Check that a build fails, and verify the changes made during build
```nix
runCommand "example" {
failed = testers.testBuildFailure (runCommand "fail" {} ''
echo ok-ish >$out
echo failing though
exit 3
'');
} ''
grep -F 'ok-ish' $failed/result
grep -F 'failing though' $failed/testBuildFailure.log
[[ 3 = $(cat $failed/testBuildFailure.exit) ]]
touch $out
''
runCommand "example"
{
failed = testers.testBuildFailure (
runCommand "fail" { } ''
echo ok-ish >$out
echo failing though
exit 3
''
);
}
''
grep -F 'ok-ish' $failed/result
grep -F 'failing though' $failed/testBuildFailure.log
[[ 3 = $(cat $failed/testBuildFailure.exit) ]]
touch $out
''
```
:::
@ -396,15 +401,18 @@ testers.testEqualContents {
expected = writeText "expected" ''
foo baz baz
'';
actual = runCommand "actual" {
# not really necessary for a package that's in stdenv
nativeBuildInputs = [ gnused ];
base = writeText "base" ''
foo bar baz
'';
} ''
sed -e 's/bar/baz/g' $base >$out
'';
actual =
runCommand "actual"
{
# not really necessary for a package that's in stdenv
nativeBuildInputs = [ gnused ];
base = writeText "base" ''
foo bar baz
'';
}
''
sed -e 's/bar/baz/g' $base >$out
'';
}
```
@ -515,10 +523,11 @@ Otherwise, the build log explains the difference via `nix-diff`.
# Check that two packages produce the same derivation
```nix
testers.testEqualDerivation
"The hello package must stay the same when enabling checks."
hello
(hello.overrideAttrs(o: { doCheck = true; }))
testers.testEqualDerivation "The hello package must stay the same when enabling checks." hello (
hello.overrideAttrs (o: {
doCheck = true;
})
)
```
:::
@ -586,7 +595,10 @@ testers.runCommand {
curl -o /dev/null https://example.com
touch $out
'';
nativeBuildInputs = with pkgs; [ cacert curl ];
nativeBuildInputs = with pkgs; [
cacert
curl
];
}
```
@ -603,15 +615,20 @@ If your test is part of the Nixpkgs repository, or if you need a more general en
# Run a NixOS test using `runNixOSTest`
```nix
pkgs.testers.runNixOSTest ({ lib, ... }: {
name = "hello";
nodes.machine = { pkgs, ... }: {
environment.systemPackages = [ pkgs.hello ];
};
testScript = ''
machine.succeed("hello")
'';
})
pkgs.testers.runNixOSTest (
{ lib, ... }:
{
name = "hello";
nodes.machine =
{ pkgs, ... }:
{
environment.systemPackages = [ pkgs.hello ];
};
testScript = ''
machine.succeed("hello")
'';
}
)
```
:::
@ -634,10 +651,17 @@ A [NixOS VM test network](https://nixos.org/nixos/manual/index.html#sec-nixos-te
{
name = "my-test";
nodes = {
machine1 = { lib, pkgs, nodes, ... }: {
environment.systemPackages = [ pkgs.hello ];
services.foo.enable = true;
};
machine1 =
{
lib,
pkgs,
nodes,
...
}:
{
environment.systemPackages = [ pkgs.hello ];
services.foo.enable = true;
};
# machine2 = ...;
};
testScript = ''

View file

@ -66,15 +66,17 @@ runCommandWith :: {
# Invocation of `runCommandWith`
```nix
runCommandWith {
name = "example";
derivationArgs.nativeBuildInputs = [ cowsay ];
} ''
cowsay > $out <<EOMOO
'runCommandWith' is a bit cumbersome,
so we have more ergonomic wrappers.
EOMOO
''
runCommandWith
{
name = "example";
derivationArgs.nativeBuildInputs = [ cowsay ];
}
''
cowsay > $out <<EOMOO
'runCommandWith' is a bit cumbersome,
so we have more ergonomic wrappers.
EOMOO
''
```
:::
@ -118,7 +120,7 @@ While the type signature(s) differ from [`runCommandWith`], individual arguments
# Invocation of `runCommand`
```nix
runCommand "my-example" {} ''
runCommand "my-example" { } ''
echo My example command is running
mkdir $out
@ -238,7 +240,7 @@ The following fields are either required, are of a different type than in the sp
Write a desktop file `/nix/store/<store path>/my-program.desktop` to the Nix store.
```nix
{makeDesktopItem}:
{ makeDesktopItem }:
makeDesktopItem {
name = "my-program";
desktopName = "My Program";
@ -260,7 +262,10 @@ makeDesktopItem {
mimeTypes = [ "video/mp4" ];
categories = [ "Utility" ];
implements = [ "org.my-program" ];
keywords = [ "Video" "Player" ];
keywords = [
"Video"
"Player"
];
startupNotify = false;
startupWMClass = "MyProgram";
prefersNonDefaultGPU = false;
@ -276,18 +281,22 @@ makeDesktopItem {
Override the `hello` package to add a desktop item.
```nix
{ copyDesktopItems
, hello
, makeDesktopItem }:
{
copyDesktopItems,
hello,
makeDesktopItem,
}:
hello.overrideAttrs {
nativeBuildInputs = [ copyDesktopItems ];
desktopItems = [(makeDesktopItem {
name = "hello";
desktopName = "Hello";
exec = "hello";
})];
desktopItems = [
(makeDesktopItem {
name = "hello";
desktopName = "Hello";
exec = "hello";
})
];
}
```
@ -446,10 +455,9 @@ The store path will include the name, and it will be a file.
Write the string `Contents of File` to `/nix/store/<store path>`:
```nix
writeText "my-file"
''
writeText "my-file" ''
Contents of File
''
''
```
:::
@ -486,10 +494,9 @@ The store path will be a directory.
Write the string `Contents of File` to `/nix/store/<store path>/share/my-file`:
```nix
writeTextDir "share/my-file"
''
writeTextDir "share/my-file" ''
Contents of File
''
''
```
:::
@ -528,10 +535,9 @@ The store path will include the name, and it will be a file.
Write the string `Contents of File` to `/nix/store/<store path>` and make the file executable.
```nix
writeScript "my-file"
''
writeScript "my-file" ''
Contents of File
''
''
```
This is equivalent to:
@ -570,10 +576,9 @@ The store path will include the name, and it will be a directory.
# Usage of `writeScriptBin`
```nix
writeScriptBin "my-script"
''
writeScriptBin "my-script" ''
echo "hi"
''
''
```
:::
@ -614,10 +619,9 @@ This function is almost exactly like [](#trivial-builder-writeScript), except th
# Usage of `writeShellScript`
```nix
writeShellScript "my-script"
''
writeShellScript "my-script" ''
echo "hi"
''
''
```
:::
@ -657,10 +661,9 @@ This function is a combination of [](#trivial-builder-writeShellScript) and [](#
# Usage of `writeShellScriptBin`
```nix
writeShellScriptBin "my-script"
''
writeShellScriptBin "my-script" ''
echo "hi"
''
''
```
:::
@ -685,26 +688,40 @@ These functions concatenate `files` to the Nix store in a single file. This is u
Here are a few examples:
```nix
# Writes my-file to /nix/store/<store path>
concatTextFile {
name = "my-file";
files = [ drv1 "${drv2}/path/to/file" ];
}
# See also the `concatText` helper function below.
concatTextFile
{
name = "my-file";
files = [
drv1
"${drv2}/path/to/file"
];
}
# See also the `concatText` helper function below.
# Writes executable my-file to /nix/store/<store path>/bin/my-file
concatTextFile {
name = "my-file";
files = [ drv1 "${drv2}/path/to/file" ];
executable = true;
destination = "/bin/my-file";
}
# Writes contents of files to /nix/store/<store path>
concatText "my-file" [ file1 file2 ]
# Writes executable my-file to /nix/store/<store path>/bin/my-file
concatTextFile
{
name = "my-file";
files = [
drv1
"${drv2}/path/to/file"
];
executable = true;
destination = "/bin/my-file";
}
# Writes contents of files to /nix/store/<store path>
concatText
"my-file"
[ file1 file2 ]
# Writes contents of files to /nix/store/<store path>
concatScript "my-file" [ file1 file2 ]
# Writes contents of files to /nix/store/<store path>
concatScript
"my-file"
[
file1
file2
]
```
## `writeShellApplication` {#trivial-builder-writeShellApplication}
@ -722,7 +739,10 @@ For example, the following shell application can refer to `curl` directly, rathe
writeShellApplication {
name = "show-nixos-org";
runtimeInputs = [ curl w3m ];
runtimeInputs = [
curl
w3m
];
text = ''
curl -s 'https://nixos.org' | w3m -dump -T text/html
@ -736,7 +756,14 @@ This can be used to put many derivations into the same directory structure. It w
Here is an example:
```nix
# adds symlinks of hello and stack to current build and prints "links added"
symlinkJoin { name = "myexample"; paths = [ pkgs.hello pkgs.stack ]; postBuild = "echo links added"; }
symlinkJoin {
name = "myexample";
paths = [
pkgs.hello
pkgs.stack
];
postBuild = "echo links added";
}
```
This creates a derivation with a directory structure like the following:
```

View file

@ -12,8 +12,10 @@
nixos-render-docs-redirects,
writeShellScriptBin,
nixpkgs ? { },
markdown-code-runner,
roboto,
treefmt,
}:
stdenvNoCC.mkDerivation (
finalAttrs:
let
@ -45,9 +47,13 @@ stdenvNoCC.mkDerivation (
postPatch = ''
ln -s ${optionsJSON}/share/doc/nixos/options.json ./config-options.json
ln -s ${treefmt.functionsDoc.markdown} ./packages/treefmt-functions.section.md
ln -s ${treefmt.optionsDoc.optionsJSON}/share/doc/nixos/options.json ./treefmt-options.json
'';
buildPhase = ''
runHook preBuild
substituteInPlace ./languages-frameworks/python.section.md \
--subst-var-by python-interpreter-table "$(<"${pythonInterpreterTable}")"
@ -83,19 +89,27 @@ stdenvNoCC.mkDerivation (
--section-toc-depth 1 \
manual.md \
out/index.html
runHook postBuild
'';
installPhase = ''
runHook preInstall
dest="$out/share/doc/nixpkgs"
mkdir -p "$(dirname "$dest")"
mv out "$dest"
mv "$dest/index.html" "$dest/manual.html"
cp "$dest/index.html" "$dest/manual.html"
cp ${roboto.src}/web/Roboto\[ital\,wdth\,wght\].ttf "$dest/Roboto.ttf"
cp ${epub} "$dest/nixpkgs-manual.epub"
mkdir -p $out/nix-support/
echo "doc manual $dest manual.html" >> $out/nix-support/hydra-build-products
echo "doc manual $dest index.html" >> $out/nix-support/hydra-build-products
echo "doc manual $dest nixpkgs-manual.epub" >> $out/nix-support/hydra-build-products
runHook postInstall
'';
passthru = {
@ -111,7 +125,7 @@ stdenvNoCC.mkDerivation (
let
devmode' = devmode.override {
buildArgs = toString ../.;
open = "/share/doc/nixpkgs/manual.html";
open = "/share/doc/nixpkgs/index.html";
};
nixos-render-docs-redirects' = writeShellScriptBin "redirects" "${lib.getExe nixos-render-docs-redirects} --file ${toString ../redirects.json} $@";
in
@ -119,10 +133,14 @@ stdenvNoCC.mkDerivation (
packages = [
devmode'
nixos-render-docs-redirects'
markdown-code-runner
];
};
tests.manpage-urls = callPackage ../tests/manpage-urls.nix { };
tests = {
manpage-urls = callPackage ../tests/manpage-urls.nix { };
check-nix-code-blocks = callPackage ../tests/check-nix-code-blocks.nix { };
};
};
}
)

View file

@ -13,17 +13,23 @@ let
# specifies how to format a key/value pair
mkKeyValue = generators.mkKeyValueDefault {
# specifies the generated string for a subset of nix values
mkValueString = v:
if v == true then ''"yes"''
else if v == false then ''"no"''
else if isString v then ''"${v}"''
mkValueString =
v:
if v == true then
''"yes"''
else if v == false then
''"no"''
else if isString v then
''"${v}"''
# and delegates all other values to the default generator
else generators.mkValueStringDefault {} v;
else
generators.mkValueStringDefault { } v;
} ":";
};
in
# the INI file can now be given as plain old nix values
in customToINI {
customToINI {
main = {
pushinfo = true;
autopush = false;

View file

@ -7,20 +7,23 @@
`pkgs.nix-gitignore` exports a number of functions, but you'll most likely need either `gitignoreSource` or `gitignoreSourcePure`. As their first argument, they both accept either 1. a file with gitignore lines or 2. a string with gitignore lines, or 3. a list of either of the two. They will be concatenated into a single big string.
```nix
{ pkgs ? import <nixpkgs> {} }: {
{
pkgs ? import <nixpkgs> { },
}:
{
src = nix-gitignore.gitignoreSource [] ./source;
# Simplest version
src = nix-gitignore.gitignoreSource [ ] ./source;
# Simplest version
src = nix-gitignore.gitignoreSource "supplemental-ignores\n" ./source;
# This one reads the ./source/.gitignore and concats the auxiliary ignores
src = nix-gitignore.gitignoreSource "supplemental-ignores\n" ./source;
# This one reads the ./source/.gitignore and concats the auxiliary ignores
src = nix-gitignore.gitignoreSourcePure "ignore-this\nignore-that\n" ./source;
# Use this string as gitignore, don't read ./source/.gitignore.
src = nix-gitignore.gitignoreSourcePure "ignore-this\nignore-that\n" ./source;
# Use this string as gitignore, don't read ./source/.gitignore.
src = nix-gitignore.gitignoreSourcePure ["ignore-this\nignore-that\n" ~/.gitignore] ./source;
# It also accepts a list (of strings and paths) that will be concatenated
# once the paths are turned to strings via readFile.
src = nix-gitignore.gitignoreSourcePure [ "ignore-this\nignore-that\n" ~/.gitignore ] ./source;
# It also accepts a list (of strings and paths) that will be concatenated
# once the paths are turned to strings via readFile.
}
```

View file

@ -3,8 +3,7 @@
`prefer-remote-fetch` is an overlay that download sources on remote builder. This is useful when the evaluating machine has a slow upload while the builder can fetch faster directly from the source. To use it, put the following snippet as a new overlay:
```nix
self: super:
(super.prefer-remote-fetch self super)
self: super: (super.prefer-remote-fetch self super)
```
A full configuration example for that sets the overlay up for your own account, could look like this

View file

@ -0,0 +1,17 @@
# autoPatchcilHook {#setup-hook-autopatchcilhook}
This is a special setup hook which helps in packaging .NET assemblies/programs in that it automatically tries to find missing shared library dependencies of .NET assemblies based on the given `buildInputs` and `nativeBuildInputs`.
As the hook needs information for the host where the package will be run on, there's a required environment variable called `autoPatchcilRuntimeId` which should be filled in with the RID (Runtime Identifier) of the machine where the output will be run on. If you're using `buildDotnetModule`, it will fall back to `dotnetRuntimeIds` (which is set to `lib.singleton (if runtimeId != null then runtimeId else systemToDotnetRid stdenvNoCC.hostPlatform.system)`) for you if not provided.
In certain situations you may want to run the main command (`autoPatchcil`) of the setup hook on a file or a set of directories instead of unconditionally patching all outputs. This can be done by setting the `dontAutoPatchcil` environment variable to a non-empty value.
By default, `autoPatchcil` will fail as soon as any .NET assembly requires a dependency which cannot be resolved via the given build inputs. In some situations you might prefer to just leave missing dependencies unpatched and continue to patch the rest. This can be achieved by setting the `autoPatchcilIgnoreMissingDeps` environment variable to a non-empty value. `autoPatchcilIgnoreMissingDeps` can be set to a list like `autoPatchcilIgnoreMissingDeps = [ "libcuda.so.1" "libcudart.so.1" ];` or to `[ "*" ]` to ignore all missing dependencies.
The `autoPatchcil` command requires the `--rid` command line flag, informing the RID (Runtime Identifier) it should assume the assemblies will be executed on, and also recognizes a `--no-recurse` command line flag, which prevents it from recursing into subdirectories.
::: {.note}
Since, unlike most native binaries, .NET assemblies are compiled once to run on any platform, many assemblies may have PInvoke stubs for libraries that might not be available on the platform that the package will effectively run on. A few examples are assemblies that call native Windows APIs through PInvoke targeting `kernel32`, `gdi32`, `user32`, `shell32` or `ntdll`.
`autoPatchcil` does its best to ignore dependencies from other platforms by checking the requested file extensions, however not all PInvoke stubs provide an extension so in those cases it will be necessary to list those in `autoPatchcilIgnoreMissingDeps` manually.
:::

View file

@ -33,3 +33,21 @@ The default value is `build`.
#### `dontUseCmakeConfigure` {#dont-use-cmake-configure}
When set to true, don't use the predefined `cmakeConfigurePhase`.
## Controlling CTest invocation {#cmake-ctest}
By default tests are run by make in [`checkPhase`](#ssec-check-phase) or by [ninja](#ninja) if `ninja` is
available in `nativeBuildInputs`. Makefile and Ninja generators produce the `test` target, which invokes `ctest` under the hood.
This makes passing additional arguments to `ctest` difficult, so it's possible to invoke it directly in `checkPhase`
by adding `ctestCheckHook` to `nativeCheckInputs`.
### CTest Variables {#cmake-ctest-variables}
#### `disabledTests` {#cmake-ctest-disabled-tests}
Allows to disable running a list of tests. Note that regular expressions are not supported by `disabledTests`, but
it can be combined with `--exclude-regex` option.
#### `ctestFlags` {#cmake-ctest-flags}
Additional options passed to `ctest` together with `checkFlags`.

View file

@ -7,6 +7,7 @@ The stdenv built-in hooks are documented in [](#ssec-setup-hooks).
```{=include=} sections
autoconf.section.md
automake.section.md
autopatchcil.section.md
autopatchelf.section.md
aws-c-common.section.md
bmake.section.md

View file

@ -99,17 +99,12 @@ failure. To prevent this, guard the completion generation commands.
```nix
{
nativeBuildInputs = [ installShellFiles ];
postInstall = lib.optionalString (stdenv.hostPlatform.emulatorAvailable buildPackages) (
let
emulator = stdenv.hostPlatform.emulator buildPackages;
in
''
# using named fd
installShellCompletion --cmd foobar \
--bash <(${emulator} $out/bin/foobar --bash-completion) \
--fish <(${emulator} $out/bin/foobar --fish-completion) \
--zsh <(${emulator} $out/bin/foobar --zsh-completion)
''
);
postInstall = lib.optionalString (stdenv.buildPlatform.canExecute stdenv.hostPlatform) ''
# using named fd
installShellCompletion --cmd foobar \
--bash <($out/bin/foobar --bash-completion) \
--fish <($out/bin/foobar --fish-completion) \
--zsh <($out/bin/foobar --zsh-completion)
'';
}
```

View file

@ -0,0 +1,55 @@
# `memcachedTestHook` {#sec-memcachedTestHook}
This hook starts a Memcached server during `checkPhase`. Example:
```nix
{
stdenv,
memcachedTestHook,
}:
stdenv.mkDerivation {
# ...
nativeCheckInputs = [
memcachedTestHook
];
}
```
If you use a custom `checkPhase`, remember to add the `runHook` calls:
```nix
{
checkPhase = ''
runHook preCheck
# ... your tests
runHook postCheck
'';
}
```
## Variables {#sec-memcachedTestHook-variables}
Bash-only variables:
- `memcachedTestPort`: Port to use by Memcached. Defaults to `11211`
Example usage:
```nix
{ stdenv, memcachedTestHook }:
stdenv.mkDerivation {
# ...
nativeCheckInputs = [
memcachedTestHook
];
preCheck = ''
memcachedTestPort=1234;
'';
}

View file

@ -11,15 +11,15 @@ the neceesary environment variables to use
Example:
```nix
{ mpiCheckPhaseHook, mpi, ... }:
{
# ...
{ mpiCheckPhaseHook, mpi, ... }:
{
# ...
nativeCheckInputs = [
openssh
mpiCheckPhaseHook
];
}
nativeCheckInputs = [
openssh
mpiCheckPhaseHook
];
}
```

View file

@ -29,7 +29,11 @@ Given a package `foo` containing an init script `this-foo.fish` that depends on
patch the init script for users to source without having the above dependencies in their `PATH`:
```nix
{ lib, stdenv, patchRcPathFish}:
{
lib,
stdenv,
patchRcPathFish,
}:
stdenv.mkDerivation {
# ...
@ -39,7 +43,13 @@ stdenv.mkDerivation {
];
postFixup = ''
patchRcPathFish $out/bin/this-foo.fish ${lib.makeBinPath [ coreutils man which ]}
patchRcPathFish $out/bin/this-foo.fish ${
lib.makeBinPath [
coreutils
man
which
]
}
'';
}
```

View file

@ -4,7 +4,11 @@
This hook starts a PostgreSQL server during the `checkPhase`. Example:
```nix
{ stdenv, postgresql, postgresqlTestHook }:
{
stdenv,
postgresql,
postgresqlTestHook,
}:
stdenv.mkDerivation {
# ...
@ -18,13 +22,13 @@ stdenv.mkDerivation {
If you use a custom `checkPhase`, remember to add the `runHook` calls:
```nix
checkPhase ''
runHook preCheck
checkPhase ''
runHook preCheck
# ... your tests
# ... your tests
runHook postCheck
''
runHook postCheck
''
```
## Variables {#sec-postgresqlTestHook-variables}

View file

@ -0,0 +1,67 @@
# `redisTestHook` {#sec-redisTestHook}
This hook starts a Redis server during `checkPhase`. Example:
```nix
{
stdenv,
redis,
redisTestHook,
}:
stdenv.mkDerivation {
# ...
nativeCheckInputs = [
redisTestHook
];
}
```
If you use a custom `checkPhase`, remember to add the `runHook` calls:
```nix
{
checkPhase = ''
runHook preCheck
# ... your tests
runHook postCheck
'';
}
```
## Variables {#sec-redisTestHook-variables}
The hook logic will read the following variables and set them to a default value if unset or empty.
Exported variables:
- `REDIS_SOCKET`: UNIX domain socket path
Bash-only variables:
- `redisTestPort`: Port to use by Redis. Defaults to `6379`
Example usage:
```nix
{
stdenv,
redis,
redisTestHook,
}:
stdenv.mkDerivation {
# ...
nativeCheckInputs = [
redisTestHook
];
preCheck = ''
redisTestPort=6390;
'';
}
```

View file

@ -23,46 +23,47 @@ In Nixpkgs, `cargo-tauri.hook` overrides the default build and install phases.
wrapGAppsHook4,
}:
rustPlatform.buildRustPackage rec {
# . . .
rustPlatform.buildRustPackage (finalAttrs: {
# ...
useFetchCargoVendor = true;
cargoHash = "...";
# Assuming our app's frontend uses `npm` as a package manager
npmDeps = fetchNpmDeps {
name = "${pname}-npm-deps-${version}";
inherit src;
name = "${finalAttrs.pname}-${finalAttrs.version}-npm-deps";
inherit (finalAttrs) src;
hash = "...";
};
nativeBuildInputs = [
# Pull in our main hook
cargo-tauri.hook
nativeBuildInputs =
[
# Pull in our main hook
cargo-tauri.hook
# Setup npm
nodejs
npmHooks.npmConfigHook
# Setup npm
nodejs
npmHooks.npmConfigHook
# Make sure we can find our libraries
pkg-config
wrapGAppsHook4
];
buildInputs =
[ openssl ]
# Make sure we can find our libraries
pkg-config
]
++ lib.optionals stdenv.hostPlatform.isLinux [
glib-networking # Most Tauri apps need networking
webkitgtk_4_1
wrapGAppsHook4
];
buildInputs = lib.optionals stdenv.hostPlatform.isLinux [
glib-networking # Most Tauri apps need networking
openssl
webkitgtk_4_1
];
# Set our Tauri source directory
cargoRoot = "src-tauri";
# And make sure we build there too
buildAndTestSubdir = cargoRoot;
buildAndTestSubdir = finalAttrs.cargoRoot;
# . . .
}
# ...
})
```
## Variables controlling cargo-tauri {#tauri-hook-variables-controlling}

View file

@ -9,7 +9,7 @@ You use it like this:
lib,
stdenv,
versionCheckHook,
# ...
# ...
}:
stdenv.mkDerivation (finalAttrs: {

View file

@ -14,7 +14,7 @@ The variables below are exclusive of `wafHook`.
Location of the `waf` tool. It defaults to `./waf`, to honor software projects that include it directly inside their source trees.
If `wafPath` doesn't exist, then `wafHook` will copy the `waf` provided from Nixpkgs to it.
If the file pointed by `wafPath` doesn't exist, then `waf` provided by Nixpkgs will be used.
#### `wafFlags` {#waf-flags}

View file

@ -7,9 +7,10 @@ In Nixpkgs, `zig.hook` overrides the default build, check and install phases.
## Example code snippet {#zig-hook-example-code-snippet}
```nix
{ lib
, stdenv
, zig
{
lib,
stdenv,
zig,
}:
stdenv.mkDerivation {

View file

@ -63,17 +63,27 @@ For example, the `fetchFromGitHub` is commonly used within Nixpkgs but should be
`nix:fod` properties may be extracted and evaluated to a derivation using code similar to the following, assuming a fictitious function `filterPropertiesToAttrs`:
```nix
{ pkgs, filterPropertiesToAttrs, properties }:
{
pkgs,
filterPropertiesToAttrs,
properties,
}:
let
fodProps = filterPropertiesToAttrs "nix:fod:" properties;
methods = {
fetchzip =
{ name, url, sha256, ... }:
{
name,
url,
sha256,
...
}:
pkgs.fetchzip {
inherit name url sha256;
};
};
in methods.${fodProps.method} fodProps
in
methods.${fodProps.method} fodProps
```

View file

@ -48,7 +48,7 @@ You can also reference a GitHub repository
agda.withPackages (p: [
(p.standard-library.overrideAttrs (oldAttrs: {
version = "1.5";
src = fetchFromGitHub {
src = fetchFromGitHub {
repo = "agda-stdlib";
owner = "agda";
rev = "v1.5";
@ -114,7 +114,9 @@ This can be overridden by a different version of `ghc` as follows:
```nix
agda.withPackages {
pkgs = [ /* ... */ ];
pkgs = [
# ...
];
ghc = haskell.compiler.ghcHEAD;
}
```
@ -132,8 +134,10 @@ A derivation can then be written using `agdaPackages.mkDerivation`. This has sim
Here is an example `default.nix`
```nix
{ nixpkgs ? <nixpkgs> }:
with (import nixpkgs {});
{
nixpkgs ? <nixpkgs>,
}:
with (import nixpkgs { });
agdaPackages.mkDerivation {
version = "1.0";
pname = "my-agda-lib";
@ -179,8 +183,12 @@ the Agda package set is small and can (still) be maintained by hand.
To add an Agda package to `nixpkgs`, the derivation should be written to `pkgs/development/libraries/agda/${library-name}/` and an entry should be added to `pkgs/top-level/agda-packages.nix`. Here it is called in a scope with access to all other Agda libraries, so the top line of the `default.nix` can look like:
```nix
{ mkDerivation, standard-library, fetchFromGitHub }:
{}
{
mkDerivation,
standard-library,
fetchFromGitHub,
}:
{ }
```
Note that the derivation function is called with `mkDerivation` set to `agdaPackages.mkDerivation`, therefore you
@ -200,8 +208,12 @@ mkDerivation {
libraryName = "IAL-1.3";
buildPhase = ''
runHook preBuild
patchShebangs find-deps.sh
make
runHook postBuild
'';
}
```

View file

@ -8,23 +8,31 @@ supporting features.
Use the `android-studio-full` attribute for a very complete Android SDK, including system images:
```nix
buildInputs = [ android-studio-full ];
{
buildInputs = [ android-studio-full ];
}
```
This is identical to:
```nix
buildInputs = [ androidStudioPackages.stable.full ];
{
buildInputs = [ androidStudioPackages.stable.full ];
}
```
Alternatively, you can pass composeAndroidPackages to the `withSdk` passthru:
```nix
buildInputs = [
(android-studio.withSdk (androidenv.composeAndroidPackages {
includeNDK = true;
}).androidsdk)
];
{
buildInputs = [
(android-studio.withSdk
(androidenv.composeAndroidPackages {
includeNDK = true;
}).androidsdk
)
];
}
```
These will export `ANDROID_SDK_ROOT` and `ANDROID_NDK_ROOT` to the SDK and NDK directories
@ -35,13 +43,20 @@ in the specified Android build environment.
Alternatively, you can deploy the SDK separately with a desired set of plugins, or subsets of an SDK.
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
let
androidComposition = androidenv.composeAndroidPackages {
platformVersions = [ "34" "35" ];
platformVersions = [
"34"
"35"
"latest"
];
systemImageTypes = [ "google_apis_playstore" ];
abiVersions = [ "armeabi-v7a" "arm64-v8a" ];
abiVersions = [
"armeabi-v7a"
"arm64-v8a"
];
includeNDK = true;
includeExtras = [
"extras;google;auto"
@ -116,7 +131,8 @@ For each requested system image we can specify the following options:
be included. Defaults to `armeabi-v7a` and `arm64-v8a`.
Most of the function arguments have reasonable default settings, preferring the latest
versions of tools when possible.
versions of tools when possible. You can additionally specify "latest" for any plugin version
that you do not care about, and just want the latest of.
You can specify license names:
@ -165,7 +181,7 @@ We can also deploy subsets of the Android SDK. For example, to only the
`platform-tools` package, you can evaluate the following expression:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
let
androidComposition = androidenv.composeAndroidPackages {
@ -183,7 +199,7 @@ to use a predefined composition that contains a fairly complete set of Android p
The following Nix expression can be used to deploy the entire SDK:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
androidenv.androidPkgs.androidsdk
```
@ -191,7 +207,7 @@ androidenv.androidPkgs.androidsdk
It is also possible to use one plugin only:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
androidenv.androidPkgs.platform-tools
```
@ -205,7 +221,7 @@ An emulator spawn script can be configured by invoking the `emulateApp {}`
function:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
androidenv.emulateApp {
name = "emulate-MyAndroidApp";
@ -221,7 +237,7 @@ It is also possible to specify an APK to deploy inside the emulator
and the package and activity names to launch it:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
androidenv.emulateApp {
name = "emulate-MyAndroidApp";
@ -344,7 +360,7 @@ requires. Most newer Android projects use Gradle, and this is included for histo
purposes.
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
androidenv.buildApp {
name = "MyAndroidApp";

View file

@ -11,7 +11,9 @@ ags.bundle {
pname = "hyprpanel";
version = "1.0.0";
src = fetchFromGitHub { ... };
src = fetchFromGitHub {
#...
};
# change your entry file (default is `app.ts`)
entry = "app.ts";
@ -32,7 +34,9 @@ ags.bundle {
# GTK 4 support is opt-in
enableGtk4 = true;
meta = { ... };
meta = {
#...
};
}
```

View file

@ -60,7 +60,10 @@ $ nix-shell -p beamPackages.rebar3
```nix
let
pkgs = import <nixpkgs> { config = {}; overlays = []; };
pkgs = import <nixpkgs> {
config = { };
overlays = [ ];
};
in
pkgs.mkShell {
packages = [ pkgs.beamPackages.rebar3 ];
@ -120,26 +123,28 @@ If there are git dependencies.
{
mixNixDeps = import ./mix.nix {
inherit beamPackages lib;
overrides = (final: prev: {
# mix2nix does not support git dependencies yet,
# so we need to add them manually
prometheus_ex = beamPackages.buildMix rec {
name = "prometheus_ex";
version = "3.0.5";
overrides = (
final: prev: {
# mix2nix does not support git dependencies yet,
# so we need to add them manually
prometheus_ex = beamPackages.buildMix rec {
name = "prometheus_ex";
version = "3.0.5";
# Change the argument src with the git src that you actually need
src = fetchFromGitLab {
domain = "git.pleroma.social";
group = "pleroma";
owner = "elixir-libraries";
repo = "prometheus.ex";
rev = "a4e9beb3c1c479d14b352fd9d6dd7b1f6d7deee5";
hash = "sha256-U17LlN6aGUKUFnT4XyYXppRN+TvUBIBRHEUsfeIiGOw=";
# Change the argument src with the git src that you actually need
src = fetchFromGitLab {
domain = "git.pleroma.social";
group = "pleroma";
owner = "elixir-libraries";
repo = "prometheus.ex";
rev = "a4e9beb3c1c479d14b352fd9d6dd7b1f6d7deee5";
hash = "sha256-U17LlN6aGUKUFnT4XyYXppRN+TvUBIBRHEUsfeIiGOw=";
};
# you can re-use the same beamDeps argument as generated
beamDeps = with final; [ prometheus ];
};
# you can re-use the same beamDeps argument as generated
beamDeps = with final; [ prometheus ];
};
});
}
);
};
}
```
@ -195,15 +200,21 @@ let
hash = lib.fakeHash;
mixEnv = ""; # default is "prod", when empty includes all dependencies, such as "dev", "test".
# if you have build time environment variables add them here
MY_ENV_VAR="my_value";
MY_ENV_VAR = "my_value";
};
nodeDependencies = (pkgs.callPackage ./assets/default.nix { }).shell.nodeDependencies;
in packages.mixRelease {
inherit src pname version mixFodDeps;
in
packages.mixRelease {
inherit
src
pname
version
mixFodDeps
;
# if you have build time environment variables add them here
MY_ENV_VAR="my_value";
MY_ENV_VAR = "my_value";
postBuild = ''
ln -sf ${nodeDependencies}/lib/node_modules assets/node_modules
@ -231,7 +242,12 @@ In order to create a service with your release, you could add a `service.nix`
in your project with the following
```nix
{config, pkgs, lib, ...}:
{
config,
pkgs,
lib,
...
}:
let
release = pkgs.callPackage ./default.nix;
@ -241,10 +257,16 @@ in
{
systemd.services.${release_name} = {
wantedBy = [ "multi-user.target" ];
after = [ "network.target" "postgresql.service" ];
after = [
"network.target"
"postgresql.service"
];
# note that if you are connecting to a postgres instance on a different host
# postgresql.service should not be included in the requires.
requires = [ "network-online.target" "postgresql.service" ];
requires = [
"network-online.target"
"postgresql.service"
];
description = "my app";
environment = {
# RELEASE_TMP is used to write the state of the
@ -292,7 +314,9 @@ in
Usually, we need to create a `shell.nix` file and do our development inside of the environment specified therein. Just install your version of Erlang and any other interpreters, and then use your normal build tools. As an example with Elixir:
```nix
{ pkgs ? import <nixpkgs> {} }:
{
pkgs ? import <nixpkgs> { },
}:
with pkgs;
let
@ -311,12 +335,14 @@ If you need to use an overlay to change some attributes of a derivation, e.g. if
```nix
let
elixir_1_18_1_overlay = (self: super: {
elixir_1_18_1_overlay = (
self: super: {
elixir_1_18 = super.elixir_1_18.override {
version = "1.18.1";
sha256 = "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
};
});
}
);
pkgs = import <nixpkgs> { overlays = [ elixir_1_18_1_overlay ]; };
in
with pkgs;
@ -349,9 +375,7 @@ let
nodePackages.prettier
];
inputs = basePackages ++ lib.optionals stdenv.hostPlatform.isLinux [ inotify-tools ]
++ lib.optionals stdenv.hostPlatform.isDarwin
(with darwin.apple_sdk.frameworks; [ CoreFoundation CoreServices ]);
inputs = basePackages ++ lib.optionals stdenv.hostPlatform.isLinux [ inotify-tools ];
# define shell startup command
hooks = ''
@ -380,7 +404,8 @@ let
export ENV_VAR="your_env_var"
'';
in mkShell {
in
mkShell {
buildInputs = inputs;
shellHook = hooks;
}

View file

@ -24,11 +24,15 @@ Running `bower2nix` will produce something like the following output:
```nix
{ fetchbower, buildEnv }:
buildEnv { name = "bower-env"; ignoreCollisions = true; paths = [
(fetchbower "angular" "1.5.3" "~1.5.0" "1749xb0firxdra4rzadm4q9x90v6pzkbd7xmcyjk6qfza09ykk9y")
(fetchbower "bootstrap" "3.3.6" "~3.3.6" "1vvqlpbfcy0k5pncfjaiskj3y6scwifxygfqnw393sjfxiviwmbv")
(fetchbower "jquery" "2.2.2" "1.9.1 - 2" "10sp5h98sqwk90y4k6hbdviwqzvzwqf47r3r51pakch5ii2y7js1")
]; }
buildEnv {
name = "bower-env";
ignoreCollisions = true;
paths = [
(fetchbower "angular" "1.5.3" "~1.5.0" "1749xb0firxdra4rzadm4q9x90v6pzkbd7xmcyjk6qfza09ykk9y")
(fetchbower "bootstrap" "3.3.6" "~3.3.6" "1vvqlpbfcy0k5pncfjaiskj3y6scwifxygfqnw393sjfxiviwmbv")
(fetchbower "jquery" "2.2.2" "1.9.1 - 2" "10sp5h98sqwk90y4k6hbdviwqzvzwqf47r3r51pakch5ii2y7js1")
];
}
```
Using the `bower2nix` command line arguments, the output can be redirected to a file. A name like `bower-packages.nix` would be fine.
@ -80,8 +84,12 @@ gulp.task('build', [], function () {
### Example Full example — default.nix {#ex-buildBowerComponentsDefaultNix}
```nix
{ myWebApp ? { outPath = ./.; name = "myWebApp"; }
, pkgs ? import <nixpkgs> {}
{
myWebApp ? {
outPath = ./.;
name = "myWebApp";
},
pkgs ? import <nixpkgs> { },
}:
pkgs.stdenv.mkDerivation {
@ -90,16 +98,24 @@ pkgs.stdenv.mkDerivation {
buildInputs = [ pkgs.nodePackages.gulp ];
bowerComponents = pkgs.buildBowerComponents { # note 1
bowerComponents = pkgs.buildBowerComponents {
# note 1
name = "my-web-app";
generated = ./bower-packages.nix;
src = myWebApp;
};
nativeBuildInputs = [
writableTmpDirAsHomeHook # note 3
];
buildPhase = ''
runHook preBuild
cp --reflink=auto --no-preserve=mode -R $bowerComponents/bower_components . # note 2
export HOME=$PWD # note 3
${pkgs.nodePackages.gulp}/bin/gulp build # note 4
runHook postBuild
'';
installPhase = "mv gulpdist $out";

View file

@ -60,19 +60,23 @@ all the other eggs:
```nix
let
myChickenPackages = pkgs.chickenPackages.overrideScope (self: super: {
myChickenPackages = pkgs.chickenPackages.overrideScope (
self: super: {
# The chicken package itself can be overridden to effect the whole ecosystem.
# chicken = super.chicken.overrideAttrs {
# src = ...
# };
chickenEggs = super.chickenEggs.overrideScope (eggself: eggsuper: {
srfi-180 = eggsuper.srfi-180.overrideAttrs {
# path to a local copy of srfi-180
src = <...>;
};
});
});
chickenEggs = super.chickenEggs.overrideScope (
eggself: eggsuper: {
srfi-180 = eggsuper.srfi-180.overrideAttrs {
# path to a local copy of srfi-180
src = <...>;
};
}
);
}
);
in
# Here, `myChickenPackages.chickenEggs.json-rpc`, which depends on `srfi-180` will use
# the local copy of `srfi-180`.

View file

@ -54,35 +54,78 @@ It also takes other standard `mkDerivation` attributes, they are added as such,
Here is a simple package example. It is a pure Coq library, thus it depends on Coq. It builds on the Mathematical Components library, thus it also takes some `mathcomp` derivations as `extraBuildInputs`.
```nix
{ lib, mkCoqDerivation, version ? null
, coq, mathcomp, mathcomp-finmap, mathcomp-bigenough }:
{
lib,
mkCoqDerivation,
version ? null,
coq,
mathcomp,
mathcomp-finmap,
mathcomp-bigenough,
}:
mkCoqDerivation {
/* namePrefix leads to e.g. `name = coq8.11-mathcomp1.11-multinomials-1.5.2` */
namePrefix = [ "coq" "mathcomp" ];
# namePrefix leads to e.g. `name = coq8.11-mathcomp1.11-multinomials-1.5.2`
namePrefix = [
"coq"
"mathcomp"
];
pname = "multinomials";
owner = "math-comp";
inherit version;
defaultVersion = with lib.versions; lib.switch [ coq.version mathcomp.version ] [
{ cases = [ (range "8.7" "8.12") (isEq "1.11") ]; out = "1.5.2"; }
{ cases = [ (range "8.7" "8.11") (range "1.8" "1.10") ]; out = "1.5.0"; }
{ cases = [ (range "8.7" "8.10") (range "1.8" "1.10") ]; out = "1.4"; }
{ cases = [ (isEq "8.6") (range "1.6" "1.7") ]; out = "1.1"; }
] null;
defaultVersion =
with lib.versions;
lib.switch
[ coq.version mathcomp.version ]
[
{
cases = [
(range "8.7" "8.12")
(isEq "1.11")
];
out = "1.5.2";
}
{
cases = [
(range "8.7" "8.11")
(range "1.8" "1.10")
];
out = "1.5.0";
}
{
cases = [
(range "8.7" "8.10")
(range "1.8" "1.10")
];
out = "1.4";
}
{
cases = [
(isEq "8.6")
(range "1.6" "1.7")
];
out = "1.1";
}
]
null;
release = {
"1.5.2".hash = "sha256-mjCx9XKa38Nz9E6wNK7YSqHdJ7YTua5fD3d6J4e7WpU=";
"1.5.1".hash = "sha256-Q8tm0y2FQAt2V1kZYkDlHWRia/lTvXAMVjdmzEV11I4=";
"1.5.0".hash = "sha256-HIK0f21G69oEW8JG46gSBde/Q2LR3GiBCv680gHbmRg=";
"1.5.0".rev = "1.5";
"1.4".hash = "sha256-F9g3MSIr3B6UZ3p8QWjz3/Jpw9sudJ+KRlvjiHSO024=";
"1.3".hash = "sha256-BPJTlAL0ETHvLMBslE0KFVt3DNoaGuMrHt2SBGyJe1A=";
"1.2".hash = "sha256-mHXBXSLYO4BN+jfN50y/+XCx0Qq5g4Ac2Y/qlsbgAdY=";
"1.1".hash = "sha256-ejAsMQbB/LtU9j+g160VdGXULrCe9s0gBWzyhKqmCuE=";
"1.0".hash = "sha256-tZTOltEBBKWciDxDMs/Ye4Jnq/33CANrHJ4FBMPtq+I=";
"1.5.0".rev = "1.5";
"1.4".hash = "sha256-F9g3MSIr3B6UZ3p8QWjz3/Jpw9sudJ+KRlvjiHSO024=";
"1.3".hash = "sha256-BPJTlAL0ETHvLMBslE0KFVt3DNoaGuMrHt2SBGyJe1A=";
"1.2".hash = "sha256-mHXBXSLYO4BN+jfN50y/+XCx0Qq5g4Ac2Y/qlsbgAdY=";
"1.1".hash = "sha256-ejAsMQbB/LtU9j+g160VdGXULrCe9s0gBWzyhKqmCuE=";
"1.0".hash = "sha256-tZTOltEBBKWciDxDMs/Ye4Jnq/33CANrHJ4FBMPtq+I=";
};
propagatedBuildInputs =
[ mathcomp.ssreflect mathcomp.algebra mathcomp-finmap mathcomp-bigenough ];
propagatedBuildInputs = [
mathcomp.ssreflect
mathcomp.algebra
mathcomp-finmap
mathcomp-bigenough
];
meta = {
description = "Coq/SSReflect Library for Monoidal Rings and Multinomials";
@ -124,12 +167,10 @@ The `overrideCoqDerivation` function lets you easily change arguments to `mkCoqD
For example, here is how you could locally add a new release of the `multinomials` library, and set the `defaultVersion` to use this release:
```nix
coqPackages.lib.overrideCoqDerivation
{
defaultVersion = "2.0";
release."2.0".hash = "sha256-czoP11rtrIM7+OLdMisv2EF7n/IbGuwFxHiPtg3qCNM=";
}
coqPackages.multinomials
coqPackages.lib.overrideCoqDerivation {
defaultVersion = "2.0";
release."2.0".hash = "sha256-czoP11rtrIM7+OLdMisv2EF7n/IbGuwFxHiPtg3qCNM=";
} coqPackages.multinomials
```
### `.overrideAttrs` {#coq-overrideAttrs}
@ -140,8 +181,10 @@ For instance, here is how you could add some code to be performed in the derivat
```nix
coqPackages.multinomials.overrideAttrs (oldAttrs: {
postInstall = oldAttrs.postInstall or "" + ''
echo "you can do anything you want here"
'';
postInstall =
oldAttrs.postInstall or ""
+ ''
echo "you can do anything you want here"
'';
})
```

View file

@ -18,7 +18,7 @@ This should have generated a `shards.nix` file.
Next create a Nix file for your derivation and use `pkgs.crystal.buildCrystalPackage` as follows:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
crystal.buildCrystalPackage rec {
pname = "mint";
version = "0.5.0";
@ -51,14 +51,17 @@ Additionally you can override the default `crystal build` options (which are cur
```nix
{
crystalBinaries.mint.options = [ "--release" "--verbose" ];
crystalBinaries.mint.options = [
"--release"
"--verbose"
];
}
```
Depending on the project, you might need additional steps to get it to compile successfully. In Mint's case, we need to link against openssl, so in the end the Nix file looks as follows:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
crystal.buildCrystalPackage rec {
version = "0.5.0";
pname = "mint";

View file

@ -12,11 +12,13 @@ compatible are available as well. For example, there can be a
To use one or more CUDA packages in an expression, give the expression a `cudaPackages` parameter, and in case CUDA is optional
```nix
{ config
, cudaSupport ? config.cudaSupport
, cudaPackages ? { }
, ...
}: {}
{
config,
cudaSupport ? config.cudaSupport,
cudaPackages ? { },
...
}:
{ }
```
When using `callPackage`, you can choose to pass in a different variant, e.g.
@ -32,11 +34,15 @@ package set to make it the default. This guarantees you get a consistent package
set.
```nix
{
mypkg = let
cudaPackages = cudaPackages_11_5.overrideScope (final: prev: {
cudnn = prev.cudnn_8_3;
});
in callPackage { inherit cudaPackages; };
mypkg =
let
cudaPackages = cudaPackages_11_5.overrideScope (
final: prev: {
cudnn = prev.cudnn_8_3;
}
);
in
callPackage { inherit cudaPackages; };
}
```

View file

@ -27,13 +27,11 @@ Nixpkgs provides a `pkgs.writeCueValidator` helper, which will write a validatio
Here is an example:
```nix
pkgs.writeCueValidator
(pkgs.writeText "schema.cue" ''
#Def1: {
field1: string
}
'')
{ document = "#Def1"; }
pkgs.writeCueValidator (pkgs.writeText "schema.cue" ''
#Def1: {
field1: string
}
'') { document = "#Def1"; }
```
- The first parameter is the Cue schema file.
@ -43,19 +41,19 @@ pkgs.writeCueValidator
Another example, given the following `validator.nix` :
```nix
{ pkgs ? import <nixpkgs> {} }:
{
pkgs ? import <nixpkgs> { },
}:
let
genericValidator = version:
pkgs.writeCueValidator
(pkgs.writeText "schema.cue" ''
genericValidator =
version:
pkgs.writeCueValidator (pkgs.writeText "schema.cue" ''
#Version1: {
field1: string
}
#Version2: #Version1 & {
field1: "unused"
}''
)
{ document = "#Version${toString version}"; };
}'') { document = "#Version${toString version}"; };
in
{
validateV1 = genericValidator 1;

View file

@ -30,7 +30,11 @@ The `dart` commands run can be overridden through `pubGetScript` and `dartCompil
Dart supports multiple [outputs types](https://dart.dev/tools/dart-compile#types-of-output), you can choose between them using `dartOutputType` (defaults to `exe`). If you want to override the binaries path or the source path they come from, you can use `dartEntryPoints`. Outputs that require a runtime will automatically be wrapped with the relevant runtime (`dartaotruntime` for `aot-snapshot`, `dart run` for `jit-snapshot` and `kernel`, `node` for `js`), this can be overridden through `dartRuntimeCommand`.
```nix
{ lib, buildDartApplication, fetchFromGitHub }:
{
lib,
buildDartApplication,
fetchFromGitHub,
}:
buildDartApplication rec {
pname = "dart-sass";
@ -38,8 +42,8 @@ buildDartApplication rec {
src = fetchFromGitHub {
owner = "sass";
repo = pname;
rev = version;
repo = "dart-sass";
tag = version;
hash = "sha256-U6enz8yJcc4Wf8m54eYIAnVg/jsGi247Wy8lp1r1wg4=";
};
@ -101,7 +105,7 @@ See the [Dart documentation](#ssec-dart-applications) for more details on requir
`flutter` in Nixpkgs always points to `flutterPackages.stable`, which is the latest packaged version. To avoid unforeseen breakage during upgrade, packages in Nixpkgs should use a specific flutter version, such as `flutter319` and `flutter322`, instead of using `flutter` directly.
```nix
{ flutter322, fetchFromGitHub }:
{ flutter322, fetchFromGitHub }:
flutter322.buildFlutterApplication {
pname = "firmware-updater";

View file

@ -90,7 +90,7 @@ buildDhallPackage {
let
nixpkgs = builtins.fetchTarball {
url = "https://github.com/NixOS/nixpkgs/archive/94b2848559b12a8ed1fe433084686b2a81123c99.tar.gz";
url = "https://github.com/NixOS/nixpkgs/archive/94b2848559b12a8ed1fe433084686b2a81123c99.tar.gz";
hash = "sha256-B4Q3c6IvTLg3Q92qYa8y+i4uTaphtFdjp+Ir3QQjdN0=";
};
@ -100,15 +100,17 @@ let
overlay = self: super: {
dhallPackages = super.dhallPackages.override (old: {
overrides =
self.lib.composeExtensions (old.overrides or (_: _: {})) dhallOverlay;
overrides = self.lib.composeExtensions (old.overrides or (_: _: { })) dhallOverlay;
});
};
pkgs = import nixpkgs { config = {}; overlays = [ overlay ]; };
pkgs = import nixpkgs {
config = { };
overlays = [ overlay ];
};
in
pkgs
pkgs
```
… which we can then build using this command:
@ -190,8 +192,7 @@ Dhall overlay like this:
{
dhallOverrides = self: super: {
# Enable source for all Dhall packages
buildDhallPackage =
args: super.buildDhallPackage (args // { source = true; });
buildDhallPackage = args: super.buildDhallPackage (args // { source = true; });
true = self.callPackage ./true.nix { };
};

View file

@ -22,7 +22,7 @@ buildDubPackage rec {
src = fetchFromGitHub {
owner = "CyberShadow";
repo = "btdu";
rev = "v${version}";
tag = "v${version}";
hash = "sha256-3sSZq+5UJH02IO0Y1yL3BLHDb4lk8k6awb5ZysBQciE=";
};

View file

@ -6,7 +6,7 @@ For local development, it's recommended to use nix-shell to create a dotnet envi
```nix
# shell.nix
with import <nixpkgs> {};
with import <nixpkgs> { };
mkShell {
name = "dotnet-env";
@ -21,15 +21,18 @@ mkShell {
It's very likely that more than one sdk will be needed on a given project. Dotnet provides several different frameworks (E.g dotnetcore, aspnetcore, etc.) as well as many versions for a given framework. Normally, dotnet is able to fetch a framework and install it relative to the executable. However, this would mean writing to the nix store in nixpkgs, which is read-only. To support the many-sdk use case, one can compose an environment using `dotnetCorePackages.combinePackages`:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
mkShell {
name = "dotnet-env";
packages = [
(with dotnetCorePackages; combinePackages [
sdk_8_0
sdk_9_0
])
(
with dotnetCorePackages;
combinePackages [
sdk_8_0
sdk_9_0
]
)
];
}
```
@ -137,11 +140,19 @@ When packaging a new application, you need to fetch its dependencies. Create an
Here is an example `default.nix`, using some of the previously discussed arguments:
```nix
{ lib, buildDotnetModule, dotnetCorePackages, ffmpeg }:
{
lib,
buildDotnetModule,
dotnetCorePackages,
ffmpeg,
}:
let
referencedProject = import ../../bar { /* ... */ };
in buildDotnetModule rec {
referencedProject = import ../../bar {
# ...
};
in
buildDotnetModule rec {
pname = "someDotnetApplication";
version = "0.1";
@ -156,7 +167,7 @@ in buildDotnetModule rec {
dotnet-runtime = dotnetCorePackages.runtime_8_0;
executables = [ "foo" ]; # This wraps "$out/lib/$pname/foo" to `$out/bin/foo`.
executables = []; # Don't install any executables.
executables = [ ]; # Don't install any executables.
packNupkg = true; # This packs the project as "foo-0.1.nupkg" at `$out/share`.

View file

@ -41,56 +41,75 @@ One advantage is that when `pkgs.zlib` is updated, it will automatically update
(pkgs.zlib.override {
stdenv = pkgs.emscriptenStdenv;
}).overrideAttrs
(old: rec {
buildInputs = old.buildInputs ++ [ pkg-config ];
# we need to reset this setting!
env = (old.env or { }) // { NIX_CFLAGS_COMPILE = ""; };
configurePhase = ''
# FIXME: Some tests require writing at $HOME
HOME=$TMPDIR
runHook preConfigure
(old: {
buildInputs = old.buildInputs ++ [ pkg-config ];
# we need to reset this setting!
env = (old.env or { }) // {
NIX_CFLAGS_COMPILE = "";
};
#export EMCC_DEBUG=2
emconfigure ./configure --prefix=$out --shared
configurePhase = ''
# FIXME: Some tests require writing at $HOME
HOME=$TMPDIR
runHook preConfigure
runHook postConfigure
'';
dontStrip = true;
outputs = [ "out" ];
buildPhase = ''
emmake make
'';
installPhase = ''
emmake make install
'';
checkPhase = ''
echo "================= testing zlib using node ================="
#export EMCC_DEBUG=2
emconfigure ./configure --prefix=$out --shared
echo "Compiling a custom test"
set -x
emcc -O2 -s EMULATE_FUNCTION_POINTER_CASTS=1 test/example.c -DZ_SOLO \
libz.so.${old.version} -I . -o example.js
runHook postConfigure
'';
echo "Using node to execute the test"
${pkgs.nodejs}/bin/node ./example.js
dontStrip = true;
outputs = [ "out" ];
set +x
if [ $? -ne 0 ]; then
echo "test failed for some reason"
exit 1;
else
echo "it seems to work! very good."
fi
echo "================= /testing zlib using node ================="
'';
buildPhase = ''
runHook preBuild
postPatch = pkgs.lib.optionalString pkgs.stdenv.hostPlatform.isDarwin ''
substituteInPlace configure \
--replace-fail '/usr/bin/libtool' 'ar' \
--replace-fail 'AR="libtool"' 'AR="ar"' \
--replace-fail 'ARFLAGS="-o"' 'ARFLAGS="-r"'
'';
})
emmake make
runHook postBuild
'';
installPhase = ''
runHook preInstall
emmake make install
runHook postInstall
'';
checkPhase = ''
runHook preCheck
echo "================= testing zlib using node ================="
echo "Compiling a custom test"
set -x
emcc -O2 -s EMULATE_FUNCTION_POINTER_CASTS=1 test/example.c -DZ_SOLO \
libz.so.${old.version} -I . -o example.js
echo "Using node to execute the test"
${pkgs.nodejs}/bin/node ./example.js
set +x
if [ $? -ne 0 ]; then
echo "test failed for some reason"
exit 1;
else
echo "it seems to work! very good."
fi
echo "================= /testing zlib using node ================="
runHook postCheck
'';
postPatch = pkgs.lib.optionalString pkgs.stdenv.hostPlatform.isDarwin ''
substituteInPlace configure \
--replace-fail '/usr/bin/libtool' 'ar' \
--replace-fail 'AR="libtool"' 'AR="ar"' \
--replace-fail 'ARFLAGS="-o"' 'ARFLAGS="-r"'
'';
})
```
:::{.example #usage-2-pkgs.buildemscriptenpackage}
@ -100,11 +119,27 @@ One advantage is that when `pkgs.zlib` is updated, it will automatically update
This `xmlmirror` example features an Emscripten package that is defined completely from this context and no `pkgs.zlib.override` is used.
```nix
pkgs.buildEmscriptenPackage rec {
name = "xmlmirror";
pkgs.buildEmscriptenPackage {
pname = "xmlmirror";
version = "1.2.3";
buildInputs = [ pkg-config autoconf automake libtool gnumake libxml2 nodejs openjdk json_c ];
nativeBuildInputs = [ pkg-config zlib ];
buildInputs = [
pkg-config
autoconf
automake
libtool
gnumake
libxml2
nodejs
openjdk
json_c
];
nativeBuildInputs = [
pkg-config
writableTmpDirAsHomeHook
zlib
];
src = pkgs.fetchgit {
url = "https://gitlab.com/odfplugfest/xmlmirror.git";
@ -113,6 +148,8 @@ pkgs.buildEmscriptenPackage rec {
};
configurePhase = ''
runHook preConfigure
rm -f fastXmlLint.js*
# a fix for ERROR:root:For asm.js, TOTAL_MEMORY must be a multiple of 16MB, was 234217728
# https://gitlab.com/odfplugfest/xmlmirror/issues/8
@ -122,16 +159,26 @@ pkgs.buildEmscriptenPackage rec {
sed -e "s/\$(JSONC_LDFLAGS) \$(ZLIB_LDFLAGS) \$(LIBXML20_LDFLAGS)/\$(JSONC_LDFLAGS) \$(LIBXML20_LDFLAGS) \$(ZLIB_LDFLAGS) /g" -i Makefile.emEnv
# https://gitlab.com/odfplugfest/xmlmirror/issues/11
sed -e "s/-o fastXmlLint.js/-s EXTRA_EXPORTED_RUNTIME_METHODS='[\"ccall\", \"cwrap\"]' -o fastXmlLint.js/g" -i Makefile.emEnv
runHook postConfigure
'';
buildPhase = ''
HOME=$TMPDIR
runHook preBuild
make -f Makefile.emEnv
runHook postBuild
'';
outputs = [ "out" "doc" ];
outputs = [
"out"
"doc"
];
installPhase = ''
runHook preInstall
mkdir -p $out/share
mkdir -p $doc/share/${name}
@ -145,9 +192,13 @@ pkgs.buildEmscriptenPackage rec {
cp *.json $out/share
cp *.rng $out/share
cp README.md $doc/share/${name}
runHook postInstall
'';
checkPhase = ''
checkPhase = ''
runHook preCheck
runHook postCheck
'';
}
```

View file

@ -125,7 +125,7 @@ factorPackages.buildFactorApplication (finalAttrs: {
version = "1.0";
src = fetchurl {
url = "https://some-forge.org/foo-${finalAttrs.version}.tar.gz"
url = "https://some-forge.org/foo-${finalAttrs.version}.tar.gz";
};
})
```

View file

@ -96,7 +96,12 @@ Given the requirements above, the package expression would become messy quickly:
--prefix XDG_DATA_DIRS : "$out/share/gsettings-schemas/${name}" \
--prefix XDG_DATA_DIRS : "${gsettings-desktop-schemas}/share/gsettings-schemas/${gsettings-desktop-schemas.name}" \
--prefix XDG_DATA_DIRS : "${hicolor-icon-theme}/share" \
--prefix GI_TYPELIB_PATH : "${lib.makeSearchPath "lib/girepository-1.0" [ pango json-glib ]}"
--prefix GI_TYPELIB_PATH : "${
lib.makeSearchPath "lib/girepository-1.0" [
pango
json-glib
]
}"
done
'';
}
@ -209,7 +214,7 @@ stdenv.mkDerivation {
You can rely on applications depending on the library setting the necessary environment variables but that is often easy to miss. Instead we recommend to patch the paths in the source code whenever possible. Here are some examples:
- []{#ssec-gnome-common-issues-unwrappable-package-gnome-shell-ext} [Replacing a `GI_TYPELIB_PATH` in GNOME Shell extension](https://github.com/NixOS/nixpkgs/blob/7bb8f05f12ca3cff9da72b56caa2f7472d5732bc/pkgs/desktops/gnome-3/core/gnome-shell-extensions/default.nix#L21-L24) we are using `substituteAll` to include the path to a typelib into a patch.
- []{#ssec-gnome-common-issues-unwrappable-package-gnome-shell-ext} [Replacing a `GI_TYPELIB_PATH` in GNOME Shell extension](https://github.com/NixOS/nixpkgs/blob/e981466fbb08e6231a1377539ff17fbba3270fda/pkgs/by-name/gn/gnome-shell-extensions/package.nix#L25-L32) we are using `replaceVars` to include the path to a typelib into a patch.
- []{#ssec-gnome-common-issues-unwrappable-package-gsettings} The following examples are hardcoding GSettings schema paths. To get the schema paths we use the functions
@ -217,7 +222,7 @@ You can rely on applications depending on the library setting the necessary envi
* `glib.makeSchemaPath` Takes a package output like `$out` and a derivation name. You should use this if the schemas you need to hardcode are in the same derivation.
[]{#ssec-gnome-common-issues-unwrappable-package-gsettings-vala} [Hard-coding GSettings schema path in Vala plug-in (dynamically loaded library)](https://github.com/NixOS/nixpkgs/blob/7bb8f05f12ca3cff9da72b56caa2f7472d5732bc/pkgs/desktops/pantheon/apps/elementary-files/default.nix#L78-L86) here, `substituteAll` cannot be used since the schema comes from the same package preventing us from pass its path to the function, probably due to a [Nix bug](https://github.com/NixOS/nix/issues/1846).
[]{#ssec-gnome-common-issues-unwrappable-package-gsettings-vala} [Hard-coding GSettings schema path in Vala plug-in (dynamically loaded library)](https://github.com/NixOS/nixpkgs/blob/7bb8f05f12ca3cff9da72b56caa2f7472d5732bc/pkgs/desktops/pantheon/apps/elementary-files/default.nix#L78-L86) here, `replaceVars` cannot be used since the schema comes from the same package preventing us from pass its path to the function, probably due to a [Nix bug](https://github.com/NixOS/nix/issues/1846).
[]{#ssec-gnome-common-issues-unwrappable-package-gsettings-c} [Hard-coding GSettings schema path in C library](https://github.com/NixOS/nixpkgs/blob/29c120c065d03b000224872251bed93932d42412/pkgs/development/libraries/glib-networking/default.nix#L31-L34) nothing special other than using [Coccinelle patch](https://github.com/NixOS/nixpkgs/pull/67957#issuecomment-527717467) to generate the patch itself.

View file

@ -13,14 +13,14 @@ The following is an example expression using `buildGoModule`:
```nix
{
pet = buildGoModule rec {
pet = buildGoModule (finalAttrs: {
pname = "pet";
version = "0.3.4";
src = fetchFromGitHub {
owner = "knqyf263";
repo = "pet";
rev = "v${version}";
tag = "v${finalAttrs.version}";
hash = "sha256-Gjw1dRrgM8D3G7v6WIM2+50r4HmTXvx0Xxme2fH9TlQ=";
};
@ -32,7 +32,7 @@ The following is an example expression using `buildGoModule`:
license = lib.licenses.mit;
maintainers = with lib.maintainers; [ kalbasit ];
};
};
});
}
```
@ -188,6 +188,13 @@ Whether the build result should be allowed to contain references to the Go tool
Defaults to `false`
### `goSum` {#var-go-goSum}
Specifies the contents of the `go.sum` file and triggers rebuilds when it changes. This helps combat inconsistent dependency errors on `go.sum` changes.
Defaults to `null`
## Overriding `goModules` {#buildGoModule-goModules-override}
Overriding `<pkg>.goModules` by calling `goModules.overrideAttrs` is unsupported. Still, it is possible to override the `vendorHash` (`goModules`'s `outputHash`) and the `pre`/`post` hooks for both the build and patch phases of the primary and `goModules` derivation.

View file

@ -21,7 +21,10 @@ stdenv.mkDerivation (finalAttrs: {
hash = "sha256-ciKotTHSEcITfQYKFZ6sY2LZnXGChBJy0+eno8B3YHY=";
};
nativeBuildInputs = [ gradle makeWrapper ];
nativeBuildInputs = [
gradle
makeWrapper
];
# if the package has dependencies, mitmCache must be set
mitmCache = gradle.fetchDeps {
@ -72,11 +75,12 @@ The first is to add the derivation arguments required for getting the
package. Using the pdftk example above:
```nix
{ lib
, stdenv
, gradle
# ...
, pdftk
{
lib,
stdenv,
gradle,
# ...
pdftk,
}:
stdenv.mkDerivation (finalAttrs: {

View file

@ -25,7 +25,8 @@ The following attributes are accepted by `hareHook`:
hareHook,
lib,
stdenv,
}: stdenv.mkDerivation {
}:
stdenv.mkDerivation {
pname = "<name>";
version = "<version>";
src = "<src>";

View file

@ -58,7 +58,7 @@ Each of those compiler versions has a corresponding attribute set `packages` bui
it. However, the non-standard package sets are not tested regularly and, as a
result, contain fewer working packages. The corresponding package set for GHC
9.4.8 is `haskell.packages.ghc948`. In fact `haskellPackages` (at the time of writing) is just an alias
for `haskell.packages.ghc966`:
for `haskell.packages.ghc984`:
Every package set also re-exposes the GHC used to build its packages as `haskell.packages.*.ghc`.
@ -297,8 +297,8 @@ Defaults to `false`.
: Whether to build (HTML) documentation using [haddock][haddock].
Defaults to `true` if supported.
`testTarget`
: Name of the test suite to build and run. If unset, all test suites will be executed.
`testTargets`
: Names of the test suites to build and run. If unset, all test suites will be executed.
`preCompileBuildDriver`
: Shell code to run before compiling `Setup.hs`.
@ -487,7 +487,7 @@ so:
```nix
let
pkgs = import <nixpkgs> {};
pkgs = import <nixpkgs> { };
inherit (pkgs) haskell;
inherit (haskell.lib.compose) overrideCabal;
@ -511,7 +511,7 @@ let
previousIntermediates = turtle-full-build-with-incremental-output.intermediates;
}) turtle;
in
turtle-incremental-build
turtle-incremental-build
```
## Development environments {#haskell-development-environments}
@ -590,7 +590,9 @@ that:
```nix
# Retrieve nixpkgs impurely from NIX_PATH for now, you can pin it instead, of course.
{ pkgs ? import <nixpkgs> {} }:
{
pkgs ? import <nixpkgs> { },
}:
# use the nixpkgs default haskell package set
pkgs.haskellPackages.callPackage ./my-project.nix { }
@ -619,6 +621,12 @@ environment. This means you can reuse Nix expressions of packages included in
nixpkgs, but also use local Nix expressions like this: `hpkgs: [
(hpkgs.callPackage ./my-project.nix { }) ]`.
`extraDependencies`
: Extra dependencies, in the form of cabal2nix build attributes. An example use
case is when you have Haskell scripts that use libraries that don't occur in
your packages' dependencies. Example: `hpkgs: {libraryHaskellDepends =
[ hpkgs.releaser ]}`. Defaults to `hpkgs: { }`.
`nativeBuildInputs`
: Expects a list of derivations to add as build tools to the build environment.
This is the place to add packages like `cabal-install`, `doctest` or `hlint`.
@ -654,7 +662,9 @@ Say our example above depends on `distribution-nixpkgs` and we have a project
file set up for both, we can add the following `shell.nix` expression:
```nix
{ pkgs ? import <nixpkgs> {} }:
{
pkgs ? import <nixpkgs> { },
}:
pkgs.haskellPackages.shellFor {
packages = hpkgs: [
@ -703,7 +713,12 @@ linked to work reliably. You can override the list of supported GHC versions
with e.g.
```nix
pkgs.haskell-language-server.override { supportedGhcVersions = [ "90" "94" ]; }
pkgs.haskell-language-server.override {
supportedGhcVersions = [
"90"
"94"
];
}
```
Where all strings `version` are allowed such that
`haskell.packages.ghc${version}` is an existing package set.
@ -764,7 +779,7 @@ that depend on that library, you may want to use:
```nix
haskellPackages.haskell-ci.overrideScope (self: super: {
Cabal = self.Cabal_3_14_1_0;
Cabal = self.Cabal_3_14_2_0;
})
```
@ -886,11 +901,9 @@ for this to work.
derivation:
```nix
pkgs.haskell.lib.overrideCabal
(pkgs.haskell.lib.justStaticExecutables my-haskell-package)
(drv: {
disallowGhcReference = false;
})
pkgs.haskell.lib.overrideCabal (pkgs.haskell.lib.justStaticExecutables my-haskell-package) (drv: {
disallowGhcReference = false;
})
```
Then use `strings` to determine which libraries are responsible:
@ -906,14 +919,12 @@ for this to work.
Finally, use `remove-references-to` to delete those store paths from the produced output:
```nix
pkgs.haskell.lib.overrideCabal
(pkgs.haskell.lib.justStaticExecutables my-haskell-package)
(drv: {
postInstall = ''
${drv.postInstall or ""}
remove-references-to -t ${pkgs.haskellPackages.hs-opentelemetry-sdk}
'';
})
pkgs.haskell.lib.overrideCabal (pkgs.haskell.lib.justStaticExecutables my-haskell-package) (drv: {
postInstall = ''
${drv.postInstall or ""}
remove-references-to -t ${pkgs.haskellPackages.hs-opentelemetry-sdk}
'';
})
```
[164630]: https://github.com/NixOS/nixpkgs/issues/164630
@ -1122,12 +1133,20 @@ Haskell packages using [import from derivation][import-from-derivation].
```nix
# cabal get mtl-2.2.1 && cd mtl-2.2.1 && cabal2nix .
{ mkDerivation, base, lib, transformers }:
{
mkDerivation,
base,
lib,
transformers,
}:
mkDerivation {
pname = "mtl";
version = "2.2.1";
src = ./.;
libraryHaskellDepends = [ base transformers ];
libraryHaskellDepends = [
base
transformers
];
homepage = "http://github.com/ekmett/mtl";
description = "Monad classes, using functional dependencies";
license = lib.licenses.bsd3;
@ -1274,60 +1293,69 @@ in
# recommended to only use such an overlay if you are enabling profiling on a
# platform that doesn't by default, because compiling GHC from scratch is
# quite expensive.
(final: prev:
let
inherit (final) lib;
in
(
final: prev:
let
inherit (final) lib;
in
{
haskell = prev.haskell // {
compiler = prev.haskell.compiler // {
${ghcName} = prev.haskell.compiler.${ghcName}.override {
# Unfortunately, the GHC setting is named differently for historical reasons
enableProfiledLibs = enableProfiling;
};
};
};
})
(final: prev:
let
inherit (final) lib;
haskellLib = final.haskell.lib.compose;
in
{
haskell = prev.haskell // {
packages = prev.haskell.packages // {
${ghcName} = prev.haskell.packages.${ghcName}.override {
overrides = hfinal: hprev: {
mkDerivation = args: hprev.mkDerivation (args // {
# Since we are forcing our ideas upon mkDerivation, this change will
# affect every package in the package set.
enableLibraryProfiling = enableProfiling;
# To actually use profiling on an executable, executable profiling
# needs to be enabled for the executable you want to profile. You
# can either do this globally or…
enableExecutableProfiling = enableProfiling;
});
# …only for the package that contains an executable you want to profile.
# That saves on unnecessary rebuilds for packages that you only depend
# on for their library, but also contain executables (e.g. pandoc).
my-executable = haskellLib.enableExecutableProfiling hprev.my-executable;
# If you are disabling profiling to save on build time, but want to
# retain the ability to substitute from the binary cache. Drop the
# override for mkDerivation above and instead have an override like
# this for the specific packages you are building locally and want
# to make cheaper to build.
my-library = haskellLib.disableLibraryProfiling hprev.my-library;
{
haskell = prev.haskell // {
compiler = prev.haskell.compiler // {
${ghcName} = prev.haskell.compiler.${ghcName}.override {
# Unfortunately, the GHC setting is named differently for historical reasons
enableProfiledLibs = enableProfiling;
};
};
};
};
})
}
)
(
final: prev:
let
inherit (final) lib;
haskellLib = final.haskell.lib.compose;
in
{
haskell = prev.haskell // {
packages = prev.haskell.packages // {
${ghcName} = prev.haskell.packages.${ghcName}.override {
overrides = hfinal: hprev: {
mkDerivation =
args:
hprev.mkDerivation (
args
// {
# Since we are forcing our ideas upon mkDerivation, this change will
# affect every package in the package set.
enableLibraryProfiling = enableProfiling;
# To actually use profiling on an executable, executable profiling
# needs to be enabled for the executable you want to profile. You
# can either do this globally or…
enableExecutableProfiling = enableProfiling;
}
);
# …only for the package that contains an executable you want to profile.
# That saves on unnecessary rebuilds for packages that you only depend
# on for their library, but also contain executables (e.g. pandoc).
my-executable = haskellLib.enableExecutableProfiling hprev.my-executable;
# If you are disabling profiling to save on build time, but want to
# retain the ability to substitute from the binary cache. Drop the
# override for mkDerivation above and instead have an override like
# this for the specific packages you are building locally and want
# to make cheaper to build.
my-library = haskellLib.disableLibraryProfiling hprev.my-library;
};
};
};
};
}
)
]
```

View file

@ -22,10 +22,16 @@ $ nix-shell -p "hy.withPackages (ps: with ps; [ numpy matplotlib ])"
Or if you want to extend your `configuration.nix`:
```nix
{ # ...
{
# ...
environment.systemPackages = with pkgs; [
(hy.withPackages (py-packages: with py-packages; [ numpy matplotlib ]))
(hy.withPackages (
py-packages: with py-packages; [
numpy
matplotlib
]
))
];
}
```

View file

@ -12,7 +12,12 @@ This however only provides the `prelude` and `base` libraries. To install idris
```nix
self: super: {
myIdris = with self.idrisPackages; with-packages [ contrib pruviloj ];
myIdris =
with self.idrisPackages;
with-packages [
contrib
pruviloj
];
}
```
@ -68,13 +73,14 @@ prelude
As an example of how a Nix expression for an Idris package can be created, here is the one for `idrisPackages.yaml`:
```nix
{ lib
, build-idris-package
, fetchFromGitHub
, contrib
, lightyear
{
lib,
build-idris-package,
fetchFromGitHub,
contrib,
lightyear,
}:
build-idris-package {
build-idris-package {
name = "yaml";
version = "2018-01-25";
@ -84,7 +90,10 @@ build-idris-package {
# different from its package name here.
ipkgName = "Yaml";
# Idris dependencies to provide for the build
idrisDeps = [ contrib lightyear ];
idrisDeps = [
contrib
lightyear
];
src = fetchFromGitHub {
owner = "Heather";
@ -111,10 +120,10 @@ $ nix-build -E '(import <nixpkgs> {}).idrisPackages.callPackage ./yaml.nix {}'
Or it's possible to use
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
{
yaml = idrisPackages.callPackage ./yaml.nix {};
yaml = idrisPackages.callPackage ./yaml.nix { };
}
```
@ -134,7 +143,11 @@ For example you could set
```nix
build-idris-package {
idrisBuildOptions = [ "--log" "1" "--verbose" ];
idrisBuildOptions = [
"--log"
"1"
"--verbose"
];
# ...
}

View file

@ -9,39 +9,50 @@ Importantly, `buildIdris` does not create a single derivation but rather an attr
A simple example of a fully packaged library would be the [`LSP-lib`](https://github.com/idris-community/LSP-lib) found in the `idris-community` GitHub organization.
```nix
{ fetchFromGitHub, idris2Packages }:
let lspLibPkg = idris2Packages.buildIdris {
ipkgName = "lsp-lib";
src = fetchFromGitHub {
owner = "idris-community";
repo = "LSP-lib";
rev = "main";
hash = "sha256-EvSyMCVyiy9jDZMkXQmtwwMoLaem1GsKVFqSGNNHHmY=";
let
lspLibPkg = idris2Packages.buildIdris {
ipkgName = "lsp-lib";
src = fetchFromGitHub {
owner = "idris-community";
repo = "LSP-lib";
rev = "main";
hash = "sha256-EvSyMCVyiy9jDZMkXQmtwwMoLaem1GsKVFqSGNNHHmY=";
};
idrisLibraries = [ ];
};
idrisLibraries = [ ];
};
in lspLibPkg.library { withSource = true; }
in
lspLibPkg.library { withSource = true; }
```
The above results in a derivation with the installed library results (with sourcecode).
A slightly more involved example of a fully packaged executable would be the [`idris2-lsp`](https://github.com/idris-community/idris2-lsp) which is an Idris2 language server that uses the `LSP-lib` found above.
```nix
{ callPackage, fetchFromGitHub, idris2Packages }:
{
callPackage,
fetchFromGitHub,
idris2Packages,
}:
# Assuming the previous example lives in `lsp-lib.nix`:
let lspLib = callPackage ./lsp-lib.nix { };
inherit (idris2Packages) idris2Api;
lspPkg = idris2Packages.buildIdris {
ipkgName = "idris2-lsp";
src = fetchFromGitHub {
owner = "idris-community";
repo = "idris2-lsp";
rev = "main";
hash = "sha256-vQTzEltkx7uelDtXOHc6QRWZ4cSlhhm5ziOqWA+aujk=";
};
idrisLibraries = [idris2Api lspLib];
let
lspLib = callPackage ./lsp-lib.nix { };
inherit (idris2Packages) idris2Api;
lspPkg = idris2Packages.buildIdris {
ipkgName = "idris2-lsp";
src = fetchFromGitHub {
owner = "idris-community";
repo = "idris2-lsp";
rev = "main";
hash = "sha256-vQTzEltkx7uelDtXOHc6QRWZ4cSlhhm5ziOqWA+aujk=";
};
in lspPkg.executable
idrisLibraries = [
idris2Api
lspLib
];
};
in
lspPkg.executable
```
The above uses the default value of `withSource = false` for the `idris2Api` but could be modified to include that library's source by passing `(idris2Api { withSource = true; })` to `idrisLibraries` instead. `idris2Api` in the above derivation comes built in with `idris2Packages`. This library exposes many of the otherwise internal APIs of the Idris2 compiler.

View file

@ -98,6 +98,7 @@ scheme.section.md
swift.section.md
tcl.section.md
texlive.section.md
typst.section.md
vim.section.md
neovim.section.md
```

View file

@ -29,7 +29,7 @@ Xcode.
```nix
let
pkgs = import <nixpkgs> {};
pkgs = import <nixpkgs> { };
xcodeenv = import ./xcodeenv {
inherit (pkgs) stdenv;
@ -63,7 +63,7 @@ executing the `xcodeenv.buildApp {}` function:
```nix
let
pkgs = import <nixpkgs> {};
pkgs = import <nixpkgs> { };
xcodeenv = import ./xcodeenv {
inherit (pkgs) stdenv;
@ -159,7 +159,7 @@ instances:
```nix
let
pkgs = import <nixpkgs> {};
pkgs = import <nixpkgs> { };
xcodeenv = import ./xcodeenv {
inherit (pkgs) stdenv;
@ -193,7 +193,7 @@ app in the requested simulator instance:
```nix
let
pkgs = import <nixpkgs> {};
pkgs = import <nixpkgs> { };
xcodeenv = import ./xcodeenv {
inherit (pkgs) stdenv;

View file

@ -7,7 +7,9 @@ stdenv.mkDerivation {
pname = "...";
version = "...";
src = fetchurl { /* ... */ };
src = fetchurl {
# ...
};
nativeBuildInputs = [
ant
@ -95,7 +97,7 @@ let
something = (pkgs.something.override { jre = my_jre; });
other = (pkgs.other.override { jre = my_jre; });
in
<...>
<...>
```
You can also specify what JDK your JRE should be based on, for example
@ -122,7 +124,10 @@ OpenJDK. For instance, to use the GNU Java Compiler:
```nix
{
nativeBuildInputs = [ gcj ant ];
nativeBuildInputs = [
gcj
ant
];
}
```

View file

@ -117,12 +117,19 @@ After you have identified the correct system, you need to override your package
For example, `dat` requires `node-gyp-build`, so we override its expression in [pkgs/development/node-packages/overrides.nix](https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/node-packages/overrides.nix):
```nix
{
dat = prev.dat.override (oldAttrs: {
buildInputs = [ final.node-gyp-build pkgs.libtool pkgs.autoconf pkgs.automake ];
meta = oldAttrs.meta // { broken = since "12"; };
});
}
{
dat = prev.dat.override (oldAttrs: {
buildInputs = [
final.node-gyp-build
pkgs.libtool
pkgs.autoconf
pkgs.automake
];
meta = oldAttrs.meta // {
broken = since "12";
};
});
}
```
### Adding and Updating Javascript packages in nixpkgs {#javascript-adding-or-updating-packages}
@ -185,16 +192,20 @@ It works by utilizing npm's cache functionality -- creating a reproducible cache
Here's an example:
```nix
{ lib, buildNpmPackage, fetchFromGitHub }:
{
lib,
buildNpmPackage,
fetchFromGitHub,
}:
buildNpmPackage rec {
buildNpmPackage (finalAttrs: {
pname = "flood";
version = "4.7.0";
src = fetchFromGitHub {
owner = "jesec";
repo = pname;
rev = "v${version}";
repo = "flood";
tag = "v${finalAttrs.version}";
hash = "sha256-BR+ZGkBBfd0dSQqAvujsbgsEPFYw/ThrylxUbOksYxM=";
};
@ -211,7 +222,7 @@ buildNpmPackage rec {
license = lib.licenses.gpl3Only;
maintainers = with lib.maintainers; [ winter ];
};
}
})
```
In the default `installPhase` set by `buildNpmPackage`, it uses `npm pack --json --dry-run` to decide what files to install in `$out/lib/node_modules/$name/`, where `$name` is the `name` string defined in the package's `package.json`.
@ -323,7 +334,9 @@ buildNpmPackage {
npmRoot = ./.;
fetcherOpts = {
# Pass 'curlOptsList' to 'pkgs.fetchurl' while fetching 'axios'
{ "node_modules/axios" = { curlOptsList = [ "--verbose" ]; }; }
"node_modules/axios" = {
curlOptsList = [ "--verbose" ];
};
};
};
@ -369,6 +382,15 @@ pkgs.mkShell {
```
will create a development shell where a `node_modules` directory is created & packages symlinked to the Nix store when activated.
:::{.note}
Commands like `npm install` & `npm add` that writes packages & executables needs to be used with `--package-lock-only`.
This means `npm` installs dependencies by writing into `package-lock.json` without modifying the `node_modules` folder. Installation happens through reloading the devShell.
This might be best practice since it gives the `nix shell` virtually exclusive ownership over your `node_modules` folder.
It's recommended to set `package-lock-only = true` in your project-local [`.npmrc`](https://docs.npmjs.com/cli/v11/configuring-npm/npmrc).
:::
### corepack {#javascript-corepack}
This package puts the corepack wrappers for pnpm and yarn in your PATH, and they will honor the `packageManager` setting in the `package.json`.
@ -403,14 +425,16 @@ When packaging an application that includes a `pnpm-lock.yaml`, you need to fetc
stdenv,
nodejs,
# This is pinned as { pnpm = pnpm_9; }
pnpm
pnpm,
}:
stdenv.mkDerivation (finalAttrs: {
pname = "foo";
version = "0-unstable-1980-01-01";
src = ...;
src = {
#...
};
nativeBuildInputs = [
nodejs
@ -439,7 +463,9 @@ stdenv.mkDerivation (finalAttrs: {
pname = "foo";
version = "0-unstable-1980-01-01";
src = ...;
src = {
# ...
};
pnpmInstallFlags = [ "--shamefully-hoist" ];
@ -466,14 +492,16 @@ Assuming the following directory structure, we can define `sourceRoot` and `pnpm
```
```nix
...
{
# ...
pnpmDeps = pnpm.fetchDeps {
...
# ...
sourceRoot = "${finalAttrs.src.name}/frontend";
};
# by default the working directory is the extracted source
pnpmRoot = "frontend";
}
```
#### PNPM Workspaces {#javascript-pnpm-workspaces}
@ -484,11 +512,13 @@ which will make PNPM only install dependencies for those workspace packages.
For example:
```nix
...
pnpmWorkspaces = [ "@astrojs/language-server" ];
pnpmDeps = pnpm.fetchDeps {
inherit (finalAttrs) pnpmWorkspaces;
...
{
# ...
pnpmWorkspaces = [ "@astrojs/language-server" ];
pnpmDeps = pnpm.fetchDeps {
inherit (finalAttrs) pnpmWorkspaces;
#...
};
}
```
@ -498,13 +528,15 @@ Note that you do not need to set `sourceRoot` to make this work.
Usually in such cases, you'd want to use `pnpm --filter=<pnpm workspace name> build` to build your project, as `npmHooks.npmBuildHook` probably won't work. A `buildPhase` based on the following example will probably fit most workspace projects:
```nix
buildPhase = ''
runHook preBuild
{
buildPhase = ''
runHook preBuild
pnpm --filter=@astrojs/language-server build
pnpm --filter=@astrojs/language-server build
runHook postBuild
'';
runHook postBuild
'';
}
```
#### Additional PNPM Commands and settings {#javascript-pnpm-extraCommands}
@ -513,13 +545,15 @@ If you require setting an additional PNPM configuration setting (such as `dedupe
set `prePnpmInstall` to the right commands to run. For example:
```nix
prePnpmInstall = ''
pnpm config set dedupe-peer-dependants false
'';
pnpmDeps = pnpm.fetchDeps {
inherit (finalAttrs) prePnpmInstall;
...
};
{
prePnpmInstall = ''
pnpm config set dedupe-peer-dependants false
'';
pnpmDeps = pnpm.fetchDeps {
inherit (finalAttrs) prePnpmInstall;
# ...
};
}
```
In this example, `prePnpmInstall` will be run by both `pnpm.configHook` and by the `pnpm.fetchDeps` builder.
@ -527,7 +561,15 @@ In this example, `prePnpmInstall` will be run by both `pnpm.configHook` and by t
### Yarn {#javascript-yarn}
Yarn based projects use a `yarn.lock` file instead of a `package-lock.json` to pin dependencies. Nixpkgs provides the Nix function `fetchYarnDeps` which fetches an offline cache suitable for running `yarn install` before building the project. In addition, Nixpkgs provides the hooks:
Yarn based projects use a `yarn.lock` file instead of a `package-lock.json` to pin dependencies.
To package yarn-based applications, you need to distinguish by the version pointers in the `yarn.lock` file. See the following sections.
#### Yarn v1 {#javascript-yarn-v1}
Yarn v1 lockfiles contain a comment `# yarn lockfile v1` at the beginning of the file.
Nixpkgs provides the Nix function `fetchYarnDeps` which fetches an offline cache suitable for running `yarn install` before building the project. In addition, Nixpkgs provides the hooks:
- `yarnConfigHook`: Fetches the dependencies from the offline cache and installs them into `node_modules`.
- `yarnBuildHook`: Runs `yarn build` or a specified `yarn` command that builds the project.
@ -577,28 +619,28 @@ stdenv.mkDerivation (finalAttrs: {
})
```
#### `yarnConfigHook` arguments {#javascript-yarnconfighook}
##### `yarnConfigHook` arguments {#javascript-yarnconfighook}
By default, `yarnConfigHook` relies upon the attribute `${yarnOfflineCache}` (or `${offlineCache}` if the former is not set) to find the location of the offline cache produced by `fetchYarnDeps`. To disable this phase, you can set `dontYarnInstallDeps = true` or override the `configurePhase`.
#### `yarnBuildHook` arguments {#javascript-yarnbuildhook}
##### `yarnBuildHook` arguments {#javascript-yarnbuildhook}
This script by default runs `yarn --offline build`, and it relies upon the project's dependencies installed at `node_modules`. Below is a list of additional `mkDerivation` arguments read by this hook:
- `yarnBuildScript`: Sets a different `yarn --offline` subcommand (defaults to `build`).
- `yarnBuildFlags`: Single string list of additional flags to pass the above command, or a Nix list of such additional flags.
#### `yarnInstallHook` arguments {#javascript-yarninstallhook}
##### `yarnInstallHook` arguments {#javascript-yarninstallhook}
To install the package `yarnInstallHook` uses both `npm` and `yarn` to cleanup project files and dependencies. To disable this phase, you can set `dontYarnInstall = true` or override the `installPhase`. Below is a list of additional `mkDerivation` arguments read by this hook:
- `yarnKeepDevDeps`: Disables the removal of devDependencies from `node_modules` before installation.
### yarn2nix {#javascript-yarn2nix}
#### yarn2nix {#javascript-yarn2nix}
WARNING: The `yarn2nix` functions have been deprecated in favor of the new `yarnConfigHook`, `yarnBuildHook` and `yarnInstallHook`. Documentation for them still appears here for the sake of the packages that still use them. See also a tracking issue [#324246](https://github.com/NixOS/nixpkgs/issues/324246).
WARNING: The `yarn2nix` functions have been deprecated in favor of `yarnConfigHook`, `yarnBuildHook` and `yarnInstallHook` (for Yarn v1) and `yarn-berry_*.*` tooling (Yarn v3 and v4). Documentation for `yarn2nix` functions still appears here for the sake of the packages that still use them. See also a tracking issue [#324246](https://github.com/NixOS/nixpkgs/issues/324246).
#### Preparation {#javascript-yarn2nix-preparation}
##### Preparation {#javascript-yarn2nix-preparation}
You will need at least a `yarn.lock` file. If upstream does not have one you need to generate it and reference it in your package definition.
@ -613,7 +655,7 @@ If the downloaded files contain the `package.json` and `yarn.lock` files they ca
}
```
#### mkYarnPackage {#javascript-yarn2nix-mkYarnPackage}
##### mkYarnPackage {#javascript-yarn2nix-mkYarnPackage}
`mkYarnPackage` will by default try to generate a binary. For package only generating static assets (Svelte, Vue, React, WebPack, ...), you will need to explicitly override the build step with your instructions.
@ -621,9 +663,16 @@ It's important to use the `--offline` flag. For example if you script is `"build
```nix
{
nativeBuildInputs = [
writableTmpDirAsHomeHook
];
buildPhase = ''
export HOME=$(mktemp -d)
runHook preBuild
yarn --offline build
runHook postBuild
'';
}
```
@ -657,7 +706,7 @@ or if you need a writeable node_modules directory:
}
```
#### mkYarnModules {#javascript-yarn2nix-mkYarnModules}
##### mkYarnModules {#javascript-yarn2nix-mkYarnModules}
This will generate a derivation including the `node_modules` directory.
If you have to build a derivation for an integrated web framework (rails, phoenix..), this is probably the easiest way.
@ -678,7 +727,11 @@ To fix this we will specify different versions of build inputs to use, as well a
mkYarnPackage rec {
pkgConfig = {
node-sass = {
buildInputs = with final;[ python libsass pkg-config ];
buildInputs = with final; [
python
libsass
pkg-config
];
postInstall = ''
LIBSASS_EXT=auto yarn --offline run build
rm build/config.gypi
@ -688,7 +741,7 @@ mkYarnPackage rec {
}
```
#### Pitfalls {#javascript-yarn2nix-pitfalls}
##### Pitfalls {#javascript-yarn2nix-pitfalls}
- If version is missing from upstream package.json, yarn will silently install nothing. In that case, you will need to override package.json as shown in the [package.json section](#javascript-upstream-package-json)
- Having trouble with `node-gyp`? Try adding these lines to the `yarnPreBuild` steps:
@ -708,6 +761,116 @@ mkYarnPackage rec {
- Exporting the headers in `npm_config_nodedir` comes from this issue: <https://github.com/nodejs/node-gyp/issues/1191#issuecomment-301243919>
- `offlineCache` (described [above](#javascript-yarn2nix-preparation)) must be specified to avoid [Import From Derivation](#ssec-import-from-derivation) (IFD) when used inside Nixpkgs.
#### Yarn Berry v3/v4 {#javascript-yarn-v3-v4}
Yarn Berry (v3 / v4) have similar formats, they start with blocks like these:
```yaml
__metadata:
version: 6
cacheKey: 8[cX]
```
```yaml
__metadata:
version: 8
cacheKey: 10[cX]
```
For these packages, we have some helpers exposed under the respective `yarn-berry_3` and `yarn-berry_4` packages:
- `yarn-berry-fetcher`
- `fetchYarnBerryDeps`
- `yarnBerryConfigHook`
It's recommended to ensure you're explicitly pinning the major version used, for example by capturing the `yarn-berry_Xn` argument and then re-defining it as a `yarn-berry` `let` binding.
```nix
{
stdenv,
nodejs,
yarn-berry_4,
}:
let
yarn-berry = yarn-berry_4;
in
stdenv.mkDerivation (finalAttrs: {
pname = "foo";
version = "0-unstable-1980-01-01";
src = {
#...
};
nativeBuildInputs = [
nodejs
yarn-berry.yarnBerryConfigHook
];
offlineCache = yarn-berry.fetchYarnBerryDeps {
inherit (finalAttrs) src;
hash = "...";
};
})
```
##### `yarn-berry_X.fetchYarnBerryDeps` {#javascript-fetchYarnBerryDeps}
`fetchYarnBerryDeps` runs `yarn-berry-fetcher fetch` in a fixed-output-derivation. It is a custom fetcher designed to reproducibly download all files in the `yarn.lock` file, validating their hashes in the process. For git dependencies, it creates a checkout at `${offlineCache}/checkouts/<40-character-commit-hash>` (relying on the git commit hash to describe the contents of the checkout).
To produce the `hash` argument for `fetchYarnBerryDeps` function call, the `yarn-berry-fetcher prefetch` command can be used:
```console
$ yarn-berry-fetcher prefetch </path/to/yarn.lock> [/path/to/missing-hashes.json]
```
This prints the hash to stdout and can be used in update scripts to recalculate the hash for a new version of `yarn.lock`.
##### `yarn-berry_X.yarnBerryConfigHook` {#javascript-yarnBerryConfigHook}
`yarnBerryConfigHook` uses the store path `offlineCache` points to, to run a `yarn install` during the build, producing a usable `node_modules` directory from the downloaded dependencies.
Internally, this uses a patched version of Yarn to ensure git dependencies are re-packed and any attempted downloads fail immediately.
##### Patching upstream `package.json` or `yarn.lock` files {#javascript-yarnBerry-patching}
In case patching the upstream `package.json` or `yarn.lock` is needed, it's important to pass `finalAttrs.patches` to `fetchYarnBerryDeps` as well, so the patched variants are picked up (i.e. `inherit (finalAttrs) patches`.
##### Missing hashes in the `yarn.lock` file {#javascript-yarnBerry-missing-hashes}
Unfortunately, `yarn.lock` files do not include hashes for optional/platform-specific dependencies. This is [by design](https://github.com/yarnpkg/berry/issues/6759).
To compensate for this, the `yarn-berry-fetcher missing-hashes` subcommand can be used to produce all missing hashes. These are usually stored in a `missing-hashes.json` file, which needs to be passed to both the build itself, as well as the `fetchYarnBerryDeps` helper:
```nix
{
stdenv,
nodejs,
yarn-berry_4,
}:
let
yarn-berry = yarn-berry_4;
in
stdenv.mkDerivation (finalAttrs: {
pname = "foo";
version = "0-unstable-1980-01-01";
src = {
#...
};
nativeBuildInputs = [
nodejs
yarn-berry.yarnBerryConfigHook
];
missingHashes = ./missing-hashes.json;
offlineCache = yarn-berry.fetchYarnBerryDeps {
inherit (finalAttrs) src missingHashes;
hash = "...";
};
})
```
## Outside Nixpkgs {#javascript-outside-nixpkgs}
There are some other tools available, which are written in the Nix language.

View file

@ -19,7 +19,7 @@ This function accepts a list of strings representing Julia package names.
For example, you can build a Julia environment with the `Plots` package as follows.
```nix
julia.withPackages ["Plots"]
julia.withPackages [ "Plots" ]
```
Arguments can be passed using `.override`.
@ -28,7 +28,8 @@ For example:
```nix
(julia.withPackages.override {
precompile = false; # Turn off precompilation
}) ["Plots"]
})
[ "Plots" ]
```
Here's a nice way to run a Julia environment with a shell one-liner:

View file

@ -48,7 +48,8 @@ Also one can create a `pkgs.mkShell` environment in `shell.nix`/`flake.nix`:
```nix
let
sbcl' = sbcl.withPackages (ps: [ ps.alexandria ]);
in mkShell {
in
mkShell {
packages = [ sbcl' ];
}
```
@ -134,7 +135,6 @@ During Quicklisp import:
- names starting with a number have a `_` prepended (`3d-vectors`->`_3d-vectors`)
- `_` in names is converted to `__` for reversibility
## Defining packages manually inside Nixpkgs {#lisp-defining-packages-inside}
Packages that for some reason are not in Quicklisp, and so cannot be
@ -184,14 +184,17 @@ let
domain = "gitlab.common-lisp.net";
owner = "alexandria";
repo = "alexandria";
rev = "v${version}";
tag = "v${version}";
hash = "sha256-1Hzxt65dZvgOFIljjjlSGgKYkj+YBLwJCACi5DZsKmQ=";
};
};
sbcl' = sbcl.withOverrides (self: super: {
inherit alexandria;
});
in sbcl'.pkgs.alexandria
sbcl' = sbcl.withOverrides (
self: super: {
inherit alexandria;
}
);
in
sbcl'.pkgs.alexandria
```
## Overriding package attributes {#lisp-overriding-package-attributes}
@ -208,7 +211,7 @@ sbcl.pkgs.alexandria.overrideLispAttrs (oldAttrs: rec {
domain = "gitlab.common-lisp.net";
owner = "alexandria";
repo = "alexandria";
rev = "v${version}";
tag = "v${version}";
hash = "sha256-1Hzxt65dZvgOFIljjjlSGgKYkj+YBLwJCACi5DZsKmQ=";
};
})
@ -296,6 +299,9 @@ This example wraps CLISP:
wrapLisp {
pkg = clisp;
faslExt = "fas";
flags = ["-E" "UTF8"];
flags = [
"-E"
"UTF8"
];
}
```

View file

@ -27,9 +27,14 @@ Note that nixpkgs patches the non-luajit interpreters to avoid referring to
Create a file, e.g. `build.nix`, with the following expression
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
lua5_2.withPackages (ps: with ps; [ busted luafilesystem ])
lua5_2.withPackages (
ps: with ps; [
busted
luafilesystem
]
)
```
and install it in your profile with
@ -46,11 +51,18 @@ If you prefer to, you could also add the environment as a package override to th
using `config.nix`,
```nix
{ # ...
{
# ...
packageOverrides = pkgs: with pkgs; {
myLuaEnv = lua5_2.withPackages (ps: with ps; [ busted luafilesystem ]);
};
packageOverrides =
pkgs: with pkgs; {
myLuaEnv = lua5_2.withPackages (
ps: with ps; [
busted
luafilesystem
]
);
};
}
```
@ -67,10 +79,16 @@ the `nixpkgs` channel was used.
For the sake of completeness, here's another example how to install the environment system-wide.
```nix
{ # ...
{
# ...
environment.systemPackages = with pkgs; [
(lua.withPackages(ps: with ps; [ busted luafilesystem ]))
(lua.withPackages (
ps: with ps; [
busted
luafilesystem
]
))
];
}
```
@ -80,13 +98,12 @@ For the sake of completeness, here's another example how to install the environm
Use the following overlay template:
```nix
final: prev:
{
final: prev: {
lua = prev.lua.override {
packageOverrides = luaself: luaprev: {
luarocks-nix = luaprev.luarocks-nix.overrideAttrs(oa: {
luarocks-nix = luaprev.luarocks-nix.overrideAttrs (oa: {
pname = "luarocks-nix";
src = /home/my_luarocks/repository;
});
@ -159,7 +176,11 @@ within a `toLuaModule` call, for instance
```nix
{
mynewlib = toLuaModule ( stdenv.mkDerivation { /* ... */ });
mynewlib = toLuaModule (
stdenv.mkDerivation {
# ...
}
);
}
```
@ -194,16 +215,23 @@ The following is an example:
version = "34.0.4-1";
src = fetchurl {
url = "https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/luaposix-34.0.4-1.src.rock";
url = "https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/luaposix-34.0.4-1.src.rock";
hash = "sha256-4mLJG8n4m6y4Fqd0meUDfsOb9RHSR0qa/KD5KCwrNXs=";
};
disabled = (luaOlder "5.1") || (luaAtLeast "5.4");
propagatedBuildInputs = [ bit32 lua std_normalize ];
propagatedBuildInputs = [
bit32
lua
std_normalize
];
meta = {
homepage = "https://github.com/luaposix/luaposix/";
description = "Lua bindings for POSIX";
maintainers = with lib.maintainers; [ vyp lblasc ];
maintainers = with lib.maintainers; [
vyp
lblasc
];
license.fullName = "MIT/X11";
};
};
@ -242,14 +270,14 @@ The `lua.withPackages` takes a function as an argument that is passed the set of
Using the `withPackages` function, the previous example for the luafilesystem environment can be written like this:
```nix
lua.withPackages (ps: [ps.luafilesystem])
lua.withPackages (ps: [ ps.luafilesystem ])
```
`withPackages` passes the correct package set for the specific interpreter version as an argument to the function. In the above example, `ps` equals `luaPackages`.
But you can also easily switch to using `lua5_1`:
```nix
lua5_1.withPackages (ps: [ps.lua])
lua5_1.withPackages (ps: [ ps.lua ])
```
Now, `ps` is set to `lua5_1.pkgs`, matching the version of the interpreter.

View file

@ -9,7 +9,13 @@ The following provides a list of common patterns with how to package a Maven pro
Consider the following package:
```nix
{ lib, fetchFromGitHub, jre, makeWrapper, maven }:
{
lib,
fetchFromGitHub,
jre,
makeWrapper,
maven,
}:
maven.buildMavenPackage rec {
pname = "jd-cli";
@ -17,8 +23,8 @@ maven.buildMavenPackage rec {
src = fetchFromGitHub {
owner = "intoolswetrust";
repo = pname;
rev = "${pname}-${version}";
repo = "jd-cli";
tag = "jd-cli-${version}";
hash = "sha256-rRttA5H0A0c44loBzbKH7Waoted3IsOgxGCD2VM0U/Q=";
};
@ -27,11 +33,15 @@ maven.buildMavenPackage rec {
nativeBuildInputs = [ makeWrapper ];
installPhase = ''
runHook preInstall
mkdir -p $out/bin $out/share/jd-cli
install -Dm644 jd-cli/target/jd-cli.jar $out/share/jd-cli
makeWrapper ${jre}/bin/java $out/bin/jd-cli \
--add-flags "-jar $out/share/jd-cli/jd-cli.jar"
runHook postInstall
'';
meta = {
@ -91,7 +101,7 @@ jd-cli.overrideMavenAttrs (old: rec {
# old mvnHash of 1.2.0 maven dependencies
mvnHash = "sha256-N9XC1pg6Y4sUiBWIQUf16QSXCuiAPpXEHGlgApviF4I=";
});
})
```
:::
@ -129,7 +139,7 @@ maven.buildMavenPackage rec {
"org.apache.maven.surefire:surefire-junit-platform:3.1.2"
"org.junit.platform:junit-platform-launcher:1.10.0"
];
};
}
```
:::
@ -246,7 +256,9 @@ This file is then given to the `buildMaven` function, and it returns 2 attribute
Here is an [example](https://github.com/fzakaria/nixos-maven-example/blob/main/build-maven-repository.nix) of building the Maven repository
```nix
{ pkgs ? import <nixpkgs> { } }:
{
pkgs ? import <nixpkgs> { },
}:
with pkgs;
(buildMaven ./project-info.json).repo
```
@ -283,22 +295,34 @@ Traditionally the Maven repository is at `~/.m2/repository`. We will override th
:::
```nix
{ lib, stdenv, maven }:
{
lib,
stdenv,
maven,
}:
stdenv.mkDerivation {
name = "maven-repository";
buildInputs = [ maven ];
src = ./.; # or fetchFromGitHub, cleanSourceWith, etc
buildPhase = ''
runHook preBuild
mvn package -Dmaven.repo.local=$out
runHook postBuild
'';
# keep only *.{pom,jar,sha1,nbm} and delete all ephemeral files with lastModified timestamps inside
installPhase = ''
runHook preInstall
find $out -type f \
-name \*.lastUpdated -or \
-name resolver-status.properties -or \
-name _remote.repositories \
-delete
runHook postInstall
'';
# don't do any fixup
@ -337,10 +361,16 @@ If your package uses _SNAPSHOT_ dependencies or _version ranges_; there is a str
Regardless of which strategy is chosen above, the step to build the derivation is the same.
```nix
{ stdenv, maven, callPackage }:
# pick a repository derivation, here we will use buildMaven
let repository = callPackage ./build-maven-repository.nix { };
in stdenv.mkDerivation rec {
{
stdenv,
maven,
callPackage,
}:
let
# pick a repository derivation, here we will use buildMaven
repository = callPackage ./build-maven-repository.nix { };
in
stdenv.mkDerivation (finalAttrs: {
pname = "maven-demo";
version = "1.0";
@ -348,14 +378,22 @@ in stdenv.mkDerivation rec {
buildInputs = [ maven ];
buildPhase = ''
runHook preBuild
echo "Using repository ${repository}"
mvn --offline -Dmaven.repo.local=${repository} package;
runHook postBuild
'';
installPhase = ''
install -Dm644 target/${pname}-${version}.jar $out/share/java
runHook preInstall
install -Dm644 target/${finalAttrs.pname}-${finalAttrs.version}.jar $out/share/java
runHook postInstall
'';
}
})
```
::: {.tip}
@ -393,35 +431,49 @@ We will read the Maven repository and flatten it to a single list. This list wil
We make sure to provide this classpath to the `makeWrapper`.
```nix
{ stdenv, maven, callPackage, makeWrapper, jre }:
{
stdenv,
maven,
callPackage,
makeWrapper,
jre,
}:
let
repository = callPackage ./build-maven-repository.nix { };
in stdenv.mkDerivation rec {
in
stdenv.mkDerivation (finalAttrs: {
pname = "maven-demo";
version = "1.0";
src = builtins.fetchTarball
"https://github.com/fzakaria/nixos-maven-example/archive/main.tar.gz";
src = builtins.fetchTarball "https://github.com/fzakaria/nixos-maven-example/archive/main.tar.gz";
nativeBuildInputs = [ makeWrapper ];
buildInputs = [ maven ];
buildPhase = ''
runHook preBuild
echo "Using repository ${repository}"
mvn --offline -Dmaven.repo.local=${repository} package;
runHook postBuild
'';
installPhase = ''
runHook preInstall
mkdir -p $out/bin
classpath=$(find ${repository} -name "*.jar" -printf ':%h/%f');
install -Dm644 target/${pname}-${version}.jar $out/share/java
install -Dm644 target/maven-demo-${finalAttrs.version}.jar $out/share/java
# create a wrapper that will automatically set the classpath
# this should be the paths from the dependency derivation
makeWrapper ${jre}/bin/java $out/bin/${pname} \
--add-flags "-classpath $out/share/java/${pname}-${version}.jar:''${classpath#:}" \
makeWrapper ${jre}/bin/java $out/bin/maven-demo \
--add-flags "-classpath $out/share/java/maven-demo-${finalAttrs.version}.jar:''${classpath#:}" \
--add-flags "Main"
runHook postInstall
'';
}
})
```
#### MANIFEST file via Maven Plugin {#manifest-file-via-maven-plugin}
@ -471,36 +523,51 @@ Main-Class: Main
We will modify the derivation above to add a symlink to our repository so that it's accessible to our JAR during the `installPhase`.
```nix
{ stdenv, maven, callPackage, makeWrapper, jre }:
# pick a repository derivation, here we will use buildMaven
let repository = callPackage ./build-maven-repository.nix { };
in stdenv.mkDerivation rec {
{
stdenv,
maven,
callPackage,
makeWrapper,
jre,
}:
let
# pick a repository derivation, here we will use buildMaven
repository = callPackage ./build-maven-repository.nix { };
in
stdenv.mkDerivation (finalAttrs: {
pname = "maven-demo";
version = "1.0";
src = builtins.fetchTarball
"https://github.com/fzakaria/nixos-maven-example/archive/main.tar.gz";
src = builtins.fetchTarball "https://github.com/fzakaria/nixos-maven-example/archive/main.tar.gz";
nativeBuildInputs = [ makeWrapper ];
buildInputs = [ maven ];
buildPhase = ''
runHook preBuild
echo "Using repository ${repository}"
mvn --offline -Dmaven.repo.local=${repository} package;
runHook postBuild
'';
installPhase = ''
runHook preInstall
mkdir -p $out/bin
# create a symbolic link for the repository directory
ln -s ${repository} $out/repository
install -Dm644 target/${pname}-${version}.jar $out/share/java
install -Dm644 target/maven-demo-${finalAttrs.version}.jar $out/share/java
# create a wrapper that will automatically set the classpath
# this should be the paths from the dependency derivation
makeWrapper ${jre}/bin/java $out/bin/${pname} \
--add-flags "-jar $out/share/java/${pname}-${version}.jar"
makeWrapper ${jre}/bin/java $out/bin/maven-demo \
--add-flags "-jar $out/share/java/maven-demo-${finalAttrs.version}.jar"
runHook postInstall
'';
}
})
```
::: {.note}
Our script produces a dependency on `jre` rather than `jdk` to restrict the runtime closure necessary to run the application.

View file

@ -63,7 +63,7 @@ For instance, `sqlite-lua` needs `g:sqlite_clib_path` to be set to work. Nixpkgs
- `plugins`: A list of plugins to add to the wrapper.
```
wrapNeovimUnstable {
wrapNeovimUnstable neovim-unwrapped {
autoconfigure = true;
autowrapRuntimeDeps = true;
luaRcContent = ''
@ -91,8 +91,8 @@ wrapNeovimUnstable {
You can explore the configuration with`nix repl` to discover these options and
override them. For instance:
```nix
neovim.overrideAttrs(oldAttrs: {
autowrapRuntimeDeps = false;
neovim.overrideAttrs (oldAttrs: {
autowrapRuntimeDeps = false;
})
```
@ -105,10 +105,10 @@ patch those plugins but expose the necessary configuration under
`PLUGIN.passthru.initLua` for neovim plugins. For instance, the `unicode-vim` plugin
needs the path towards a unicode database so we expose the following snippet `vim.g.Unicode_data_directory="${self.unicode-vim}/autoload/unicode"` under `vimPlugins.unicode-vim.passthru.initLua`.
#### {#neovim-luarocks-based-plugins}
#### LuaRocks based plugins {#neovim-luarocks-based-plugins}
In order to automatically handle plugin dependencies, several neovim plugins
upload their package to [](www.luarocks.org). This means less work for nixpkgs maintainers in the long term as dependencies get updated automatically.
upload their package to [LuaRocks](https://www.luarocks.org). This means less work for nixpkgs maintainers in the long term as dependencies get updated automatically.
This means several neovim plugins are first packaged as nixpkgs [lua
packages](#packaging-a-library-on-luarocks), and converted via `buildNeovimPlugin` in
a vim plugin. This conversion is necessary because neovim expects lua folders to be
@ -116,9 +116,11 @@ top-level while luarocks installs them in various subfolders by default.
For instance:
```nix
rtp-nvim = neovimUtils.buildNeovimPlugin {
{
rtp-nvim = neovimUtils.buildNeovimPlugin {
luaAttr = luaPackages.rtp-nvim;
};
};
}
```
To update these packages, you should use the lua updater rather than vim's.
@ -164,16 +166,19 @@ The check hook will fail the build if any modules cannot be loaded. This encoura
To only check a specific module, add it manually to the plugin definition [overrides](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/editors/vim/plugins/overrides.nix).
```nix
{
gitsigns-nvim = super.gitsigns-nvim.overrideAttrs {
dependencies = [ self.plenary-nvim ];
nvimRequireCheck = "gitsigns";
};
}
```
Some plugins will have lua modules that require a user configuration to function properly or can contain optional lua modules that we dont want to test requiring.
We can skip specific modules using `nvimSkipModules`. Similar to `nvimRequireCheck`, it accepts a list of strings.
- `nvimSkipModules = [ MODULE1 MODULE2 ];`
```nix
{
asyncrun-vim = super.asyncrun-vim.overrideAttrs {
nvimSkipModules = [
# vim plugin with optional toggleterm integration
@ -181,14 +186,17 @@ We can skip specific modules using `nvimSkipModules`. Similar to `nvimRequireChe
"asyncrun.toggleterm2"
];
};
}
```
In rare cases, we might not want to actually test loading lua modules for a plugin. In those cases, we can disable `neovimRequireCheck` with `doCheck = false;`.
This can be manually added through plugin definition overrides in the [overrides.nix](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/editors/vim/plugins/overrides.nix).
```nix
{
vim-test = super.vim-test.overrideAttrs {
# Vim plugin with a test lua file
doCheck = false;
};
}
```

View file

@ -7,7 +7,11 @@ Nim programs are built using a lockfile and either `buildNimPackage` or `buildNi
The following example shows a Nim program that depends only on Nim libraries:
```nix
{ lib, buildNimPackage, fetchFromGitHub }:
{
lib,
buildNimPackage,
fetchFromGitHub,
}:
buildNimPackage (finalAttrs: {
pname = "ttop";
@ -91,7 +95,9 @@ The `buildNimPackage` and `buildNimSbom` functions generate flags and additional
```nix
pkgs.nitter.overrideNimAttrs {
# using a different source which has different dependencies from the standard package
src = pkgs.fetchFromGithub { /* … */ };
src = pkgs.fetchFromGithub {
# …
};
# new lock file generated from the source
lockFile = ./custom-lock.json;
}
@ -104,21 +110,25 @@ The default overrides are maintained as the top-level `nimOverrides` attrset at
For example, to propagate a dependency on SDL2 for lockfiles that select the Nim `sdl2` library, an overlay is added to the set in the `nim-overrides.nix` file:
```nix
{ lib
/* … */
, SDL2
/* … */
{
lib,
# …
SDL2,
# …
}:
{
/* … */
# …
sdl2 =
lockAttrs:
{ buildInputs ? [ ], ... }:
{
buildInputs ? [ ],
...
}:
{
buildInputs = buildInputs ++ [ SDL2 ];
};
/* … */
# …
}
```
@ -132,22 +142,28 @@ The `nimOverrides` attrset makes it possible to modify overrides in a few differ
Override a package internal to its definition:
```nix
{ lib, buildNimPackage, nimOverrides, libressl }:
{
lib,
buildNimPackage,
nimOverrides,
libressl,
}:
let
buildNimPackage' = buildNimPackage.override {
nimOverrides = nimOverrides.override { openssl = libressl; };
};
in buildNimPackage' (finalAttrs: {
in
buildNimPackage' (finalAttrs: {
pname = "foo";
# …
})
```
Override a package externally:
```nix
{ pkgs }: {
{ pkgs }:
{
foo = pkgs.foo.override {
buildNimPackage = pkgs.buildNimPackage.override {
nimOverrides = pkgs.nimOverrides.override { openssl = libressl; };

View file

@ -12,13 +12,18 @@ To open a shell able to build a typical OCaml project, put the dependencies in `
For example:
```nix
let
pkgs = import <nixpkgs> {};
# choose the ocaml version you want to use
ocamlPackages = pkgs.ocaml-ng.ocamlPackages_4_12;
pkgs = import <nixpkgs> { };
# choose the ocaml version you want to use
ocamlPackages = pkgs.ocaml-ng.ocamlPackages_4_12;
in
pkgs.mkShell {
# build tools
nativeBuildInputs = with ocamlPackages; [ ocaml findlib dune_2 ocaml-lsp ];
nativeBuildInputs = with ocamlPackages; [
ocaml
findlib
dune_2
ocaml-lsp
];
# dependencies
buildInputs = with ocamlPackages; [ ocamlgraph ];
}
@ -58,7 +63,8 @@ Here is a simple package example.
generates.
```nix
{ lib,
{
lib,
fetchFromGitHub,
buildDunePackage,
ocaml,
@ -66,7 +72,8 @@ Here is a simple package example.
alcotest,
result,
bigstringaf,
ppx_let }:
ppx_let,
}:
buildDunePackage rec {
pname = "angstrom";
@ -75,15 +82,21 @@ buildDunePackage rec {
minimalOCamlVersion = "4.04";
src = fetchFromGitHub {
owner = "inhabitedtype";
repo = pname;
rev = version;
hash = "sha256-MK8o+iPGANEhrrTc1Kz9LBilx2bDPQt7Pp5P2libucI=";
owner = "inhabitedtype";
repo = "angstrom";
tag = version;
hash = "sha256-MK8o+iPGANEhrrTc1Kz9LBilx2bDPQt7Pp5P2libucI=";
};
checkInputs = [ alcotest ppx_let ];
checkInputs = [
alcotest
ppx_let
];
buildInputs = [ ocaml-syntax-shims ];
propagatedBuildInputs = [ bigstringaf result ];
propagatedBuildInputs = [
bigstringaf
result
];
doCheck = lib.versionAtLeast ocaml.version "4.05";
meta = {
@ -98,7 +111,11 @@ buildDunePackage rec {
Here is a second example, this time using a source archive generated with `dune-release`. It is a good idea to use this archive when it is available as it will usually contain substituted variables such as a `%%VERSION%%` field. This library does not depend on any other OCaml library and no tests are run after building it.
```nix
{ lib, fetchurl, buildDunePackage }:
{
lib,
fetchurl,
buildDunePackage,
}:
buildDunePackage rec {
pname = "wtf8";
@ -107,7 +124,7 @@ buildDunePackage rec {
minimalOCamlVersion = "4.02";
src = fetchurl {
url = "https://github.com/flowtype/ocaml-${pname}/releases/download/v${version}/${pname}-v${version}.tbz";
url = "https://github.com/flowtype/ocaml-wtf8/releases/download/v${version}/wtf8-v${version}.tbz";
hash = "sha256-d5/3KUBAWRj8tntr4RkJ74KWW7wvn/B/m1nx0npnzyc=";
};

View file

@ -3,7 +3,7 @@
## Introduction {#ssec-octave-introduction}
Octave is a modular scientific programming language and environment.
A majority of the packages supported by Octave from their [website](https://octave.sourceforge.io/packages.php) are packaged in nixpkgs.
A majority of the packages supported by Octave from their [website](https://gnu-octave.github.io/packages/) are packaged in nixpkgs.
## Structure {#ssec-octave-structure}
@ -39,7 +39,9 @@ $ nix-shell -p 'octave.withPackages (ps: with ps; [ symbolic ])'
This will also work in a `shell.nix` file.
```nix
{ pkgs ? import <nixpkgs> { }}:
{
pkgs ? import <nixpkgs> { },
}:
pkgs.mkShell {
nativeBuildInputs = with pkgs; [

View file

@ -39,7 +39,7 @@ Perl packages from CPAN are defined in [pkgs/top-level/perl-packages.nix](https:
pname = "Class-C3";
version = "0.21";
src = fetchurl {
url = "mirror://cpan/authors/id/F/FL/FLORA/${pname}-${version}.tar.gz";
url = "mirror://cpan/authors/id/F/FL/FLORA/Class-C3-${version}.tar.gz";
hash = "sha256-/5GE5xHT0uYGOQxroqj6LMU7CtKn2s6vMVoSXxL4iK4=";
};
};
@ -51,7 +51,10 @@ Note the use of `mirror://cpan/`, and the `pname` and `version` in the URL defin
```nix
{
foo = import ../path/to/foo.nix {
inherit stdenv fetchurl /* ... */;
inherit
stdenv
fetchurl # ...
;
inherit (perlPackages) ClassC3;
};
}
@ -74,14 +77,18 @@ So what does `buildPerlPackage` do? It does the following:
`buildPerlPackage` is built on top of `stdenv`, so everything can be customised in the usual way. For instance, the `BerkeleyDB` module has a `preConfigure` hook to generate a configuration file used by `Makefile.PL`:
```nix
{ buildPerlPackage, fetchurl, db }:
{
buildPerlPackage,
fetchurl,
db,
}:
buildPerlPackage rec {
pname = "BerkeleyDB";
version = "0.36";
src = fetchurl {
url = "mirror://cpan/authors/id/P/PM/PMQS/${pname}-${version}.tar.gz";
url = "mirror://cpan/authors/id/P/PM/PMQS/BerkeleyDB-${version}.tar.gz";
hash = "sha256-4Y+HGgGQqcOfdiKcFIyMrWBEccVNVAMDBWZlFTMorh8=";
};
@ -100,11 +107,14 @@ Dependencies on other Perl packages can be specified in the `buildInputs` and `p
pname = "Class-C3-Componentised";
version = "1.0004";
src = fetchurl {
url = "mirror://cpan/authors/id/A/AS/ASH/${pname}-${version}.tar.gz";
url = "mirror://cpan/authors/id/A/AS/ASH/Class-C3-Componentised-${version}.tar.gz";
hash = "sha256-ASO9rV/FzJYZ0BH572Fxm2ZrFLMZLFATJng1NuU4FHc=";
};
propagatedBuildInputs = [
ClassC3 ClassInspector TestException MROCompat
ClassC3
ClassInspector
TestException
MROCompat
];
};
}
@ -113,7 +123,13 @@ Dependencies on other Perl packages can be specified in the `buildInputs` and `p
On Darwin, if a script has too many `-Idir` flags in its first line (its “shebang line”), it will not run. This can be worked around by calling the `shortenPerlShebang` function from the `postInstall` phase:
```nix
{ lib, stdenv, buildPerlPackage, fetchurl, shortenPerlShebang }:
{
lib,
stdenv,
buildPerlPackage,
fetchurl,
shortenPerlShebang,
}:
{
ImageExifTool = buildPerlPackage {
@ -121,7 +137,7 @@ On Darwin, if a script has too many `-Idir` flags in its first line (its “sheb
version = "12.50";
src = fetchurl {
url = "https://exiftool.org/${pname}-${version}.tar.gz";
url = "https://exiftool.org/Image-ExifTool-${version}.tar.gz";
hash = "sha256-vOhB/FwQMC8PPvdnjDvxRpU6jAZcC6GMQfc0AH4uwKg=";
};

View file

@ -45,24 +45,30 @@ extensions. For example, a PHP package with all default extensions and
ImageMagick enabled:
```nix
php.withExtensions ({ enabled, all }:
enabled ++ [ all.imagick ])
php.withExtensions ({ enabled, all }: enabled ++ [ all.imagick ])
```
To exclude some, but not all, of the default extensions, you can
filter the `enabled` list like this:
```nix
php.withExtensions ({ enabled, all }:
(lib.filter (e: e != php.extensions.opcache) enabled)
++ [ all.imagick ])
php.withExtensions (
{ enabled, all }: (lib.filter (e: e != php.extensions.opcache) enabled) ++ [ all.imagick ]
)
```
To build your list of extensions from the ground up, you can
ignore `enabled`:
```nix
php.withExtensions ({ all, ... }: with all; [ imagick opcache ])
php.withExtensions (
{ all, ... }:
with all;
[
imagick
opcache
]
)
```
`php.withExtensions` provides extensions by wrapping a minimal php
@ -82,7 +88,13 @@ and ImageMagick extensions enabled, and `memory_limit` set to `256M`:
```nix
php.buildEnv {
extensions = { all, ... }: with all; [ imagick opcache ];
extensions =
{ all, ... }:
with all;
[
imagick
opcache
];
extraConfig = "memory_limit=256M";
}
```
@ -94,8 +106,16 @@ follows:
```nix
let
myPhp = php.withExtensions ({ all, ... }: with all; [ imagick opcache ]);
in {
myPhp = php.withExtensions (
{ all, ... }:
with all;
[
imagick
opcache
]
);
in
{
services.phpfpm.pools."foo".phpPackage = myPhp;
}
```
@ -103,10 +123,17 @@ in {
```nix
let
myPhp = php.buildEnv {
extensions = { all, ... }: with all; [ imagick opcache ];
extensions =
{ all, ... }:
with all;
[
imagick
opcache
];
extraConfig = "memory_limit=256M";
};
in {
in
{
services.phpfpm.pools."foo".phpPackage = myPhp;
}
```
@ -132,9 +159,14 @@ won't work with that project unless those extensions are loaded.
Example of building `composer` with additional extensions:
```nix
(php.withExtensions ({ all, enabled }:
enabled ++ (with all; [ imagick redis ]))
).packages.composer
(php.withExtensions (
{ all, enabled }:
enabled
++ (with all; [
imagick
redis
])
)).packages.composer
```
### Overriding PHP packages {#ssec-php-user-guide-overriding-packages}
@ -148,7 +180,7 @@ php.override {
packageOverrides = final: prev: {
extensions = prev.extensions // {
mysqlnd = prev.extensions.mysqlnd.overrideAttrs (attrs: {
patches = attrs.patches or [] ++ [
patches = attrs.patches or [ ] ++ [
# ...
];
});
@ -182,7 +214,7 @@ code, while others choose not to.
In Nix, there are multiple approaches to building a Composer-based project.
One such method is the `php.buildComposerProject` helper function, which serves
One such method is the `php.buildComposerProject2` helper function, which serves
as a wrapper around `mkDerivation`.
Using this function, you can build a PHP project that includes both a
@ -217,27 +249,31 @@ To customize the PHP version, you can specify the `php` attribute. Similarly, if
you wish to modify the Composer version, use the `composer` attribute. It is
important to note that both attributes should be of the `derivation` type.
Here's an example of working code example using `php.buildComposerProject`:
Here's an example of working code example using `php.buildComposerProject2`:
```nix
{ php, fetchFromGitHub }:
php.buildComposerProject (finalAttrs: {
php.buildComposerProject2 (finalAttrs: {
pname = "php-app";
version = "1.0.0";
src = fetchFromGitHub {
owner = "git-owner";
repo = "git-repo";
rev = finalAttrs.version;
tag = finalAttrs.version;
hash = "sha256-VcQRSss2dssfkJ+iUb5qT+FJ10GHiFDzySigcmuVI+8=";
};
# PHP version containing the `ast` extension enabled
php = php.buildEnv {
extensions = ({ enabled, all }: enabled ++ (with all; [
ast
]));
extensions = (
{ enabled, all }:
enabled
++ (with all; [
ast
])
);
};
# The composer vendor hash
@ -259,38 +295,45 @@ Here's a working code example to build a PHP library using `mkDerivation` and
separate functions and hooks:
```nix
{ stdenvNoCC, fetchFromGitHub, php }:
{
stdenvNoCC,
fetchFromGitHub,
php,
}:
stdenvNoCC.mkDerivation (finalAttrs:
let
src = fetchFromGitHub {
owner = "git-owner";
repo = "git-repo";
rev = finalAttrs.version;
hash = "sha256-VcQRSss2dssfkJ+iUb5qT+FJ10GHiFDzySigcmuVI+8=";
};
in {
inherit src;
pname = "php-app";
version = "1.0.0";
stdenvNoCC.mkDerivation (
finalAttrs:
let
src = fetchFromGitHub {
owner = "git-owner";
repo = "git-repo";
rev = finalAttrs.version;
hash = "sha256-VcQRSss2dssfkJ+iUb5qT+FJ10GHiFDzySigcmuVI+8=";
};
in
{
inherit src;
pname = "php-app";
version = "1.0.0";
buildInputs = [ php ];
buildInputs = [ php ];
nativeBuildInputs = [
php.packages.composer
# This hook will use the attribute `composerRepository`
php.composerHooks.composerInstallHook
];
nativeBuildInputs = [
php.packages.composer
# This hook will use the attribute `composerRepository`
php.composerHooks.composerInstallHook
];
composerRepository = php.mkComposerRepository {
inherit (finalAttrs) pname version src;
composerNoDev = true;
composerNoPlugins = true;
composerNoScripts = true;
# Specifying a custom composer.lock since it is not present in the sources.
composerLock = ./composer.lock;
# The composer vendor hash
vendorHash = "sha256-86s/F+/5cBAwBqZ2yaGRM5rTGLmou5//aLRK5SA0WiQ=";
};
})
composerRepository = php.mkComposerRepository {
inherit (finalAttrs) pname version src;
composerNoDev = true;
composerNoPlugins = true;
composerNoScripts = true;
# Specifying a custom composer.lock since it is not present in the sources.
composerLock = ./composer.lock;
# The composer vendor hash
vendorHash = "sha256-86s/F+/5cBAwBqZ2yaGRM5rTGLmou5//aLRK5SA0WiQ=";
};
}
)
```

View file

@ -17,9 +17,12 @@ A good example of all these things is miniz:
{ pkg-config, testers, ... }:
stdenv.mkDerivation (finalAttrs: {
/* ... */
# ...
nativeBuildInputs = [ pkg-config validatePkgConfig ];
nativeBuildInputs = [
pkg-config
validatePkgConfig
];
passthru.tests.pkg-config = testers.hasPkgConfigModules {
package = finalAttrs.finalPackage;
@ -27,7 +30,7 @@ stdenv.mkDerivation (finalAttrs: {
};
meta = {
/* ... */
# ...
pkgConfigModules = [ "miniz" ];
};
})

View file

@ -50,7 +50,6 @@ sets are
* `pkgs.python27Packages`
* `pkgs.python3Packages`
* `pkgs.python39Packages`
* `pkgs.python310Packages`
* `pkgs.python311Packages`
* `pkgs.python312Packages`
@ -79,24 +78,25 @@ using setup hooks.
The following is an example:
```nix
{ lib
, buildPythonPackage
, fetchPypi
{
lib,
buildPythonPackage,
fetchPypi,
# build-system
, setuptools
, setuptools-scm
# build-system
setuptools,
setuptools-scm,
# dependencies
, attrs
, pluggy
, py
, setuptools
, six
# dependencies
attrs,
pluggy,
py,
setuptools,
six,
# tests
, hypothesis
}:
# tests
hypothesis,
}:
buildPythonPackage rec {
pname = "pytest";
@ -135,7 +135,12 @@ buildPythonPackage rec {
description = "Framework for writing tests";
homepage = "https://github.com/pytest-dev/pytest";
license = lib.licenses.mit;
maintainers = with lib.maintainers; [ domenkozar lovek323 madjar lsix ];
maintainers = with lib.maintainers; [
domenkozar
lovek323
madjar
lsix
];
};
}
```
@ -232,23 +237,31 @@ override first the Python interpreter and pass `packageOverrides` which contains
the overrides for packages in the package set.
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
(let
python = let
packageOverrides = self: super: {
pandas = super.pandas.overridePythonAttrs(old: rec {
version = "0.19.1";
src = fetchPypi {
pname = "pandas";
inherit version;
hash = "sha256-JQn+rtpy/OA2deLszSKEuxyttqBzcAil50H+JDHUdCE=";
(
let
python =
let
packageOverrides = self: super: {
pandas = super.pandas.overridePythonAttrs (old: rec {
version = "0.19.1";
src = fetchPypi {
pname = "pandas";
inherit version;
hash = "sha256-JQn+rtpy/OA2deLszSKEuxyttqBzcAil50H+JDHUdCE=";
};
});
};
});
};
in pkgs.python3.override {inherit packageOverrides; self = python;};
in
pkgs.python3.override {
inherit packageOverrides;
self = python;
};
in python.withPackages(ps: [ ps.blaze ])).env
in
python.withPackages (ps: [ ps.blaze ])
).env
```
The next example shows a non trivial overriding of the `blas` implementation to
@ -259,12 +272,16 @@ be used through out all of the Python package set:
python3MyBlas = pkgs.python3.override {
packageOverrides = self: super: {
# We need toPythonModule for the package set to evaluate this
blas = super.toPythonModule(super.pkgs.blas.override {
blasProvider = super.pkgs.mkl;
});
lapack = super.toPythonModule(super.pkgs.lapack.override {
lapackProvider = super.pkgs.mkl;
});
blas = super.toPythonModule (
super.pkgs.blas.override {
blasProvider = super.pkgs.mkl;
}
);
lapack = super.toPythonModule (
super.pkgs.lapack.override {
lapackProvider = super.pkgs.mkl;
}
);
};
};
}
@ -291,9 +308,10 @@ called with `callPackage` and passed `python3` or `python3Packages` (possibly
specifying an interpreter version), like this:
```nix
{ lib
, python3Packages
, fetchPypi
{
lib,
python3Packages,
fetchPypi,
}:
python3Packages.buildPythonApplication rec {
@ -303,7 +321,7 @@ python3Packages.buildPythonApplication rec {
src = fetchPypi {
inherit pname version;
hash = "sha256-Pe229rT0aHwA98s+nTHQMEFKZPo/yw6sot8MivFDvAw=";
hash = "sha256-Pe229rT0aHwA98s+nTHQMEFKZPo/yw6sot8MivFDvAw=";
};
build-system = with python3Packages; [
@ -357,10 +375,12 @@ modifications.
```nix
{
opencv = toPythonModule (pkgs.opencv.override {
enablePython = true;
pythonPackages = self;
});
opencv = toPythonModule (
pkgs.opencv.override {
enablePython = true;
pythonPackages = self;
}
);
}
```
@ -395,8 +415,10 @@ The `build-system`'s provided will instead become runtime dependencies of the ed
Note that overriding packages deeper in the dependency graph _can_ work, but it's not the primary use case and overriding existing packages can make others break in unexpected ways.
``` nix
{ pkgs ? import <nixpkgs> { } }:
```nix
{
pkgs ? import <nixpkgs> { },
}:
let
pyproject = pkgs.lib.importTOML ./pyproject.toml;
@ -419,9 +441,10 @@ let
};
};
pythonEnv = myPython.withPackages (ps: [ ps.my-editable ]);
pythonEnv = myPython.withPackages (ps: [ ps.my-editable ]);
in pkgs.mkShell {
in
pkgs.mkShell {
packages = [ pythonEnv ];
}
```
@ -433,7 +456,7 @@ This example shows how to create an environment that has the Pyramid Web Framewo
Saving the following as `default.nix`
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
python3.buildEnv.override {
extraLibs = [ python3Packages.pyramid ];
@ -454,7 +477,7 @@ packages installed. This is somewhat comparable to `virtualenv`. For example,
running `nix-shell` with the following `shell.nix`
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
(python3.buildEnv.override {
extraLibs = with python3Packages; [
@ -484,7 +507,7 @@ of the packages to be included in the environment. Using the [`withPackages`](#p
example for the Pyramid Web Framework environment can be written like this:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
python.withPackages (ps: [ ps.pyramid ])
```
@ -494,7 +517,7 @@ version as an argument to the function. In the above example, `ps` equals
`pythonPackages`. But you can also easily switch to using python3:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
python3.withPackages (ps: [ ps.pyramid ])
```
@ -506,12 +529,14 @@ supports the `env` attribute. The `shell.nix` file from the previous section can
thus be also written like this:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
(python3.withPackages (ps: with ps; [
numpy
requests
])).env
(python3.withPackages (
ps: with ps; [
numpy
requests
]
)).env
```
In contrast to [`python.buildEnv`](#python.buildenv-function), [`python.withPackages`](#python.withpackages-function) does not support the
@ -759,11 +784,13 @@ Say we want to have Python 3.12, `numpy` and `toolz`, like before,
in an environment. We can add a `shell.nix` file describing our dependencies:
```nix
with import <nixpkgs> {};
(python312.withPackages (ps: with ps; [
numpy
toolz
])).env
with import <nixpkgs> { };
(python312.withPackages (
ps: with ps; [
numpy
toolz
]
)).env
```
And then at the command line, just typing `nix-shell` produces the same
@ -786,13 +813,14 @@ What's happening here?
To combine this with `mkShell` you can:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
let
pythonEnv = python312.withPackages (ps: [
ps.numpy
ps.toolz
]);
in mkShell {
in
mkShell {
packages = [
pythonEnv
@ -869,10 +897,16 @@ For the sake of completeness, here's how to install the environment system-wide
on NixOS.
```nix
{ # ...
{
# ...
environment.systemPackages = with pkgs; [
(python310.withPackages(ps: with ps; [ numpy toolz ]))
(python310.withPackages (
ps: with ps; [
numpy
toolz
]
))
];
}
```
@ -892,10 +926,11 @@ building Python libraries is [`buildPythonPackage`](#buildpythonpackage-function
`toolz` package.
```nix
{ lib
, buildPythonPackage
, fetchPypi
, setuptools
{
lib,
buildPythonPackage,
fetchPypi,
setuptools,
}:
buildPythonPackage rec {
@ -953,9 +988,10 @@ The following expression creates a derivation for the `toolz` package,
and adds it along with a `numpy` package to a Python environment.
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
( let
(
let
my_toolz = python312.pkgs.buildPythonPackage rec {
pname = "toolz";
version = "0.10.0";
@ -980,10 +1016,13 @@ with import <nixpkgs> {};
};
};
in python312.withPackages (ps: with ps; [
numpy
my_toolz
])
in
python312.withPackages (
ps: with ps; [
numpy
my_toolz
]
)
).env
```
@ -1015,18 +1054,21 @@ The following example shows which arguments are given to [`buildPythonPackage`](
order to build [`datashape`](https://github.com/blaze/datashape).
```nix
{ lib
, buildPythonPackage
, fetchPypi
{
lib,
buildPythonPackage,
fetchPypi,
# build dependencies
, setuptools
# build dependencies
setuptools,
# dependencies
, numpy, multipledispatch, python-dateutil
# dependencies
numpy,
multipledispatch,
python-dateutil,
# tests
, pytestCheckHook
# tests
pytestCheckHook,
}:
buildPythonPackage rec {
@ -1073,12 +1115,13 @@ Python bindings to `libxml2` and `libxslt`. These libraries are only required
when building the bindings and are therefore added as [`buildInputs`](#var-stdenv-buildInputs).
```nix
{ lib
, buildPythonPackage
, fetchPypi
, setuptools
, libxml2
, libxslt
{
lib,
buildPythonPackage,
fetchPypi,
setuptools,
libxml2,
libxslt,
}:
buildPythonPackage rec {
@ -1129,19 +1172,20 @@ The bindings don't expect to find each of them in a different folder, and
therefore we have to set `LDFLAGS` and `CFLAGS`.
```nix
{ lib
, buildPythonPackage
, fetchPypi
{
lib,
buildPythonPackage,
fetchPypi,
# build dependencies
, setuptools
# build dependencies
setuptools,
# dependencies
, fftw
, fftwFloat
, fftwLongDouble
, numpy
, scipy
# dependencies
fftw,
fftwFloat,
fftwLongDouble,
numpy,
scipy,
}:
buildPythonPackage rec {
@ -1183,7 +1227,10 @@ buildPythonPackage rec {
changelog = "https://github.com/pyFFTW/pyFFTW/releases/tag/v${version}";
description = "Pythonic wrapper around FFTW, the FFT library, presenting a unified interface for all the supported transforms";
homepage = "http://hgomersall.github.com/pyFFTW";
license = with lib.licenses; [ bsd2 bsd3 ];
license = with lib.licenses; [
bsd2
bsd3
];
};
}
```
@ -1233,36 +1280,14 @@ test run would be:
However, many repositories' test suites do not translate well to nix's build
sandbox, and will generally need many tests to be disabled.
To filter tests using pytest, one can do the following:
This is achievable by
- Including paths or test items (`path/to/file.py::MyClass` or `path/to/file.py::MyClass::test_method`) with positional arguments.
- Excluding paths with `--ignore` or globbed paths with `--ignore-glob`.
- Excluding test items using the `--deselect` flag.
- Including or excluding classes or test methods by their name using the `-k` flag.
- Including or excluding test by their marks using the `-m` flag.
```nix
{
nativeCheckInputs = [ pytest ];
# avoid tests which need additional data or touch network
checkPhase = ''
runHook preCheck
pytest tests/ --ignore=tests/integration -k 'not download and not update' --ignore=tests/test_failing.py
runHook postCheck
'';
}
```
`--ignore` will tell pytest to ignore that file or directory from being
collected as part of a test run. This is useful is a file uses a package
which is not available in nixpkgs, thus skipping that test file is much
easier than having to create a new package.
`-k` is used to define a predicate for test names. In this example, we are
filtering out tests which contain `download` or `update` in their test case name.
Only one `-k` argument is allowed, and thus a long predicate should be concatenated
with “\\” and wrapped to the next line.
::: {.note}
In pytest==6.0.1, the use of “\\” to continue a line (e.g. `-k 'not download \'`) has
been removed, in this case, it's recommended to use `pytestCheckHook`.
:::
We highly recommend `pytestCheckHook` for an easier and more structural setup.
#### Using pytestCheckHook {#using-pytestcheckhook}
@ -1272,7 +1297,40 @@ when a package may need many items disabled to run the test suite.
Most packages use `pytest` or `unittest`, which is compatible with `pytest`,
so you will most likely use `pytestCheckHook`.
Using the example above, the analogous `pytestCheckHook` usage would be:
To use `pytestCheckHook`, add it to `nativeCheckInputs`.
Adding `pytest` is not required, since it is included with `pytestCheckHook`.
```nix
{
nativeCheckInputs = [
pytestCheckHook
];
}
```
`pytestCheckHook` recognizes the following attributes:
`enabledTestPaths` and `disabledTestPaths`
: To specify path globs (files or directories) or test items.
`enabledTests` and `disabledTests`
: To specify keywords for class names or test method names.
`enabledTestMarks` and `disabledTestMarks`
: To specify test marks.
`pytestFlags`
: To append additional command-line arguments to `pytest`.
By default, `pytest` automatically discovers which tests to run.
If tests are explicitly enabled, only those tests will run.
A test, that is both enabled and disabled, will not run.
The following example demonstrates usage of various `pytestCheckHook` attributes:
```nix
{
@ -1280,46 +1338,92 @@ Using the example above, the analogous `pytestCheckHook` usage would be:
pytestCheckHook
];
# requires additional data
pytestFlags = [
# Allow running the following test paths and test objects.
enabledTestPaths = [
# Find tests under the tests directory.
# The trailing slash is not necessary.
"tests/"
"--ignore=tests/integration"
];
disabledTests = [
# touches network
"download"
"update"
# Additionally run test_foo
"other-tests/test_foo.py::Foo::test_foo"
];
# Override the above-enabled test paths and test objects.
disabledTestPaths = [
"tests/test_failing.py"
# Tests under tests/integration requires additional data.
"tests/integration"
];
# Allow tests by keywords matching their class names or method names.
enabledTests = [
# pytest by default only runs test methods begin with "test_" or end with "_test".
# This includes all functions whose name contains "test".
"test"
];
# Override the above-enabled tests by keywords matching their class names or method names.
disabledTests = [
# Tests touching networks.
"upload"
"download"
];
# Additional pytest flags
pytestFlags = [
# Disable benchmarks and run benchmarking tests only once.
"--benchmark-disable"
];
}
```
This is especially useful when tests need to be conditionally disabled,
for example:
These attributes are all passed into the derivation directly
and added to the `pytest` command without additional Bash expansion.
It requires `__structuredAttrs = true` to pass list elements containing spaces.
The `<enabled/disabled>TestsPaths` attributes expand Unix-style globs.
If a test path contains characters like `*`, `?`, `[`, or `]`, you can
quote them with square brackets (`[*]`, `[?]`, `[[]`, and `[]]`) to match literally.
The `<enabled/disabled>Tests` and `<enabled/disabled>TestMarks` attribute pairs
form a logical expression `((included_element1) or (included_element2)) and not (excluded_element1) and not (excluded_element2)`
which will be passed to pytest's `-k` and `-m` flags respectively.
With `__structuredAttrs = true` enabled, they additionally support sub-expressions.
For example, you could disable test items like `TestFoo::test_bar_functionality`
by disabling tests that match both `"Foo"` **and** `"bar"`:
```nix
{
__structuredAttrs = true;
disabledTests = [
# touches network
"download"
"update"
] ++ lib.optionals (pythonAtLeast "3.8") [
# broken due to python3.8 async changes
"async"
] ++ lib.optionals stdenv.buildPlatform.isDarwin [
# can fail when building with other packages
"socket"
"Foo and bar"
];
}
```
Trying to concatenate the related strings to disable tests in a regular
[`checkPhase`](#ssec-check-phase) would be much harder to read. This also enables us to comment on
why specific tests are disabled.
The main benefits of using `pytestCheckHook` to construct `pytest` commands
is structuralization and eval-time accessibility.
This is especially helpful to select tests or specify flags conditionally:
```nix
{
disabledTests =
[
# touches network
"download"
"update"
]
++ lib.optionals (pythonAtLeast "3.8") [
# broken due to python3.8 async changes
"async"
]
++ lib.optionals stdenv.buildPlatform.isDarwin [
# can fail when building with other packages
"socket"
];
}
```
#### Using pythonImportsCheck {#using-pythonimportscheck}
@ -1442,7 +1546,9 @@ automatically add `pythonRelaxDepsHook` if either `pythonRelaxDeps` or
];
unittestFlags = [
"-s" "tests" "-v"
"-s"
"tests"
"-v"
];
}
```
@ -1523,10 +1629,11 @@ Let's split the package definition from the environment definition.
We first create a function that builds `toolz` in `~/path/to/toolz/release.nix`
```nix
{ lib
, buildPythonPackage
, fetchPypi
, setuptools
{
lib,
buildPythonPackage,
fetchPypi,
setuptools,
}:
buildPythonPackage rec {
@ -1556,13 +1663,15 @@ It takes an argument [`buildPythonPackage`](#buildpythonpackage-function). We no
`callPackage` in the definition of our environment
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
( let
(
let
toolz = callPackage /path/to/toolz/release.nix {
buildPythonPackage = python3Packages.buildPythonPackage;
};
in python3.withPackages (ps: [
in
python3.withPackages (ps: [
ps.numpy
toolz
])
@ -1590,20 +1699,27 @@ We can override the interpreter and pass `packageOverrides`. In the following
example we rename the `pandas` package and build it.
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
(let
python = let
packageOverrides = self: super: {
pandas = super.pandas.overridePythonAttrs(old: {name="foo";});
};
in pkgs.python310.override {
inherit packageOverrides;
};
(
let
python =
let
packageOverrides = self: super: {
pandas = super.pandas.overridePythonAttrs (old: {
name = "foo";
});
};
in
pkgs.python310.override {
inherit packageOverrides;
};
in python.withPackages (ps: [
ps.pandas
])).env
in
python.withPackages (ps: [
ps.pandas
])
).env
```
Using `nix-build` on this expression will build an environment that contains the
@ -1617,17 +1733,20 @@ environment that uses it. All packages in the Python package set will now use
the updated `scipy` version.
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
( let
(
let
packageOverrides = self: super: {
scipy = super.scipy_0_17;
};
in (pkgs.python310.override {
in
(pkgs.python310.override {
inherit packageOverrides;
}).withPackages (ps: [
ps.blaze
])
}).withPackages
(ps: [
ps.blaze
])
).env
```
@ -1639,15 +1758,22 @@ If you want the whole of Nixpkgs to use your modifications, then you can use
```nix
let
pkgs = import <nixpkgs> {};
newpkgs = import pkgs.path { overlays = [ (self: super: {
python310 = let
packageOverrides = python-self: python-super: {
numpy = python-super.numpy_1_18;
};
in super.python310.override {inherit packageOverrides;};
} ) ]; };
in newpkgs.inkscape
pkgs = import <nixpkgs> { };
newpkgs = import pkgs.path {
overlays = [
(self: super: {
python310 =
let
packageOverrides = python-self: python-super: {
numpy = python-super.numpy_1_18;
};
in
super.python310.override { inherit packageOverrides; };
})
];
};
in
newpkgs.inkscape
```
### `python setup.py bdist_wheel` cannot create .whl {#python-setup.py-bdist_wheel-cannot-create-.whl}
@ -1737,7 +1863,8 @@ with import <nixpkgs> { };
let
pythonPackages = python3Packages;
in pkgs.mkShell rec {
in
pkgs.mkShell rec {
name = "impurePythonEnv";
venvDir = "./.venv";
buildInputs = [
@ -1792,7 +1919,8 @@ with import <nixpkgs> { };
let
venvDir = "./.venv";
pythonPackages = python3Packages;
in pkgs.mkShell rec {
in
pkgs.mkShell rec {
name = "impurePythonEnv";
buildInputs = [
pythonPackages.python
@ -1904,13 +2032,11 @@ The following overlay overrides the call to [`buildPythonPackage`](#buildpythonp
```nix
final: prev: {
pythonPackagesExtensions = prev.pythonPackagesExtensions ++ [
(
python-final: python-prev: {
foo = python-prev.foo.overridePythonAttrs (oldAttrs: {
# ...
});
}
)
(python-final: python-prev: {
foo = python-prev.foo.overridePythonAttrs (oldAttrs: {
# ...
});
})
];
}
```
@ -1936,13 +2062,14 @@ interpreter of interest, e.g using
```nix
let
pkgs = import ./. {};
pkgs = import ./. { };
mypython = pkgs.python3.override {
enableOptimizations = true;
reproducibleBuild = false;
self = mypython;
};
in mypython
in
mypython
```
### How to add optional dependencies? {#python-optional-dependencies}
@ -1975,6 +2102,14 @@ Note this method is preferred over adding parameters to builders, as that can
result in packages depending on different variants and thereby causing
collisions.
::: {.note}
The `optional-dependencies` attribute should only be used for dependency groups
as defined in package metadata. If a package gracefully handles missing
dependencies in runtime but doesn't advertise it through package metadata, then
these dependencies should not be listed at all. (One may still have to list
them in `nativeCheckInputs` to pass test suite.)
:::
### How to contribute a Python package to nixpkgs? {#tools}
Packages inside nixpkgs must use the [`buildPythonPackage`](#buildpythonpackage-function) or [`buildPythonApplication`](#buildpythonapplication-function) function directly,
@ -1982,6 +2117,7 @@ because we can only provide security support for non-vendored dependencies.
We recommend [nix-init](https://github.com/nix-community/nix-init) for creating new python packages within nixpkgs,
as it already prefetches the source, parses dependencies for common formats and prefills most things in `meta`.
When using the tool, pull from the original source repository instead of PyPI, if possible.
See also [contributing section](#contributing).
@ -2008,38 +2144,9 @@ Occasionally packages don't make use of a common test framework, which may then
#### Common issues {#common-issues}
* Non-working tests can often be deselected. Most Python modules
do follow the standard test protocol where the pytest runner can be used.
`pytest` supports the `-k` and `--ignore-glob` parameters to ignore test
methods or classes as well as whole files. For `pytestCheckHook` these are
conveniently exposed as `disabledTests` and `disabledTestPaths` respectively.
```nix
buildPythonPackage {
# ...
nativeCheckInputs = [
pytestCheckHook
];
disabledTests = [
"function_name"
"other_function"
];
disabledTestPaths = [
"path/to/performance.py"
"path/to/connect-*.py"
];
}
```
::: {.note}
If the test path to disable contains characters like `*`, `?`, `[`, and `]`,
quote them with square brackets (`[*]`, `[?]`, `[[]`, and `[]]`) to match literally.
:::
* Tests that attempt to access `$HOME` can be fixed by using the following
work-around before running tests (e.g. `preCheck`): `export HOME=$(mktemp -d)`
* Tests that attempt to access `$HOME` can be fixed by using `writableTmpDirAsHomeHook` in
`nativeCheckInputs`, which sets up a writable temporary directory as the home directory. Alternatively,
you can achieve the same effect manually (e.g. in `preCheck`) with: `export HOME=$(mktemp -d)`.
* Compiling with Cython causes tests to fail with a `ModuleNotLoadedError`.
This can be fixed with two changes in the derivation: 1) replacing `pytest` with
`pytestCheckHook` and 2) adding a `preCheck` containing `cd $out` to run
@ -2084,12 +2191,17 @@ The following rules are desired to be respected:
that characters should be converted to lowercase and `.` and `_` should be
replaced by a single `-` (foo-bar-baz instead of Foo__Bar.baz).
If necessary, `pname` has to be given a different value within `fetchPypi`.
* It's generally preferable to fetch `src` directly from the repo and not from
PyPI. Use `fetchPypi` when there's a clear technical reason to do so.
* Packages from sources such as GitHub and GitLab that do not exist on PyPI
should not use a name that is already used on PyPI. When possible, they should
use the package repository name prefixed with the owner (e.g. organization) name
and using a `-` as delimiter.
* Attribute names in `python-packages.nix` should be sorted alphanumerically to
avoid merge conflicts and ease locating attributes.
* Non-python runtime dependencies should be added via explicit wrapping or
patching (using e.g. `substituteInPlace`), rather than through propagation via
`dependencies`/`propagatedBuildInputs`, to reduce clutter in `$PATH`.
This list is useful for reviewers as well as for self-checking when submitting packages.

View file

@ -64,14 +64,18 @@ and then create wrappers manually in `fixupPhase`, using `wrapQtApp`, which itse
The `makeWrapper` arguments required for Qt are also exposed in the environment as `$qtWrapperArgs`.
```nix
{ stdenv, lib, wrapQtAppsHook }:
{
stdenv,
lib,
wrapQtAppsHook,
}:
stdenv.mkDerivation {
# ...
nativeBuildInputs = [ wrapQtAppsHook ];
dontWrapQtApps = true;
preFixup = ''
wrapQtApp "$out/bin/myapp" --prefix PATH : /path/to/bin
wrapQtApp "$out/bin/myapp" --prefix PATH : /path/to/bin
'';
}
```

View file

@ -7,18 +7,22 @@ use by adding the following snippet to your $HOME/.config/nixpkgs/config.nix fil
```nix
{
packageOverrides = super: let self = super.pkgs; in
packageOverrides =
super:
let
self = super.pkgs;
in
{
rEnv = super.rWrapper.override {
packages = with self.rPackages; [
devtools
ggplot2
reshape2
yaml
optparse
];
};
rEnv = super.rWrapper.override {
packages = with self.rPackages; [
devtools
ggplot2
reshape2
yaml
optparse
];
};
};
}
```
@ -33,7 +37,7 @@ environment available for other contributors, you can create a `default.nix`
file like so:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
{
myProject = stdenv.mkDerivation {
name = "myProject";
@ -60,16 +64,20 @@ environment, see `rstudioWrapper`, which functions similarly to
```nix
{
packageOverrides = super: let self = super.pkgs; in
packageOverrides =
super:
let
self = super.pkgs;
in
{
rstudioEnv = super.rstudioWrapper.override {
packages = with self.rPackages; [
dplyr
ggplot2
reshape2
];
};
rstudioEnv = super.rstudioWrapper.override {
packages = with self.rPackages; [
dplyr
ggplot2
reshape2
];
};
};
}
```
@ -81,13 +89,17 @@ Alternatively, you can create a self-contained `shell.nix` without the need to
modify any configuration files:
```nix
{ pkgs ? import <nixpkgs> {}
{
pkgs ? import <nixpkgs> { },
}:
pkgs.rstudioWrapper.override {
packages = with pkgs.rPackages; [ dplyr ggplot2 reshape2 ];
packages = with pkgs.rPackages; [
dplyr
ggplot2
reshape2
];
}
```
Executing `nix-shell` will then drop you into an environment equivalent to the

View file

@ -36,8 +36,13 @@ As explained [in the `nix-shell` section](https://nixos.org/manual/nix/stable/co
Say we want to have Ruby, `nokogori`, and `pry`. Consider a `shell.nix` file with:
```nix
with import <nixpkgs> {};
ruby.withPackages (ps: with ps; [ nokogiri pry ])
with import <nixpkgs> { };
ruby.withPackages (
ps: with ps; [
nokogiri
pry
]
)
```
What's happening here?
@ -107,7 +112,13 @@ let
name = "gems-for-some-project";
gemdir = ./.;
};
in mkShell { packages = [ gems gems.wrappedRuby ]; }
in
mkShell {
packages = [
gems
gems.wrappedRuby
];
}
```
With this file in your directory, you can run `nix-shell` to build and use the gems. The important parts here are `bundlerEnv` and `wrappedRuby`.
@ -118,7 +129,12 @@ One common issue that you might have is that you have Ruby, but also `bundler` i
```nix
# ...
mkShell { buildInputs = [ gems (lowPrio gems.wrappedRuby) ]; }
mkShell {
buildInputs = [
gems
(lowPrio gems.wrappedRuby)
];
}
```
Sometimes a Gemfile references other files. Such as `.ruby-version` or vendored gems. When copying the Gemfile to the nix store we need to copy those files alongside. This can be done using `extraConfigPaths`. For example:
@ -148,41 +164,54 @@ Two places that allow this modification are the `ruby` derivation, or `bundlerEn
Here's the `ruby` one:
```nix
{ pg_version ? "10", pkgs ? import <nixpkgs> { } }:
{
pg_version ? "10",
pkgs ? import <nixpkgs> { },
}:
let
myRuby = pkgs.ruby.override {
defaultGemConfig = pkgs.defaultGemConfig // {
pg = attrs: {
buildFlags =
[ "--with-pg-config=${lib.getDev pkgs."postgresql_${pg_version}"}/bin/pg_config" ];
buildFlags = [ "--with-pg-config=${pkgs."postgresql_${pg_version}".pg_config}/bin/pg_config" ];
};
};
};
in myRuby.withPackages (ps: with ps; [ pg ])
in
myRuby.withPackages (ps: with ps; [ pg ])
```
And an example with `bundlerEnv`:
```nix
{ pg_version ? "10", pkgs ? import <nixpkgs> { } }:
{
pg_version ? "10",
pkgs ? import <nixpkgs> { },
}:
let
gems = pkgs.bundlerEnv {
name = "gems-for-some-project";
gemdir = ./.;
gemConfig = pkgs.defaultGemConfig // {
pg = attrs: {
buildFlags =
[ "--with-pg-config=${lib.getDev pkgs."postgresql_${pg_version}"}/bin/pg_config" ];
buildFlags = [ "--with-pg-config=${pkgs."postgresql_${pg_version}".pg_config}/bin/pg_config" ];
};
};
};
in mkShell { buildInputs = [ gems gems.wrappedRuby ]; }
in
mkShell {
buildInputs = [
gems
gems.wrappedRuby
];
}
```
And finally via overlays:
```nix
{ pg_version ? "10" }:
{
pg_version ? "10",
}:
let
pkgs = import <nixpkgs> {
overlays = [
@ -190,14 +219,15 @@ let
defaultGemConfig = super.defaultGemConfig // {
pg = attrs: {
buildFlags = [
"--with-pg-config=${lib.getDev pkgs."postgresql_${pg_version}"}/bin/pg_config"
"--with-pg-config=${pkgs."postgresql_${pg_version}".pg_config}/bin/pg_config"
];
};
};
})
];
};
in pkgs.ruby.withPackages (ps: with ps; [ pg ])
in
pkgs.ruby.withPackages (ps: with ps; [ pg ])
```
Then we can get whichever postgresql version we desire and the `pg` gem will always reference it correctly:
@ -278,7 +308,14 @@ Of course you could also make a custom `gemConfig` if you know exactly how to pa
Here's another example:
```nix
{ lib, bundlerApp, makeWrapper, git, gnutar, gzip }:
{
lib,
bundlerApp,
makeWrapper,
git,
gnutar,
gzip,
}:
bundlerApp {
pname = "r10k";
@ -288,7 +325,13 @@ bundlerApp {
nativeBuildInputs = [ makeWrapper ];
postBuild = ''
wrapProgram $out/bin/r10k --prefix PATH : ${lib.makeBinPath [ git gnutar gzip ]}
wrapProgram $out/bin/r10k --prefix PATH : ${
lib.makeBinPath [
git
gnutar
gzip
]
}
'';
}
```

View file

@ -22,20 +22,23 @@ or use [community maintained Rust toolchains](#using-community-maintained-rust-t
Rust applications are packaged by using the `buildRustPackage` helper from `rustPlatform`:
```nix
{ lib, fetchFromGitHub, rustPlatform }:
{
lib,
fetchFromGitHub,
rustPlatform,
}:
rustPlatform.buildRustPackage rec {
rustPlatform.buildRustPackage (finalAttrs: {
pname = "ripgrep";
version = "14.1.1";
src = fetchFromGitHub {
owner = "BurntSushi";
repo = pname;
rev = version;
repo = "ripgrep";
tag = finalAttrs.version;
hash = "sha256-gyWnahj1A+iXUQlQ1O1H1u7K5euYQOld9qWm99Vjaeg=";
};
useFetchCargoVendor = true;
cargoHash = "sha256-9atn5qyBDy4P6iUoHFhg+TV6Ur71fiah4oTJbBMeEy4=";
meta = {
@ -44,7 +47,7 @@ rustPlatform.buildRustPackage rec {
license = lib.licenses.unlicense;
maintainers = [ ];
};
}
})
```
`buildRustPackage` requires a `cargoHash` attribute, computed over all crate sources of this package.
@ -100,21 +103,20 @@ be made invariant to the version by setting `cargoDepsName` to
`pname`:
```nix
rustPlatform.buildRustPackage rec {
rustPlatform.buildRustPackage (finalAttrs: {
pname = "broot";
version = "1.2.0";
src = fetchCrate {
inherit pname version;
inherit (finalAttrs) pname version;
hash = "sha256-aDQA4A5mScX9or3Lyiv/5GyAehidnpKKE0grhbP1Ctc=";
};
useFetchCargoVendor = true;
cargoHash = "sha256-iDYh52rj1M5Uupvbx2WeDd/jvQZ+2A50V5rp5e2t7q4=";
cargoDepsName = pname;
cargoDepsName = finalAttrs.pname;
# ...
}
})
```
### Importing a `Cargo.lock` file {#importing-a-cargo.lock-file}
@ -151,11 +153,13 @@ rustPlatform.buildRustPackage {
pname = "myproject";
version = "1.0.0";
cargoLock = let
fixupLockFile = path: f (builtins.readFile path);
in {
lockFileContents = fixupLockFile ./Cargo.lock;
};
cargoLock =
let
fixupLockFile = path: f (builtins.readFile path);
in
{
lockFileContents = fixupLockFile ./Cargo.lock;
};
# ...
}
@ -178,7 +182,7 @@ The output hash of each dependency that uses a git source must be
specified in the `outputHashes` attribute. For example:
```nix
rustPlatform.buildRustPackage rec {
rustPlatform.buildRustPackage {
pname = "myproject";
version = "1.0.0";
@ -203,7 +207,7 @@ For usage outside nixpkgs, `allowBuiltinFetchGit` could be used to
avoid having to specify `outputHashes`. For example:
```nix
rustPlatform.buildRustPackage rec {
rustPlatform.buildRustPackage {
pname = "myproject";
version = "1.0.0";
@ -229,12 +233,15 @@ If you want to use different features for check phase, you can use
For example:
```nix
rustPlatform.buildRustPackage rec {
rustPlatform.buildRustPackage {
pname = "myproject";
version = "1.0.0";
buildNoDefaultFeatures = true;
buildFeatures = [ "color" "net" ];
buildFeatures = [
"color"
"net"
];
# disable network features in tests
checkFeatures = [ "color" ];
@ -283,7 +290,10 @@ where they are known to differ. But there are ways to customize the argument:
import <nixpkgs> {
crossSystem = (import <nixpkgs/lib>).systems.examples.armhf-embedded // {
rust.rustcTarget = "thumb-crazy";
rust.platform = { foo = ""; bar = ""; };
rust.platform = {
foo = "";
bar = "";
};
};
}
```
@ -310,7 +320,7 @@ so:
```nix
rustPlatform.buildRustPackage {
/* ... */
# ...
checkType = "debug";
}
```
@ -353,7 +363,7 @@ This can be achieved with `--skip` in `checkFlags`:
```nix
rustPlatform.buildRustPackage {
/* ... */
# ...
checkFlags = [
# reason for disabling test
"--skip=example::tests:example_test"
@ -370,7 +380,7 @@ adapted to be compatible with cargo-nextest.
```nix
rustPlatform.buildRustPackage {
/* ... */
# ...
useNextest = true;
}
```
@ -382,7 +392,7 @@ sometimes it may be necessary to disable this so the tests run consecutively.
```nix
rustPlatform.buildRustPackage {
/* ... */
# ...
dontUseCargoParallelTests = true;
}
```
@ -394,7 +404,7 @@ should be built in `debug` mode, it can be configured like so:
```nix
rustPlatform.buildRustPackage {
/* ... */
# ...
buildType = "debug";
}
```
@ -415,7 +425,7 @@ source code in a reproducible way. If it is missing or out-of-date one can use
the `cargoPatches` attribute to update or add it.
```nix
rustPlatform.buildRustPackage rec {
rustPlatform.buildRustPackage {
# ...
cargoPatches = [
# a patch file to add/update Cargo.lock in the source code
@ -548,12 +558,13 @@ directory of the `tokenizers` project's source archive, we use
`sourceRoot` to point the tooling to this directory:
```nix
{ fetchFromGitHub
, buildPythonPackage
, cargo
, rustPlatform
, rustc
, setuptools-rust
{
fetchFromGitHub,
buildPythonPackage,
cargo,
rustPlatform,
rustc,
setuptools-rust,
}:
buildPythonPackage rec {
@ -562,13 +573,18 @@ buildPythonPackage rec {
src = fetchFromGitHub {
owner = "huggingface";
repo = pname;
rev = "python-v${version}";
repo = "tokenizers";
tag = "python-v${version}";
hash = "sha256-rQ2hRV52naEf6PvRsWVCTN7B1oXAQGmnpJw4iIdhamw=";
};
cargoDeps = rustPlatform.fetchCargoVendor {
inherit pname version src sourceRoot;
inherit
pname
version
src
sourceRoot
;
hash = "sha256-RO1m8wEd5Ic2M9q+zFHeCJWhCr4Sv3CEWd08mkxsBec=";
};
@ -593,12 +609,12 @@ following example, the crate is in `src/rust`, as specified in the
path for `fetchCargoVendor`.
```nix
{ buildPythonPackage
, fetchPypi
, rustPlatform
, setuptools-rust
, openssl
{
buildPythonPackage,
fetchPypi,
rustPlatform,
setuptools-rust,
openssl,
}:
buildPythonPackage rec {
@ -632,10 +648,11 @@ builds the `retworkx` Python package. `fetchCargoVendor` and
`maturinBuildHook` is used to perform the build.
```nix
{ lib
, buildPythonPackage
, rustPlatform
, fetchFromGitHub
{
lib,
buildPythonPackage,
rustPlatform,
fetchFromGitHub,
}:
buildPythonPackage rec {
@ -646,7 +663,7 @@ buildPythonPackage rec {
src = fetchFromGitHub {
owner = "Qiskit";
repo = "retworkx";
rev = version;
tag = version;
hash = "sha256-11n30ldg3y3y6qxg3hbj837pnbwjkqw3nxq6frds647mmmprrd20=";
};
@ -655,7 +672,10 @@ buildPythonPackage rec {
hash = "sha256-QsPCQhNZKYCAogQriQX6pBYQUDAIUsEdRX/63dAqTzg=";
};
nativeBuildInputs = with rustPlatform; [ cargoSetupHook maturinBuildHook ];
nativeBuildInputs = with rustPlatform; [
cargoSetupHook
maturinBuildHook
];
# ...
}
@ -666,23 +686,24 @@ buildPythonPackage rec {
Some projects, especially GNOME applications, are built with the Meson Build System instead of calling Cargo directly. Using `rustPlatform.buildRustPackage` may successfully build the main program, but related files will be missing. Instead, you need to set up Cargo dependencies with `fetchCargoVendor` and `cargoSetupHook` and leave the rest to Meson. `rust` and `cargo` are still needed in `nativeBuildInputs` for Meson to use.
```nix
{ lib
, stdenv
, fetchFromGitLab
, meson
, ninja
, pkg-config
, rustPlatform
, rustc
, cargo
, wrapGAppsHook4
, blueprint-compiler
, libadwaita
, libsecret
, tinysparql
{
lib,
stdenv,
fetchFromGitLab,
meson,
ninja,
pkg-config,
rustPlatform,
rustc,
cargo,
wrapGAppsHook4,
blueprint-compiler,
libadwaita,
libsecret,
tinysparql,
}:
stdenv.mkDerivation rec {
stdenv.mkDerivation (finalAttrs: {
pname = "health";
version = "0.95.0";
@ -690,12 +711,12 @@ stdenv.mkDerivation rec {
domain = "gitlab.gnome.org";
owner = "World";
repo = "health";
rev = version;
tag = finalAttrs.version;
hash = "sha256-PrNPprSS98yN8b8yw2G6hzTSaoE65VbsM3q7FVB4mds=";
};
cargoDeps = rustPlatform.fetchCargoVendor {
inherit pname version src;
inherit (finalAttrs) pname version src;
hash = "sha256-eR1ZGtTZQNhofFUEjI7IX16sMKPJmAl7aIFfPJukecg=";
};
@ -717,7 +738,7 @@ stdenv.mkDerivation rec {
];
# ...
}
})
```
## `buildRustCrate`: Compiling Rust crates using Nix instead of Cargo {#compiling-rust-crates-using-nix-instead-of-cargo}
@ -744,8 +765,8 @@ Starting from that file, one can add more overrides, to add features
or build inputs by overriding the hello crate in a separate file.
```nix
with import <nixpkgs> {};
((import ./hello.nix).hello {}).override {
with import <nixpkgs> { };
((import ./hello.nix).hello { }).override {
crateOverrides = defaultCrateOverrides // {
hello = attrs: { buildInputs = [ openssl ]; };
};
@ -764,15 +785,17 @@ the override above can be read, as in the following example, which
patches the derivation:
```nix
with import <nixpkgs> {};
((import ./hello.nix).hello {}).override {
with import <nixpkgs> { };
((import ./hello.nix).hello { }).override {
crateOverrides = defaultCrateOverrides // {
hello = attrs: lib.optionalAttrs (lib.versionAtLeast attrs.version "1.0") {
postPatch = ''
substituteInPlace lib/zoneinfo.rs \
--replace-fail "/usr/share/zoneinfo" "${tzdata}/share/zoneinfo"
'';
};
hello =
attrs:
lib.optionalAttrs (lib.versionAtLeast attrs.version "1.0") {
postPatch = ''
substituteInPlace lib/zoneinfo.rs \
--replace-fail "/usr/share/zoneinfo" "${tzdata}/share/zoneinfo"
'';
};
};
}
```
@ -785,10 +808,10 @@ dependencies. For instance, to override the build inputs for crate
crate, we could do:
```nix
with import <nixpkgs> {};
((import hello.nix).hello {}).override {
with import <nixpkgs> { };
((import hello.nix).hello { }).override {
crateOverrides = defaultCrateOverrides // {
libc = attrs: { buildInputs = []; };
libc = attrs: { buildInputs = [ ]; };
};
}
```
@ -801,27 +824,27 @@ general. A number of other parameters can be overridden:
- The version of `rustc` used to compile the crate:
```nix
(hello {}).override { rust = pkgs.rust; }
(hello { }).override { rust = pkgs.rust; }
```
- Whether to build in release mode or debug mode (release mode by
default):
```nix
(hello {}).override { release = false; }
(hello { }).override { release = false; }
```
- Whether to print the commands sent to `rustc` when building
(equivalent to `--verbose` in cargo:
```nix
(hello {}).override { verbose = false; }
(hello { }).override { verbose = false; }
```
- Extra arguments to be passed to `rustc`:
```nix
(hello {}).override { extraRustcOpts = "-Z debuginfo=2"; }
(hello { }).override { extraRustcOpts = "-Z debuginfo=2"; }
```
- Phases, just like in any other derivation, can be specified using
@ -833,9 +856,9 @@ general. A number of other parameters can be overridden:
before running the build script:
```nix
(hello {}).override {
(hello { }).override {
preConfigure = ''
echo "pub const PATH=\"${hi.out}\";" >> src/path.rs"
echo "pub const PATH=\"${hi.out}\";" >> src/path.rs"
'';
}
```
@ -856,12 +879,13 @@ Using the example `hello` project above, we want to do the following:
A typical `shell.nix` might look like:
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
stdenv.mkDerivation {
name = "rust-env";
nativeBuildInputs = [
rustc cargo
rustc
cargo
# Example Build-time Additional Dependencies
pkg-config
@ -917,15 +941,13 @@ Here is a simple `shell.nix` that provides Rust nightly (default profile) using
```nix
with import <nixpkgs> { };
let
fenix = callPackage
(fetchFromGitHub {
owner = "nix-community";
repo = "fenix";
# commit from: 2023-03-03
rev = "e2ea04982b892263c4d939f1cc3bf60a9c4deaa1";
hash = "sha256-AsOim1A8KKtMWIxG+lXh5Q4P2bhOZjoUhFWJ1EuZNNk=";
})
{ };
fenix = callPackage (fetchFromGitHub {
owner = "nix-community";
repo = "fenix";
# commit from: 2023-03-03
rev = "e2ea04982b892263c4d939f1cc3bf60a9c4deaa1";
hash = "sha256-AsOim1A8KKtMWIxG+lXh5Q4P2bhOZjoUhFWJ1EuZNNk=";
}) { };
in
mkShell {
name = "rust-env";
@ -964,8 +986,7 @@ You can also use Rust nightly to build rust packages using `makeRustPlatform`.
The below snippet demonstrates invoking `buildRustPackage` with a Rust toolchain from oxalica's overlay:
```nix
with import <nixpkgs>
{
with import <nixpkgs> {
overlays = [
(import (fetchTarball "https://github.com/oxalica/rust-overlay/archive/master.tar.gz"))
];
@ -977,29 +998,32 @@ let
};
in
rustPlatform.buildRustPackage rec {
rustPlatform.buildRustPackage (finalAttrs: {
pname = "ripgrep";
version = "14.1.1";
src = fetchFromGitHub {
owner = "BurntSushi";
repo = "ripgrep";
rev = version;
tag = finalAttrs.version;
hash = "sha256-gyWnahj1A+iXUQlQ1O1H1u7K5euYQOld9qWm99Vjaeg=";
};
useFetchCargoVendor = true;
cargoHash = "sha256-9atn5qyBDy4P6iUoHFhg+TV6Ur71fiah4oTJbBMeEy4=";
# Tests require network access. Skipping.
doCheck = false;
meta = {
description = "Fast line-oriented regex search tool, similar to ag and ack";
homepage = "https://github.com/BurntSushi/ripgrep";
license = with lib.licenses; [ mit unlicense ];
maintainers = with lib.maintainers; [];
license = with lib.licenses; [
mit
unlicense
];
maintainers = with lib.maintainers; [ ];
};
}
})
```
Follow the below steps to try that snippet.
@ -1029,19 +1053,28 @@ with the path into which you have `git clone`d the `rustc` git
repository:
```nix
(final: prev: /*lib.optionalAttrs prev.stdenv.targetPlatform.isAarch64*/ {
rust_1_72 =
lib.updateManyAttrsByPath [{
path = [ "packages" "stable" ];
update = old: old.overrideScope(final: prev: {
rustc-unwrapped = prev.rustc-unwrapped.overrideAttrs (_: {
src = lib.cleanSource /git/scratch/rust;
# do *not* put passthru.isReleaseTarball=true here
});
});
}]
prev.rust_1_72;
})
(
final: prev: # lib.optionalAttrs prev.stdenv.targetPlatform.isAarch64
{
rust_1_72 = lib.updateManyAttrsByPath [
{
path = [
"packages"
"stable"
];
update =
old:
old.overrideScope (
final: prev: {
rustc-unwrapped = prev.rustc-unwrapped.overrideAttrs (_: {
src = lib.cleanSource /git/scratch/rust;
# do *not* put passthru.isReleaseTarball=true here
});
}
);
}
] prev.rust_1_72;
})
```
If the problem you're troubleshooting only manifests when

View file

@ -69,42 +69,55 @@ This produces some files in a directory `nix`, which will be part of your Nix
expression. The next step is to write that expression:
```nix
{ stdenv, swift, swiftpm, swiftpm2nix, fetchFromGitHub }:
{
stdenv,
swift,
swiftpm,
swiftpm2nix,
fetchFromGitHub,
}:
let
# Pass the generated files to the helper.
generated = swiftpm2nix.helpers ./nix;
in
stdenv.mkDerivation rec {
stdenv.mkDerivation (finalAttrs: {
pname = "myproject";
version = "0.0.0";
src = fetchFromGitHub {
owner = "nixos";
repo = pname;
rev = version;
hash = "sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=";
repo = "myproject";
tag = finalAttrs.version;
hash = "";
};
# Including SwiftPM as a nativeBuildInput provides a buildPhase for you.
# This by default performs a release build using SwiftPM, essentially:
# swift build -c release
nativeBuildInputs = [ swift swiftpm ];
nativeBuildInputs = [
swift
swiftpm
];
# The helper provides a configure snippet that will prepare all dependencies
# in the correct place, where SwiftPM expects them.
configurePhase = generated.configure;
installPhase = ''
runHook preInstall
# This is a special function that invokes swiftpm to find the location
# of the binaries it produced.
binPath="$(swiftpmBinPath)"
# Now perform any installation steps.
mkdir -p $out/bin
cp $binPath/myproject $out/bin/
runHook postInstall
'';
}
})
```
### Custom build flags {#ssec-swiftpm-custom-build-flags}

View file

@ -10,7 +10,13 @@ Release 23.11 ships with a new interface that will eventually replace `texlive.c
- Packages cannot be used directly but must be assembled in an environment. To create or add packages to an environment, use
```nix
texliveSmall.withPackages (ps: with ps; [ collection-langkorean algorithms cm-super ])
texliveSmall.withPackages (
ps: with ps; [
collection-langkorean
algorithms
cm-super
]
)
```
The function `withPackages` can be called multiple times to add more packages.
@ -18,12 +24,14 @@ Release 23.11 ships with a new interface that will eventually replace `texlive.c
- `texlive.withPackages` uses the same logic as `buildEnv`. Only parts of a package are installed in an environment: its 'runtime' files (`tex` output), binaries (`out` output), and support files (`tlpkg` output). Moreover, man and info pages are assembled into separate `man` and `info` outputs. To add only the TeX files of a package, or its documentation (`texdoc` output), just specify the outputs:
```nix
texlive.withPackages (ps: with ps; [
texdoc # recommended package to navigate the documentation
perlPackages.LaTeXML.tex # tex files of LaTeXML, omit binaries
cm-super
cm-super.texdoc # documentation of cm-super
])
texlive.withPackages (
ps: with ps; [
texdoc # recommended package to navigate the documentation
perlPackages.LaTeXML.tex # tex files of LaTeXML, omit binaries
cm-super
cm-super.texdoc # documentation of cm-super
]
)
```
- All packages distributed by TeX Live, which contains most of CTAN, are available and can be found under `texlive.pkgs`:
@ -50,7 +58,12 @@ Release 23.11 ships with a new interface that will eventually replace `texlive.c
```nix
texlive.combine {
inherit (texlive) scheme-small collection-langkorean algorithms cm-super;
inherit (texlive)
scheme-small
collection-langkorean
algorithms
cm-super
;
}
```
@ -61,8 +74,8 @@ Release 23.11 ships with a new interface that will eventually replace `texlive.c
```nix
texlive.combine {
# inherit (texlive) whatever-you-want;
pkgFilter = pkg:
pkg.tlType == "run" || pkg.tlType == "bin" || pkg.hasManpages || pkg.pname == "cm-super";
pkgFilter =
pkg: pkg.tlType == "run" || pkg.tlType == "bin" || pkg.hasManpages || pkg.pname == "cm-super";
# elem tlType [ "run" "bin" "doc" "source" ]
# there are also other attributes: version, name
}
@ -81,18 +94,18 @@ Release 23.11 ships with a new interface that will eventually replace `texlive.c
- TeX Live packages are also available under `texlive.pkgs` as derivations with outputs `out`, `tex`, `texdoc`, `texsource`, `tlpkg`, `man`, `info`. They cannot be installed outside of `texlive.combine` but are available for other uses. To repackage a font, for instance, use
```nix
stdenvNoCC.mkDerivation rec {
stdenvNoCC.mkDerivation (finalAttrs: {
src = texlive.pkgs.iwona;
dontUnpack = true;
inherit (src) pname version;
inherit (finalAttrs.src) pname version;
installPhase = ''
runHook preInstall
install -Dm644 $src/fonts/opentype/nowacki/iwona/*.otf -t $out/share/fonts/opentype
runHook postInstall
'';
}
})
```
See `biber`, `iwona` for complete examples.
@ -114,14 +127,17 @@ When using `pkgFilter`, `texlive.combine` will assign `tlType` respectively `"bi
Here is a (very verbose) example. See also the packages `auctex`, `eukleides`, `mftrace` for more examples.
```nix
with import <nixpkgs> {};
with import <nixpkgs> { };
let
foiltex = stdenvNoCC.mkDerivation {
pname = "latex-foiltex";
version = "2.1.4b";
outputs = [ "tex" "texdoc" ];
outputs = [
"tex"
"texdoc"
];
passthru.tlDeps = with texlive; [ latex ];
srcs = [
@ -146,11 +162,18 @@ let
'';
nativeBuildInputs = [
(texliveSmall.withPackages (ps: with ps; [ cm-super hypdoc latexmk ]))
(texliveSmall.withPackages (
ps: with ps; [
cm-super
hypdoc
latexmk
]
))
# multiple-outputs.sh fails if $out is not defined
(writeShellScript "force-tex-output.sh" ''
out="''${tex-}"
'')
writableTmpDirAsHomeHook # Need a writable $HOME for latexmk
];
dontConfigure = true;
@ -162,7 +185,6 @@ let
latex foiltex.ins
# Generate the documentation
export HOME=.
latexmk -pdf foiltex.dtx
runHook postBuild
@ -192,22 +214,24 @@ let
latex_with_foiltex = texliveSmall.withPackages (_: [ foiltex ]);
in
runCommand "test.pdf" {
runCommand "test.pdf"
{
nativeBuildInputs = [ latex_with_foiltex ];
} ''
cat >test.tex <<EOF
\documentclass{foils}
}
''
cat >test.tex <<EOF
\documentclass{foils}
\title{Presentation title}
\date{}
\title{Presentation title}
\date{}
\begin{document}
\maketitle
\end{document}
EOF
pdflatex test.tex
cp test.pdf $out
''
\begin{document}
\maketitle
\end{document}
EOF
pdflatex test.tex
cp test.pdf $out
''
```
## LuaLaTeX font cache {#sec-language-texlive-lualatex-font-cache}
@ -215,13 +239,15 @@ EOF
The font cache for LuaLaTeX is written to `$HOME`.
Therefore, it is necessary to set `$HOME` to a writable path, e.g. [before using LuaLaTeX in nix derivations](https://github.com/NixOS/nixpkgs/issues/180639):
```nix
runCommandNoCC "lualatex-hello-world" {
buildInputs = [ texliveFull ];
} ''
mkdir $out
echo '\documentclass{article} \begin{document} Hello world \end{document}' > main.tex
env HOME=$(mktemp -d) lualatex -interaction=nonstopmode -output-format=pdf -output-directory=$out ./main.tex
''
runCommandNoCC "lualatex-hello-world"
{
buildInputs = [ texliveFull ];
}
''
mkdir $out
echo '\documentclass{article} \begin{document} Hello world \end{document}' > main.tex
env HOME=$(mktemp -d) lualatex -interaction=nonstopmode -output-format=pdf -output-directory=$out ./main.tex
''
```
Additionally, [the cache of a user can diverge from the nix store](https://github.com/NixOS/nixpkgs/issues/278718).

View file

@ -0,0 +1,73 @@
# Typst {#typst}
Typst can be configured to include packages from [Typst Universe](https://typst.app/universe/) or custom packages.
## Custom Environment {#typst-custom-environment}
You can create a custom Typst environment with a selected set of packages from **Typst Universe** using the following code. It is also possible to specify a Typst package with a specific version (e.g., `cetz_0_3_0`). A package without a version number will always refer to its latest version.
```nix
typst.withPackages (
p: with p; [
polylux_0_4_0
cetz_0_3_0
]
)
```
### Handling Outdated Package Hashes {#typst-handling-outdated-package-hashes}
Since **Typst Universe** does not provide a way to fetch a package with a specific hash, the package hashes in `nixpkgs` can sometimes be outdated. To resolve this issue, you can manually override the package source using the following approach:
```nix
typst.withPackages.override
(old: {
typstPackages = old.typstPackages.extend (
_: previous: {
polylux_0_4_0 = previous.polylux_0_4_0.overrideAttrs (oldPolylux: {
src = oldPolylux.src.overrideAttrs {
outputHash = YourUpToDatePolyluxHash;
};
});
}
);
})
(
p: with p; [
polylux_0_4_0
cetz_0_3_0
]
)
```
## Custom Packages {#typst-custom-packages}
`Nixpkgs` provides a helper function, `buildTypstPackage`, to build custom Typst packages that can be used within the Typst environment. However, all dependencies of the custom package must be explicitly specified in `typstDeps`.
Here's how to define a custom Typst package:
```nix
{
buildTypstPackage,
typstPackages,
}:
buildTypstPackage (finalAttrs: {
pname = "my-typst-package";
version = "0.0.1";
src = ./.;
typstDeps = with typstPackages; [ cetz_0_3_0 ];
})
```
### Package Scope and Usage {#typst-package-scope-and-usage}
By default, every custom package is scoped under `@preview`, as shown below:
```typst
#import "@preview/my-typst-package:0.0.1": *
```
Since `@preview` is intended for packages from **Typst Universe**, it is recommended to use this approach **only for temporary or experimental modifications over existing packages** from **Typst Universe**.
On the other hand, **local packages**, packages scoped under `@local`, are **not** considered part of the Typst environment. This means that local packages must be manually linked to the Typst compiler if needed.

View file

@ -47,11 +47,17 @@ To store your plugins in Vim packages (the native Vim plugin manager, see `:help
vim-full.customize {
vimrcConfig.packages.myVimPackage = with pkgs.vimPlugins; {
# loaded on launch
start = [ youcompleteme fugitive ];
start = [
youcompleteme
fugitive
];
# manually loadable by calling `:packadd $plugin-name`
# however, if a Vim plugin has a dependency that is not explicitly listed in
# opt that dependency will always be added to start to avoid confusion.
opt = [ phpCompletion elm-vim ];
opt = [
phpCompletion
elm-vim
];
# To automatically load a plugin when opening a filetype, add vimrc lines like:
# autocmd FileType php :packadd phpCompletion
};
@ -63,18 +69,19 @@ The resulting package can be added to `packageOverrides` in `~/.nixpkgs/config.n
```nix
{
packageOverrides = pkgs: with pkgs; {
myVim = vim-full.customize {
# `name` specifies the name of the executable and package
name = "vim-with-plugins";
# add here code from the example section
};
myNeovim = neovim.override {
configure = {
# add code from the example section here
packageOverrides =
pkgs: with pkgs; {
myVim = vim-full.customize {
# `name` specifies the name of the executable and package
name = "vim-with-plugins";
# add here code from the example section
};
myNeovim = neovim.override {
configure = {
# add code from the example section here
};
};
};
};
}
```
@ -100,20 +107,18 @@ let
in
{
environment.systemPackages = [
(
pkgs.neovim.override {
configure = {
packages.myPlugins = with pkgs.vimPlugins; {
(pkgs.neovim.override {
configure = {
packages.myPlugins = with pkgs.vimPlugins; {
start = [
vim-go # already packaged plugin
easygrep # custom package
];
opt = [];
opt = [ ];
};
# ...
};
}
)
})
];
}
```
@ -129,7 +134,12 @@ plugins the following example can be used:
vim-full.customize {
vimrcConfig.packages.myVimPackage = with pkgs.vimPlugins; {
# loaded on launch
plug.plugins = [ youcompleteme fugitive phpCompletion elm-vim ];
plug.plugins = [
youcompleteme
fugitive
phpCompletion
elm-vim
];
};
}
```
@ -147,8 +157,11 @@ Some plugins require overrides in order to function properly. Overrides are plac
```nix
{
deoplete-fish = super.deoplete-fish.overrideAttrs(old: {
dependencies = with super; [ deoplete-nvim vim-fish ];
deoplete-fish = super.deoplete-fish.overrideAttrs (old: {
dependencies = with super; [
deoplete-nvim
vim-fish
];
});
}
```
@ -164,7 +177,7 @@ Finally, there are some plugins that are also packaged in nodePackages because t
Run the update script with a GitHub API token that has at least `public_repo` access. Running the script without the token is likely to result in rate-limiting (429 errors). For steps on creating an API token, please refer to [GitHub's token documentation](https://docs.github.com/en/free-pro-team@latest/github/authenticating-to-github/creating-a-personal-access-token).
```sh
nix-shell -p vimPluginsUpdater --run 'vim-plugins-updater --github-token=mytoken' # or set GITHUB_API_TOKEN environment variable
nix-shell -p vimPluginsUpdater --run 'vim-plugins-updater --github-token=mytoken' # or set GITHUB_TOKEN environment variable
```
Alternatively, set the number of processes to a lower count to avoid rate-limiting.
@ -199,9 +212,7 @@ You can then reference the generated vim plugins via:
```nix
{
myVimPlugins = pkgs.vimPlugins.extend (
(pkgs.callPackage ./generated.nix {})
);
myVimPlugins = pkgs.vimPlugins.extend ((pkgs.callPackage ./generated.nix { }));
}
```

View file

@ -228,6 +228,8 @@
"systemd-socket-activate(1)": "https://www.freedesktop.org/software/systemd/man/systemd-socket-activate.html",
"systemd-socket-proxyd(8)": "https://www.freedesktop.org/software/systemd/man/systemd-socket-proxyd.html",
"systemd-soft-reboot.service(8)": "https://www.freedesktop.org/software/systemd/man/systemd-soft-reboot.service.html",
"systemd-ssh-generator(8)": "https://www.freedesktop.org/software/systemd/man/systemd-ssh-generator.html",
"systemd-ssh-proxy(1)": "https://www.freedesktop.org/software/systemd/man/systemd-ssh-proxy.html",
"systemd-stdio-bridge(1)": "https://www.freedesktop.org/software/systemd/man/systemd-stdio-bridge.html",
"systemd-stub(7)": "https://www.freedesktop.org/software/systemd/man/systemd-stub.html",
"systemd-suspend-then-hibernate.service(8)": "https://www.freedesktop.org/software/systemd/man/systemd-suspend-then-hibernate.service.html",

View file

@ -9,6 +9,7 @@ preface.chapter.md
using-nixpkgs.md
lib.md
stdenv.md
toolchains.md
build-helpers.md
development.md
contributing.md

View file

@ -30,13 +30,12 @@ substitute {
```
:::
## `pkgs.substituteAll` {#pkgs-substituteall}
## `pkgs.replaceVars` {#pkgs-replacevars}
`pkgs.substituteAll` substitutes all instances of `@varName@` (`@`s included) in file `src` with the value of the corresponding environment variable.
As this uses the [`substituteAll`] (#fun-substitute) function, its limitations regarding variable names that will or will not be replaced also apply here.
`pkgs.replaceVars <src> <replacements>` replaces all instances of `@varName@` (`@`s included) in file `src` with the respective value in the attribute set `replacements`.
:::{.example #ex-pkgs-substituteAll}
# Usage of `pkgs.substituteAll`
:::{.example #ex-pkgs-replace-vars}
# Usage of `pkgs.replaceVars`
If `say-goodbye.sh` contains the following:
@ -51,16 +50,14 @@ the following derivation will make substitutions to `@bash@`, `@hello@`, and `@g
```nix
{
substituteAll,
replaceVars,
bash,
hello,
}:
substituteAll {
src = ./say-goodbye.sh;
env = {
inherit bash hello;
greeting = "goodbye";
};
replaceVars ./say-goodbye.sh {
inherit bash hello;
greeting = "goodbye";
unchanged = null;
}
```
@ -72,31 +69,37 @@ such that `$out` will result in something like the following:
echo @unchanged@
/nix/store/566f5isbvw014h7knmzmxa5l6hshx43k-hello-2.12.1/bin/hello --greeting goodbye
```
Note that, in contrast to the old `substituteAll`, `unchanged = null` must explicitly be set.
Any unreferenced `@...@` pattern in the source file will throw an error.
:::
## `pkgs.substituteAllFiles` {#pkgs-substituteallfiles}
## `pkgs.replaceVarsWith` {#pkgs-replacevarswith}
`pkgs.substituteAllFiles` replaces `@varName@` with the value of the environment variable `varName`.
It expects `src` to be a directory and requires a `files` argument that specifies which files will be subject to replacements; only these files will be placed in `$out`.
`pkgs.replaceVarsWith` works the same way as [pkgs.replaceVars](#pkgs-replacevars), but additionally allows more options.
As it also uses the `substituteAll` function, it is subject to the same limitations on environment variables as discussed in [pkgs.substituteAll](#pkgs-substituteall).
:::{.example #ex-pkgs-replace-vars-with}
# Usage of `pkgs.replaceVarsWith`
:::{.example #ex-pkgs-substitute-all-files}
# Usage of `pkgs.substituteAllFiles`
If the current directory contains `{foo,bar,baz}.txt` and the following `default.nix`
With the example file `say-goodbye.sh`, consider:
```nix
{ substituteAllFiles }:
substituteAllFiles {
src = ./.;
files = [
"foo.txt"
"bar.txt"
];
hello = "there";
{ replaceVarsWith }:
replaceVarsWith {
src = ./say-goodbye.sh;
replacements = {
inherit bash hello;
greeting = "goodbye";
unchanged = null;
};
name = "say-goodbye";
dir = "bin";
isExecutable = true;
meta.mainProgram = "say-goodbye";
}
```
in the resulting derivation, every instance of `@hello@` will be replaced with `there` in `$out/foo.txt` and `$out/bar.txt`; `baz.txt` will not be processed nor will it appear in `$out`.
This will make the resulting file executable, put it in `bin/say-goodbye` and set `meta` attributes respectively.
:::

View file

@ -48,7 +48,7 @@ let
# Unfortunately, this refers to the package before overriding and
# parallel building is still disabled.
badExample = myCDDA.withMods (_: []);
badExample = myCDDA.withMods (_: [ ]);
inherit (cataclysmDDA) attachPkgs pkgs wrapCDDA;
@ -66,7 +66,7 @@ in
# badExample # parallel building disabled
# goodExample1.withMods (_: []) # parallel building enabled
goodExample2.withMods (_: []) # parallel building enabled
goodExample2.withMods (_: [ ]) # parallel building enabled
```
## Customizing with mods {#customizing-with-mods}
@ -75,9 +75,11 @@ To install Cataclysm DDA with mods of your choice, you can use `withMods`
attribute:
```nix
cataclysm-dda.withMods (mods: with mods; [
tileset.UndeadPeople
])
cataclysm-dda.withMods (
mods: with mods; [
tileset.UndeadPeople
]
)
```
All mods, soundpacks, and tilesets available in nixpkgs are found in
@ -88,42 +90,46 @@ in nixpkgs:
```nix
let
customMods = self: super: lib.recursiveUpdate super {
# Modify existing mod
tileset.UndeadPeople = super.tileset.UndeadPeople.overrideAttrs (old: {
# If you like to apply a patch to the tileset for example
patches = [ ./path/to/your.patch ];
});
customMods =
self: super:
lib.recursiveUpdate super {
# Modify existing mod
tileset.UndeadPeople = super.tileset.UndeadPeople.overrideAttrs (old: {
# If you like to apply a patch to the tileset for example
patches = [ ./path/to/your.patch ];
});
# Add another mod
mod.Awesome = cataclysmDDA.buildMod {
modName = "Awesome";
version = "0.x";
src = fetchFromGitHub {
owner = "Someone";
repo = "AwesomeMod";
rev = "...";
hash = "...";
# Add another mod
mod.Awesome = cataclysmDDA.buildMod {
modName = "Awesome";
version = "0.x";
src = fetchFromGitHub {
owner = "Someone";
repo = "AwesomeMod";
rev = "...";
hash = "...";
};
# Path to be installed in the unpacked source (default: ".")
modRoot = "contents/under/this/path/will/be/installed";
};
# Path to be installed in the unpacked source (default: ".")
modRoot = "contents/under/this/path/will/be/installed";
};
# Add another soundpack
soundpack.Fantastic = cataclysmDDA.buildSoundPack {
# ditto
};
# Add another soundpack
soundpack.Fantastic = cataclysmDDA.buildSoundPack {
# ditto
};
# Add another tileset
tileset.SuperDuper = cataclysmDDA.buildTileSet {
# ditto
# Add another tileset
tileset.SuperDuper = cataclysmDDA.buildTileSet {
# ditto
};
};
};
in
cataclysm-dda.withMods (mods: with mods.extend customMods; [
tileset.UndeadPeople
mod.Awesome
soundpack.Fantastic
tileset.SuperDuper
])
cataclysm-dda.withMods (
mods: with mods.extend customMods; [
tileset.UndeadPeople
mod.Awesome
soundpack.Fantastic
tileset.SuperDuper
]
)
```

View file

@ -28,5 +28,6 @@ let
./custom-cert-1.pem
./custom-cert-2.pem # ...
];
in citrix_workspace.override { inherit extraCerts; }
in
citrix_workspace.override { inherit extraCerts; }
```

View file

@ -89,58 +89,72 @@ $ sudo launchctl kickstart -k system/org.nixos.nix-daemon
darwin.inputs.nixpkgs.follows = "nixpkgs";
};
outputs = { self, darwin, nixpkgs, ... }@inputs:
let
outputs =
{
self,
darwin,
nixpkgs,
...
}@inputs:
let
inherit (darwin.lib) darwinSystem;
system = "aarch64-darwin";
pkgs = nixpkgs.legacyPackages."${system}";
linuxSystem = builtins.replaceStrings [ "darwin" ] [ "linux" ] system;
inherit (darwin.lib) darwinSystem;
system = "aarch64-darwin";
pkgs = nixpkgs.legacyPackages."${system}";
linuxSystem = builtins.replaceStrings [ "darwin" ] [ "linux" ] system;
darwin-builder = nixpkgs.lib.nixosSystem {
system = linuxSystem;
modules = [
"${nixpkgs}/nixos/modules/profiles/nix-builder-vm.nix"
{ virtualisation = {
host.pkgs = pkgs;
darwin-builder.workingDirectory = "/var/lib/darwin-builder";
darwin-builder.hostPort = 22;
};
}
];
};
in {
darwinConfigurations = {
machine1 = darwinSystem {
inherit system;
darwin-builder = nixpkgs.lib.nixosSystem {
system = linuxSystem;
modules = [
"${nixpkgs}/nixos/modules/profiles/nix-builder-vm.nix"
{
nix.distributedBuilds = true;
nix.buildMachines = [{
hostName = "localhost";
sshUser = "builder";
sshKey = "/etc/nix/builder_ed25519";
system = linuxSystem;
maxJobs = 4;
supportedFeatures = [ "kvm" "benchmark" "big-parallel" ];
}];
launchd.daemons.darwin-builder = {
command = "${darwin-builder.config.system.build.macos-builder-installer}/bin/create-builder";
serviceConfig = {
KeepAlive = true;
RunAtLoad = true;
StandardOutPath = "/var/log/darwin-builder.log";
StandardErrorPath = "/var/log/darwin-builder.log";
};
virtualisation = {
host.pkgs = pkgs;
darwin-builder.workingDirectory = "/var/lib/darwin-builder";
darwin-builder.hostPort = 22;
};
}
];
};
};
in
{
};
darwinConfigurations = {
machine1 = darwinSystem {
inherit system;
modules = [
{
nix.distributedBuilds = true;
nix.buildMachines = [
{
hostName = "localhost";
sshUser = "builder";
sshKey = "/etc/nix/builder_ed25519";
system = linuxSystem;
maxJobs = 4;
supportedFeatures = [
"kvm"
"benchmark"
"big-parallel"
];
}
];
launchd.daemons.darwin-builder = {
command = "${darwin-builder.config.system.build.macos-builder-installer}/bin/create-builder";
serviceConfig = {
KeepAlive = true;
RunAtLoad = true;
StandardOutPath = "/var/log/darwin-builder.log";
StandardErrorPath = "/var/log/darwin-builder.log";
};
};
}
];
};
};
};
}
```
@ -154,21 +168,21 @@ To do this, you just need to set the `virtualisation.darwin-builder.*` parameter
in the example below and rebuild.
```nix
{
darwin-builder = nixpkgs.lib.nixosSystem {
system = linuxSystem;
modules = [
"${nixpkgs}/nixos/modules/profiles/nix-builder-vm.nix"
{
virtualisation.host.pkgs = pkgs;
virtualisation.darwin-builder.diskSize = 5120;
virtualisation.darwin-builder.memorySize = 1024;
virtualisation.darwin-builder.hostPort = 33022;
virtualisation.darwin-builder.workingDirectory = "/var/lib/darwin-builder";
}
];
};
}
{
darwin-builder = nixpkgs.lib.nixosSystem {
system = linuxSystem;
modules = [
"${nixpkgs}/nixos/modules/profiles/nix-builder-vm.nix"
{
virtualisation.host.pkgs = pkgs;
virtualisation.darwin-builder.diskSize = 5120;
virtualisation.darwin-builder.memorySize = 1024;
virtualisation.darwin-builder.hostPort = 33022;
virtualisation.darwin-builder.workingDirectory = "/var/lib/darwin-builder";
}
];
};
}
```
You may make any other changes to your VM in this attribute set. For example,

View file

@ -15,11 +15,13 @@ If you prefer to install plugins in a more declarative manner, then Nixpkgs also
```nix
{
packageOverrides = pkgs: {
myEclipse = with pkgs.eclipses; eclipseWithPlugins {
eclipse = eclipse-platform;
jvmArgs = [ "-Xmx2048m" ];
plugins = [ plugins.color-theme ];
};
myEclipse =
with pkgs.eclipses;
eclipseWithPlugins {
eclipse = eclipse-platform;
jvmArgs = [ "-Xmx2048m" ];
plugins = [ plugins.color-theme ];
};
};
}
```
@ -37,32 +39,34 @@ Expanding the previous example with two plugins using the above functions, we ha
```nix
{
packageOverrides = pkgs: {
myEclipse = with pkgs.eclipses; eclipseWithPlugins {
eclipse = eclipse-platform;
jvmArgs = [ "-Xmx2048m" ];
plugins = [
plugins.color-theme
(plugins.buildEclipsePlugin {
name = "myplugin1-1.0";
srcFeature = fetchurl {
url = "http://…/features/myplugin1.jar";
hash = "sha256-123…";
};
srcPlugin = fetchurl {
url = "http://…/plugins/myplugin1.jar";
hash = "sha256-123…";
};
})
(plugins.buildEclipseUpdateSite {
name = "myplugin2-1.0";
src = fetchurl {
stripRoot = false;
url = "http://…/myplugin2.zip";
hash = "sha256-123…";
};
})
];
};
myEclipse =
with pkgs.eclipses;
eclipseWithPlugins {
eclipse = eclipse-platform;
jvmArgs = [ "-Xmx2048m" ];
plugins = [
plugins.color-theme
(plugins.buildEclipsePlugin {
name = "myplugin1-1.0";
srcFeature = fetchurl {
url = "http://…/features/myplugin1.jar";
hash = "sha256-123…";
};
srcPlugin = fetchurl {
url = "http://…/plugins/myplugin1.jar";
hash = "sha256-123…";
};
})
(plugins.buildEclipseUpdateSite {
name = "myplugin2-1.0";
src = fetchurl {
stripRoot = false;
url = "http://…/myplugin2.zip";
hash = "sha256-123…";
};
})
];
};
};
}
```

View file

@ -6,17 +6,21 @@ The Emacs package comes with some extra helpers to make it easier to configure.
```nix
{
packageOverrides = pkgs: with pkgs; {
myEmacs = emacs.pkgs.withPackages (epkgs: (with epkgs.melpaStablePackages; [
company
counsel
flycheck
ivy
magit
projectile
use-package
]));
};
packageOverrides =
pkgs: with pkgs; {
myEmacs = emacs.pkgs.withPackages (
epkgs:
(with epkgs.melpaStablePackages; [
company
counsel
flycheck
ivy
magit
projectile
use-package
])
);
};
}
```
@ -24,8 +28,8 @@ You can install it like any other packages via `nix-env -iA myEmacs`. However, t
```nix
{
packageOverrides = pkgs: with pkgs; rec {
myEmacsConfig = writeText "default.el" ''
packageOverrides = pkgs: {
myEmacsConfig = pkgs.writeText "default.el" ''
(eval-when-compile
(require 'use-package))
@ -80,19 +84,22 @@ You can install it like any other packages via `nix-env -iA myEmacs`. However, t
(projectile-global-mode))
'';
myEmacs = emacs.pkgs.withPackages (epkgs: (with epkgs.melpaStablePackages; [
(runCommand "default.el" {} ''
mkdir -p $out/share/emacs/site-lisp
cp ${myEmacsConfig} $out/share/emacs/site-lisp/default.el
'')
company
counsel
flycheck
ivy
magit
projectile
use-package
]));
myEmacs = emacs.pkgs.withPackages (
epkgs:
(with epkgs.melpaStablePackages; [
(runCommand "default.el" { } ''
mkdir -p $out/share/emacs/site-lisp
cp ${myEmacsConfig} $out/share/emacs/site-lisp/default.el
'')
company
counsel
flycheck
ivy
magit
projectile
use-package
])
);
};
}
```
@ -108,11 +115,12 @@ let
# ...
};
in
((emacsPackagesFor emacs).overrideScope overrides).withPackages
(p: with p; [
((emacsPackagesFor emacs).overrideScope overrides).withPackages (
p: with p; [
# here both these package will use haskell-mode of our own choice
ghc-mod
dante
])
]
)
```
}

View file

@ -42,9 +42,12 @@ way to test Fish plugins and scripts without having to alter the environment.
```nix
wrapFish {
pluginPkgs = with fishPlugins; [ pure foreign-env ];
completionDirs = [];
functionDirs = [];
pluginPkgs = with fishPlugins; [
pure
foreign-env
];
completionDirs = [ ];
functionDirs = [ ];
confDirs = [ "/path/to/some/fish/init/dir/" ];
}
```

View file

@ -9,7 +9,8 @@ IBus needs to be configured accordingly to activate `typing-booster`. The config
On NixOS, you need to explicitly enable `ibus` with given engines before customizing your desktop to use `typing-booster`. This can be achieved using the `ibus` module:
```nix
{ pkgs, ... }: {
{ pkgs, ... }:
{
i18n.inputMethod = {
enable = true;
type = "ibus";
@ -23,7 +24,12 @@ On NixOS, you need to explicitly enable `ibus` with given engines before customi
The IBus engine is based on `hunspell` to support completion in many languages. By default, the dictionaries `de-de`, `en-us`, `fr-moderne` `es-es`, `it-it`, `sv-se` and `sv-fi` are in use. To add another dictionary, the package can be overridden like this:
```nix
ibus-engines.typing-booster.override { langs = [ "de-at" "en-gb" ]; }
ibus-engines.typing-booster.override {
langs = [
"de-at"
"en-gb"
];
}
```
_Note: each language passed to `langs` must be an attribute name in `pkgs.hunspellDicts`._
@ -35,7 +41,8 @@ The `ibus-engines.typing-booster` package contains a program named `emoji-picker
On NixOS, it can be installed using the following expression:
```nix
{ pkgs, ... }: {
{ pkgs, ... }:
{
fonts.packages = with pkgs; [ noto-fonts-color-emoji ];
}
```

View file

@ -24,6 +24,8 @@ etc-files.section.md
nginx.section.md
opengl.section.md
shell-helpers.section.md
python-tree-sitter.section.md
treefmt.section.md
steam.section.md
cataclysm-dda.section.md
urxvt.section.md

View file

@ -23,7 +23,7 @@ list of previous plugins via `pkgs.krita.binaryPlugins`:
```nix
(pkgs.krita.override (old: {
binaryPlugins = old.binaryPlugins ++ [ your-plugin ];
binaryPlugins = old.binaryPlugins ++ [ your-plugin ];
}))
```

View file

@ -0,0 +1,56 @@
# Python Tree Sitter {#python-tree-sitter}
[Tree Sitter](https://tree-sitter.github.io/tree-sitter/) is a framework for building grammars for programming languages. It generates and uses syntax trees from source files, which are useful for code analysis, tooling, and syntax highlighting.
Python bindings for Tree Sitter grammars are provided through the [py-tree-sitter](https://github.com/tree-sitter/py-tree-sitter) module. The Nix package `python3Packages.tree-sitter-grammars` provides pre-built grammars for various languages.
For example, to experiment with the Rust grammar, you can create a shell environment with the following configuration:
```nix
{
pkgs ? <nixpkgs> { },
}:
pkgs.mkShell {
name = "py-tree-sitter-dev-shell";
buildInputs = with pkgs; [
(python3.withPackages (
ps: with ps; [
tree-sitter
tree-sitter-grammars.tree-sitter-rust
]
))
];
}
```
Once inside the shell, the following Python code demonstrates how to parse a Rust code snippet:
```python
# Import the Tree Sitter library and Rust grammar
import tree_sitter
import tree_sitter_rust
# Load the Rust grammar and initialize the parser
rust = tree_sitter.Language(tree_sitter_rust.language())
parser = tree_sitter.Parser(rust)
# Parse a Rust snippet
tree = parser.parse(
bytes(
"""
fn main() {
println!("Hello, world!");
}
""",
"utf8"
)
)
# Display the resulting syntax tree
print(tree.root_node)
```
The `tree_sitter_rust.language()` function references the Rust grammar loaded in the Nix shell. The resulting tree allows you to inspect the structure of the code programmatically.

View file

@ -0,0 +1,23 @@
# treefmt {#treefmt}
[treefmt](https://github.com/numtide/treefmt) streamlines the process of applying formatters to your project, making it a breeze with just one command line.
The [`treefmt` package](https://search.nixos.org/packages?channel=unstable&show=treefmt)
provides functions for configuring treefmt using the module system, which are [documented below](#sec-functions-library-treefmt), along with [their options](#sec-treefmt-options-reference).
Alternatively, treefmt can be configured using [treefmt-nix](https://github.com/numtide/treefmt-nix).
```{=include=} sections auto-id-prefix=auto-generated-treefmt-functions
treefmt-functions.section.md
```
## Options Reference {#sec-treefmt-options-reference}
The following attributes can be passed to [`withConfig`](#pkgs.treefmt.withConfig) or [`evalConfig`](#pkgs.treefmt.evalConfig):
```{=include=} options
id-prefix: opt-treefmt-
list-id: configuration-variable-list
source: ../treefmt-options.json
```

View file

@ -8,9 +8,15 @@ In `nixpkgs`, urxvt is provided by the package `rxvt-unicode`. It can be configu
```nix
rxvt-unicode.override {
configure = { availablePlugins, ... }: {
plugins = with availablePlugins; [ perls resize-font vtwheel ];
};
configure =
{ availablePlugins, ... }:
{
plugins = with availablePlugins; [
perls
resize-font
vtwheel
];
};
}
```
@ -20,9 +26,11 @@ In order to add plugins but also keep all default plugins installed, it is possi
```nix
rxvt-unicode.override {
configure = { availablePlugins, ... }: {
plugins = (builtins.attrValues availablePlugins) ++ [ custom-plugin ];
};
configure =
{ availablePlugins, ... }:
{
plugins = (builtins.attrValues availablePlugins) ++ [ custom-plugin ];
};
}
```
@ -40,9 +48,11 @@ In addition to `plugins` the options `extraDeps` and `perlDeps` can be used to i
```nix
rxvt-unicode.override {
configure = { availablePlugins, ... }: {
pluginsDeps = [ xsel ];
};
configure =
{ availablePlugins, ... }:
{
pluginsDeps = [ xsel ];
};
}
```
@ -50,9 +60,11 @@ rxvt-unicode.override {
```nix
rxvt-unicode.override {
configure = { availablePlugins, ... }: {
perlDeps = with perlPackages; [ AnyEvent ];
};
configure =
{ availablePlugins, ... }:
{
perlDeps = with perlPackages; [ AnyEvent ];
};
}
```

View file

@ -3,9 +3,16 @@
WeeChat can be configured to include your choice of plugins, reducing its closure size from the default configuration which includes all available plugins. To make use of this functionality, install an expression that overrides its configuration, such as:
```nix
weechat.override {configure = ({availablePlugins, ...}: {
plugins = with availablePlugins; [ python perl ];
});
weechat.override {
configure = (
{ availablePlugins, ... }:
{
plugins = with availablePlugins; [
python
perl
];
}
);
}
```
@ -16,10 +23,18 @@ The plugins currently available are `python`, `perl`, `ruby`, `guile`, `tcl` and
The Python and Perl plugins allows the addition of extra libraries. For instance, the `inotify.py` script in `weechat-scripts` requires D-Bus or libnotify, and the `fish.py` script requires `pycrypto`. To use these scripts, use the plugin's `withPackages` attribute:
```nix
weechat.override { configure = {availablePlugins, ...}: {
plugins = with availablePlugins; [
(python.withPackages (ps: with ps; [ pycrypto python-dbus ]))
];
weechat.override {
configure =
{ availablePlugins, ... }:
{
plugins = with availablePlugins; [
(python.withPackages (
ps: with ps; [
pycrypto
python-dbus
]
))
];
};
}
```
@ -27,23 +42,37 @@ weechat.override { configure = {availablePlugins, ...}: {
In order to also keep all default plugins installed, it is possible to use the following method:
```nix
weechat.override { configure = { availablePlugins, ... }: {
plugins = builtins.attrValues (availablePlugins // {
python = availablePlugins.python.withPackages (ps: with ps; [ pycrypto python-dbus ]);
});
}; }
weechat.override {
configure =
{ availablePlugins, ... }:
{
plugins = builtins.attrValues (
availablePlugins
// {
python = availablePlugins.python.withPackages (
ps: with ps; [
pycrypto
python-dbus
]
);
}
);
};
}
```
WeeChat allows to set defaults on startup using the `--run-command`. The `configure` method can be used to pass commands to the program:
```nix
weechat.override {
configure = { availablePlugins, ... }: {
init = ''
/set foo bar
/server add libera irc.libera.chat
'';
};
configure =
{ availablePlugins, ... }:
{
init = ''
/set foo bar
/server add libera irc.libera.chat
'';
};
}
```
@ -53,14 +82,18 @@ Additionally, it's possible to specify scripts to be loaded when starting `weech
```nix
weechat.override {
configure = { availablePlugins, ... }: {
scripts = with pkgs.weechatScripts; [
weechat-xmpp weechat-matrix-bridge wee-slack
];
init = ''
/set plugins.var.python.jabber.key "val"
'';
};
configure =
{ availablePlugins, ... }:
{
scripts = with pkgs.weechatScripts; [
weechat-xmpp
weechat-matrix-bridge
wee-slack
];
init = ''
/set plugins.var.python.jabber.key "val"
'';
};
}
```
@ -75,7 +108,10 @@ stdenv.mkDerivation {
url = "https://scripts.tld/your-scripts.tar.gz";
hash = "...";
};
passthru.scripts = [ "foo.py" "bar.lua" ];
passthru.scripts = [
"foo.py"
"bar.lua"
];
installPhase = ''
mkdir $out/share
cp foo.py $out/share

View file

@ -42,7 +42,7 @@ shows the status of tests for the `nixpkgs-unstable` channel.
The tests are conducted by a cluster called [Hydra](https://nixos.org/hydra/),
which also builds binary packages from the Nix expressions in Nixpkgs for
`x86_64-linux`, `i686-linux` and `x86_64-darwin`.
`x86_64-linux`, `aarch64-linux`, `x86_64-darwin` and `aarch64-darwin`.
The binaries are made available via a [binary cache](https://cache.nixos.org).
The current Nix expressions of the channels are available in the

Some files were not shown because too many files have changed in this diff Show more