0
0
Fork 0
mirror of https://github.com/NixOS/nixpkgs.git synced 2025-07-14 06:00:33 +03:00

Merge branch 'NixOS:master' into jxd/add-config

This commit is contained in:
Jia Xiaodong 2024-04-03 20:29:53 +08:00 committed by GitHub
commit a19bf3e045
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2026 changed files with 89111 additions and 27436 deletions

View file

@ -102,3 +102,6 @@ fb0e5be84331188a69b3edd31679ca6576edb75a
# systemd: break too long lines of Nix code # systemd: break too long lines of Nix code
67643f8ec84bef1482204709073e417c9f07eb87 67643f8ec84bef1482204709073e417c9f07eb87
# {pkgs/development/cuda-modules,pkgs/test/cuda,pkgs/top-level/cuda-packages.nix}: reformat all CUDA files with nixfmt-rfc-style 2023-03-01
802a1b4d3338f24cbc4efd704616654456d75a94

5
.github/CODEOWNERS vendored
View file

@ -159,7 +159,6 @@ nixos/modules/installer/tools/nix-fallback-paths.nix @raitobezarius @ma27
# C compilers # C compilers
/pkgs/development/compilers/gcc /pkgs/development/compilers/gcc
/pkgs/development/compilers/llvm @RaitoBezarius
/pkgs/development/compilers/emscripten @raitobezarius /pkgs/development/compilers/emscripten @raitobezarius
/doc/languages-frameworks/emscripten.section.md @raitobezarius /doc/languages-frameworks/emscripten.section.md @raitobezarius
@ -204,10 +203,6 @@ pkgs/development/python-modules/buildcatrust/ @ajs124 @lukegb @mweinelt
/nixos/modules/services/databases/postgresql.nix @thoughtpolice /nixos/modules/services/databases/postgresql.nix @thoughtpolice
/nixos/tests/postgresql.nix @thoughtpolice /nixos/tests/postgresql.nix @thoughtpolice
# Linux kernel
/pkgs/os-specific/linux/kernel @raitobezarius
/pkgs/top-level/linux-kernels.nix @raitobezarius
# Hardened profile & related modules # Hardened profile & related modules
/nixos/modules/profiles/hardened.nix @joachifm /nixos/modules/profiles/hardened.nix @joachifm
/nixos/modules/security/hidepid.nix @joachifm /nixos/modules/security/hidepid.nix @joachifm

9
.github/labeler.yml vendored
View file

@ -95,6 +95,14 @@
- pkgs/top-level/haskell-packages.nix - pkgs/top-level/haskell-packages.nix
- pkgs/top-level/release-haskell.nix - pkgs/top-level/release-haskell.nix
"6.topic: julia":
- any:
- changed-files:
- any-glob-to-any-file:
- doc/languages-frameworks/julia.section.md
- pkgs/development/compilers/julia/**/*
- pkgs/development/julia-modules/**/*
"6.topic: jupyter": "6.topic: jupyter":
- any: - any:
- changed-files: - changed-files:
@ -122,6 +130,7 @@
- any: - any:
- changed-files: - changed-files:
- any-glob-to-any-file: - any-glob-to-any-file:
- pkgs/development/tools/misc/luarocks/*
- pkgs/development/interpreters/lua-5/**/* - pkgs/development/interpreters/lua-5/**/*
- pkgs/development/interpreters/luajit/**/* - pkgs/development/interpreters/luajit/**/*
- pkgs/development/lua-modules/**/* - pkgs/development/lua-modules/**/*

50
.github/workflows/check-nix-format.yml vendored Normal file
View file

@ -0,0 +1,50 @@
# This file was copied mostly from check-maintainers-sorted.yaml.
# NOTE: Formatting with the RFC-style nixfmt command is not yet stable. See
# https://github.com/NixOS/rfcs/pull/166.
# Because of this, this action is not yet enabled for all files -- only for
# those who have opted in.
name: Check that Nix files are formatted
on:
pull_request_target:
permissions:
contents: read
jobs:
nixos:
runs-on: ubuntu-latest
if: github.repository_owner == 'NixOS'
steps:
- uses: actions/checkout@9bb56186c3b09b4f86b1c65136769dd318469633 # v4.1.2
with:
# pull_request_target checks out the base branch by default
ref: refs/pull/${{ github.event.pull_request.number }}/merge
- uses: cachix/install-nix-action@8887e596b4ee1134dae06b98d573bd674693f47c # v26
with:
# explicitly enable sandbox
extra_nix_config: sandbox = true
- name: Install nixfmt
run: nix-env -f default.nix -iAP nixfmt-rfc-style
- name: Check that Nix files are formatted according to the RFC style
# Each environment variable beginning with NIX_FMT_PATHS_ is a list of
# paths to check with nixfmt.
env:
# Format paths related to the Nixpkgs CUDA ecosystem.
NIX_FMT_PATHS_CUDA: |
pkgs/development/cuda-modules
pkgs/test/cuda
pkgs/top-level/cuda-packages.nix
# Iterate over all environment variables beginning with NIX_FMT_PATHS_.
run: |
for env_var in "${!NIX_FMT_PATHS_@}"; do
readarray -t paths <<< "${!env_var}"
if [[ "${paths[*]}" == "" ]]; then
echo "Error: $env_var is empty."
exit 1
fi
echo "Checking paths: ${paths[@]}"
if ! nixfmt --check "${paths[@]}"; then
echo "Error: nixfmt failed."
exit 1
fi
done

View file

@ -557,7 +557,7 @@ Names of files and directories should be in lowercase, with dashes between words
```nix ```nix
foo { foo {
arg = ...; arg = <...>;
} }
``` ```
@ -566,14 +566,14 @@ Names of files and directories should be in lowercase, with dashes between words
```nix ```nix
foo foo
{ {
arg = ...; arg = <...>;
} }
``` ```
Also fine is Also fine is
```nix ```nix
foo { arg = ...; } foo { arg = <...>; }
``` ```
if it's a short call. if it's a short call.
@ -581,41 +581,45 @@ Names of files and directories should be in lowercase, with dashes between words
- In attribute sets or lists that span multiple lines, the attribute names or list elements should be aligned: - In attribute sets or lists that span multiple lines, the attribute names or list elements should be aligned:
```nix ```nix
# A long list. {
list = [ # A long list.
elem1 list = [
elem2 elem1
elem3 elem2
]; elem3
];
# A long attribute set. # A long attribute set.
attrs = { attrs = {
attr1 = short_expr; attr1 = short_expr;
attr2 = attr2 =
if true then big_expr else big_expr; if true then big_expr else big_expr;
}; };
# Combined # Combined
listOfAttrs = [ listOfAttrs = [
{ {
attr1 = 3; attr1 = 3;
attr2 = "fff"; attr2 = "fff";
} }
{ {
attr1 = 5; attr1 = 5;
attr2 = "ggg"; attr2 = "ggg";
} }
]; ];
}
``` ```
- Short lists or attribute sets can be written on one line: - Short lists or attribute sets can be written on one line:
```nix ```nix
# A short list. {
list = [ elem1 elem2 elem3 ]; # A short list.
list = [ elem1 elem2 elem3 ];
# A short set. # A short set.
attrs = { x = 1280; y = 1024; }; attrs = { x = 1280; y = 1024; };
}
``` ```
- Breaking in the middle of a function argument can give hard-to-read code, like - Breaking in the middle of a function argument can give hard-to-read code, like
@ -649,7 +653,7 @@ Names of files and directories should be in lowercase, with dashes between words
```nix ```nix
{ arg1, arg2 }: { arg1, arg2 }:
assert system == "i686-linux"; assert system == "i686-linux";
stdenv.mkDerivation { ... stdenv.mkDerivation { /* ... */ }
``` ```
not not
@ -657,41 +661,41 @@ Names of files and directories should be in lowercase, with dashes between words
```nix ```nix
{ arg1, arg2 }: { arg1, arg2 }:
assert system == "i686-linux"; assert system == "i686-linux";
stdenv.mkDerivation { ... stdenv.mkDerivation { /* ... */ }
``` ```
- Function formal arguments are written as: - Function formal arguments are written as:
```nix ```nix
{ arg1, arg2, arg3 }: { arg1, arg2, arg3 }: { /* ... */ }
``` ```
but if they don't fit on one line they're written as: but if they don't fit on one line they're written as:
```nix ```nix
{ arg1, arg2, arg3 { arg1, arg2, arg3
, arg4, ... , arg4
, # Some comment... # Some comment...
argN , argN
}: }: { }
``` ```
- Functions should list their expected arguments as precisely as possible. That is, write - Functions should list their expected arguments as precisely as possible. That is, write
```nix ```nix
{ stdenv, fetchurl, perl }: ... { stdenv, fetchurl, perl }: <...>
``` ```
instead of instead of
```nix ```nix
args: with args; ... args: with args; <...>
``` ```
or or
```nix ```nix
{ stdenv, fetchurl, perl, ... }: ... { stdenv, fetchurl, perl, ... }: <...>
``` ```
For functions that are truly generic in the number of arguments (such as wrappers around `mkDerivation`) that have some required arguments, you should write them using an `@`-pattern: For functions that are truly generic in the number of arguments (such as wrappers around `mkDerivation`) that have some required arguments, you should write them using an `@`-pattern:
@ -700,7 +704,7 @@ Names of files and directories should be in lowercase, with dashes between words
{ stdenv, doCoverageAnalysis ? false, ... } @ args: { stdenv, doCoverageAnalysis ? false, ... } @ args:
stdenv.mkDerivation (args // { stdenv.mkDerivation (args // {
... if doCoverageAnalysis then "bla" else "" ... foo = if doCoverageAnalysis then "bla" else "";
}) })
``` ```
@ -710,32 +714,40 @@ Names of files and directories should be in lowercase, with dashes between words
args: args:
args.stdenv.mkDerivation (args // { args.stdenv.mkDerivation (args // {
... if args ? doCoverageAnalysis && args.doCoverageAnalysis then "bla" else "" ... foo = if args ? doCoverageAnalysis && args.doCoverageAnalysis then "bla" else "";
}) })
``` ```
- Unnecessary string conversions should be avoided. Do - Unnecessary string conversions should be avoided. Do
```nix ```nix
rev = version; {
rev = version;
}
``` ```
instead of instead of
```nix ```nix
rev = "${version}"; {
rev = "${version}";
}
``` ```
- Building lists conditionally _should_ be done with `lib.optional(s)` instead of using `if cond then [ ... ] else null` or `if cond then [ ... ] else [ ]`. - Building lists conditionally _should_ be done with `lib.optional(s)` instead of using `if cond then [ ... ] else null` or `if cond then [ ... ] else [ ]`.
```nix ```nix
buildInputs = lib.optional stdenv.isDarwin iconv; {
buildInputs = lib.optional stdenv.isDarwin iconv;
}
``` ```
instead of instead of
```nix ```nix
buildInputs = if stdenv.isDarwin then [ iconv ] else null; {
buildInputs = if stdenv.isDarwin then [ iconv ] else null;
}
``` ```
As an exception, an explicit conditional expression with null can be used when fixing a important bug without triggering a mass rebuild. As an exception, an explicit conditional expression with null can be used when fixing a important bug without triggering a mass rebuild.

View file

@ -29,8 +29,8 @@
* [Discourse Forum](https://discourse.nixos.org/) * [Discourse Forum](https://discourse.nixos.org/)
* [Matrix Chat](https://matrix.to/#/#community:nixos.org) * [Matrix Chat](https://matrix.to/#/#community:nixos.org)
* [NixOS Weekly](https://weekly.nixos.org/) * [NixOS Weekly](https://weekly.nixos.org/)
* [Community-maintained wiki](https://nixos.wiki/) * [Official wiki](https://wiki.nixos.org/)
* [Community-maintained list of ways to get in touch](https://nixos.wiki/wiki/Get_In_Touch#Chat) (Discord, Telegram, IRC, etc.) * [Community-maintained list of ways to get in touch](https://wiki.nixos.org/wiki/Get_In_Touch#Chat) (Discord, Telegram, IRC, etc.)
# Other Project Repositories # Other Project Repositories

View file

@ -1,66 +1,161 @@
# Fetchers {#chap-pkgs-fetchers} # Fetchers {#chap-pkgs-fetchers}
Building software with Nix often requires downloading source code and other files from the internet. Building software with Nix often requires downloading source code and other files from the internet.
To this end, Nixpkgs provides *fetchers*: functions to obtain remote sources via various protocols and services. To this end, we use functions that we call _fetchers_, which obtain remote sources via various protocols and services.
Nix provides built-in fetchers such as [`builtins.fetchTarball`](https://nixos.org/manual/nix/stable/language/builtins.html#builtins-fetchTarball).
Nixpkgs provides its own fetchers, which work differently:
Nixpkgs fetchers differ from built-in fetchers such as [`builtins.fetchTarball`](https://nixos.org/manual/nix/stable/language/builtins.html#builtins-fetchTarball):
- A built-in fetcher will download and cache files at evaluation time and produce a [store path](https://nixos.org/manual/nix/stable/glossary#gloss-store-path). - A built-in fetcher will download and cache files at evaluation time and produce a [store path](https://nixos.org/manual/nix/stable/glossary#gloss-store-path).
A Nixpkgs fetcher will create a ([fixed-output](https://nixos.org/manual/nix/stable/glossary#gloss-fixed-output-derivation)) [derivation](https://nixos.org/manual/nix/stable/language/derivations), and files are downloaded at build time. A Nixpkgs fetcher will create a ([fixed-output](https://nixos.org/manual/nix/stable/glossary#gloss-fixed-output-derivation)) [derivation](https://nixos.org/manual/nix/stable/glossary#gloss-derivation), and files are downloaded at build time.
- Built-in fetchers will invalidate their cache after [`tarball-ttl`](https://nixos.org/manual/nix/stable/command-ref/conf-file#conf-tarball-ttl) expires, and will require network activity to check if the cache entry is up to date. - Built-in fetchers will invalidate their cache after [`tarball-ttl`](https://nixos.org/manual/nix/stable/command-ref/conf-file#conf-tarball-ttl) expires, and will require network activity to check if the cache entry is up to date.
Nixpkgs fetchers only re-download if the specified hash changes or the store object is not otherwise available. Nixpkgs fetchers only re-download if the specified hash changes or the store object is not available.
- Built-in fetchers do not use [substituters](https://nixos.org/manual/nix/stable/command-ref/conf-file#conf-substituters). - Built-in fetchers do not use [substituters](https://nixos.org/manual/nix/stable/command-ref/conf-file#conf-substituters).
Derivations produced by Nixpkgs fetchers will use any configured binary cache transparently. Derivations produced by Nixpkgs fetchers will use any configured binary cache transparently.
This significantly reduces the time needed to evaluate the entirety of Nixpkgs, and allows [Hydra](https://nixos.org/hydra) to retain and re-distribute sources used by Nixpkgs in the [public binary cache](https://cache.nixos.org). This significantly reduces the time needed to evaluate Nixpkgs, and allows [Hydra](https://nixos.org/hydra) to retain and re-distribute sources used by Nixpkgs in the [public binary cache](https://cache.nixos.org).
For these reasons, built-in fetchers are not allowed in Nixpkgs source code. For these reasons, Nix's built-in fetchers are not allowed in Nixpkgs.
The following table shows an overview of the differences: The following table summarises the differences:
| Fetchers | Download | Output | Cache | Re-download when | | Fetchers | Download | Output | Cache | Re-download when |
|-|-|-|-|-| |-|-|-|-|-|
| `builtins.fetch*` | evaluation time | store path | `/nix/store`, `~/.cache/nix` | `tarball-ttl` expires, cache miss in `~/.cache/nix`, output store object not in local store | | `builtins.fetch*` | evaluation time | store path | `/nix/store`, `~/.cache/nix` | `tarball-ttl` expires, cache miss in `~/.cache/nix`, output store object not in local store |
| `pkgs.fetch*` | build time | derivation | `/nix/store`, substituters | output store object not available | | `pkgs.fetch*` | build time | derivation | `/nix/store`, substituters | output store object not available |
:::{.tip}
`pkgs.fetchFrom*` helpers retrieve _snapshots_ of version-controlled sources, as opposed to the entire version history, which is more efficient.
`pkgs.fetchgit` by default also has the same behaviour, but can be changed through specific attributes given to it.
:::
## Caveats {#chap-pkgs-fetchers-caveats} ## Caveats {#chap-pkgs-fetchers-caveats}
The fact that the hash belongs to the Nix derivation output and not the file itself can lead to confusion. Because Nixpkgs fetchers are fixed-output derivations, an [output hash](https://nixos.org/manual/nix/stable/language/advanced-attributes#adv-attr-outputHash) has to be specified, usually indirectly through a `hash` attribute.
For example, consider the following fetcher: This hash refers to the derivation output, which can be different from the remote source itself!
```nix This has the following implications that you should be aware of:
fetchurl {
url = "http://www.example.org/hello-1.0.tar.gz";
hash = "sha256-lTeyxzJNQeMdu1IVdovNMtgn77jRIhSybLdMbTkf2Ww=";
};
```
A common mistake is to update a fetchers URL, or a version parameter, without updating the hash. - Use Nix (or Nix-aware) tooling to produce the output hash.
```nix - When changing any fetcher parameters, always update the output hash.
fetchurl { Use one of the methods from [](#sec-pkgs-fetchers-updating-source-hashes).
url = "http://www.example.org/hello-1.1.tar.gz"; Otherwise, existing store objects that match the output hash will be re-used rather than fetching new content.
hash = "sha256-lTeyxzJNQeMdu1IVdovNMtgn77jRIhSybLdMbTkf2Ww=";
};
```
**This will reuse the old contents**. :::{.note}
Remember to invalidate the hash argument, in this case by setting the `hash` attribute to an empty string. A similar problem arises while testing changes to a fetcher's implementation.
If the output of the derivation already exists in the Nix store, test failures can go undetected.
The [`invalidateFetcherByDrvHash`](#tester-invalidateFetcherByDrvHash) function helps prevent reusing cached derivations.
:::
```nix ## Updating source hashes {#sec-pkgs-fetchers-updating-source-hashes}
fetchurl {
url = "http://www.example.org/hello-1.1.tar.gz";
hash = "";
};
```
Use the resulting error message to determine the correct hash. There are several ways to obtain the hash corresponding to a remote source.
Unless you understand how the fetcher you're using calculates the hash from the downloaded contents, you should use [the fake hash method](#sec-pkgs-fetchers-updating-source-hashes-fakehash-method).
``` 1. []{#sec-pkgs-fetchers-updating-source-hashes-fakehash-method} The fake hash method: In your package recipe, set the hash to one of
error: hash mismatch in fixed-output derivation '/path/to/my.drv':
specified: sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
got: sha256-lTeyxzJNQeMdu1IVdovNMtgn77jRIhSybLdMbTkf2Ww=
```
A similar problem arises while testing changes to a fetcher's implementation. If the output of the derivation already exists in the Nix store, test failures can go undetected. The [`invalidateFetcherByDrvHash`](#tester-invalidateFetcherByDrvHash) function helps prevent reusing cached derivations. - `""`
- `lib.fakeHash`
- `lib.fakeSha256`
- `lib.fakeSha512`
Attempt to build, extract the calculated hashes from error messages, and put them into the recipe.
:::{.warning}
You must use one of these four fake hashes and not some arbitrarily-chosen hash.
See [](#sec-pkgs-fetchers-secure-hashes) for details.
:::
:::{.example #ex-fetchers-update-fod-hash}
# Update source hash with the fake hash method
Consider the following recipe that produces a plain file:
```nix
{ fetchurl }:
fetchurl {
url = "https://raw.githubusercontent.com/NixOS/nixpkgs/23.05/.version";
hash = "sha256-ZHl1emidXVojm83LCVrwULpwIzKE/mYwfztVkvpruOM=";
}
```
A common mistake is to update a fetcher parameter, such as `url`, without updating the hash:
```nix
{ fetchurl }:
fetchurl {
url = "https://raw.githubusercontent.com/NixOS/nixpkgs/23.11/.version";
hash = "sha256-ZHl1emidXVojm83LCVrwULpwIzKE/mYwfztVkvpruOM=";
}
```
**This will produce the same output as before!**
Set the hash to an empty string:
```nix
{ fetchurl }:
fetchurl {
url = "https://raw.githubusercontent.com/NixOS/nixpkgs/23.11/.version";
hash = "";
}
```
When building the package, use the error message to determine the correct hash:
```shell
$ nix-build
(some output removed for clarity)
error: hash mismatch in fixed-output derivation '/nix/store/7yynn53jpc93l76z9zdjj4xdxgynawcw-version.drv':
specified: sha256-AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
got: sha256-BZqI7r0MNP29yGH5+yW2tjU9OOpOCEvwWKrWCv5CQ0I=
error: build of '/nix/store/bqdjcw5ij5ymfbm41dq230chk9hdhqff-version.drv' failed
```
:::
2. Prefetch the source with [`nix-prefetch-<type> <URL>`](https://search.nixos.org/packages?buckets={%22package_attr_set%22%3A[%22No%20package%20set%22]%2C%22package_license_set%22%3A[]%2C%22package_maintainers_set%22%3A[]%2C%22package_platforms%22%3A[]}&query=nix-prefetch), where `<type>` is one of
- `url`
- `git`
- `hg`
- `cvs`
- `bzr`
- `svn`
The hash is printed to stdout.
3. Prefetch by package source (with `nix-prefetch-url '<nixpkgs>' -A <package>.src`, where `<package>` is package attribute name).
The hash is printed to stdout.
This works well when you've upgraded the existing package version and want to find out new hash, but is useless if the package can't be accessed by attribute or the package has multiple sources (`.srcs`, architecture-dependent sources, etc).
4. Upstream hash: use it when upstream provides `sha256` or `sha512`.
Don't use it when upstream provides `md5`, compute `sha256` instead.
A little nuance is that `nix-prefetch-*` tools produce hashes with the `nix32` encoding (a Nix-specific base32 adaptation), but upstream usually provides hexadecimal (`base16`) encoding.
Fetchers understand both formats.
Nixpkgs does not standardise on any one format.
You can convert between hash formats with [`nix-hash`](https://nixos.org/manual/nix/stable/command-ref/nix-hash).
5. Extract the hash from a local source archive with `sha256sum`.
Use `nix-prefetch-url file:///path/to/archive` if you want the custom Nix `base32` hash.
## Obtaining hashes securely {#sec-pkgs-fetchers-secure-hashes}
It's always a good idea to avoid Man-in-the-Middle (MITM) attacks when downloading source contents.
Otherwise, you could unknowingly download malware instead of the intended source, and instead of the actual source hash, you'll end up using the hash of malware.
Here are security considerations for this scenario:
- `http://` URLs are not secure to prefetch hashes.
- Upstream hashes should be obtained via a secure protocol.
- `https://` URLs give you more protections when using `nix-prefetch-*` or for upstream hashes.
- `https://` URLs are secure when using the [fake hash method](#sec-pkgs-fetchers-updating-source-hashes-fakehash-method) *only if* you use one of the listed fake hashes.
If you use any other hash, the download will be exposed to MITM attacks even if you use HTTPS URLs.
In more concrete terms, if you use any other hash, the [`--insecure` flag](https://curl.se/docs/manpage.html#-k) will be passed to the underlying call to `curl` when downloading content.
## `fetchurl` and `fetchzip` {#fetchurl} ## `fetchurl` and `fetchzip` {#fetchurl}
@ -123,7 +218,7 @@ Here is an example of `fetchDebianPatch` in action:
buildPythonPackage rec { buildPythonPackage rec {
pname = "pysimplesoap"; pname = "pysimplesoap";
version = "1.16.2"; version = "1.16.2";
src = ...; src = <...>;
patches = [ patches = [
(fetchDebianPatch { (fetchDebianPatch {
@ -134,7 +229,7 @@ buildPythonPackage rec {
}) })
]; ];
... # ...
} }
``` ```
@ -243,7 +338,7 @@ This is a useful last-resort workaround for license restrictions that prohibit r
If the requested file is present in the Nix store, the resulting derivation will not be built, because its expected output is already available. If the requested file is present in the Nix store, the resulting derivation will not be built, because its expected output is already available.
Otherwise, the builder will run, but fail with a message explaining to the user how to provide the file. The following code, for example: Otherwise, the builder will run, but fail with a message explaining to the user how to provide the file. The following code, for example:
``` ```nix
requireFile { requireFile {
name = "jdk-${version}_linux-x64_bin.tar.gz"; name = "jdk-${version}_linux-x64_bin.tar.gz";
url = "https://www.oracle.com/java/technologies/javase-jdk11-downloads.html"; url = "https://www.oracle.com/java/technologies/javase-jdk11-downloads.html";
@ -270,7 +365,7 @@ It produces packages that cannot be built automatically.
`fetchtorrent` expects two arguments. `url` which can either be a Magnet URI (Magnet Link) such as `magnet:?xt=urn:btih:dd8255ecdc7ca55fb0bbf81323d87062db1f6d1c` or an HTTP URL pointing to a `.torrent` file. It can also take a `config` argument which will craft a `settings.json` configuration file and give it to `transmission`, the underlying program that is performing the fetch. The available config options for `transmission` can be found [here](https://github.com/transmission/transmission/blob/main/docs/Editing-Configuration-Files.md#options) `fetchtorrent` expects two arguments. `url` which can either be a Magnet URI (Magnet Link) such as `magnet:?xt=urn:btih:dd8255ecdc7ca55fb0bbf81323d87062db1f6d1c` or an HTTP URL pointing to a `.torrent` file. It can also take a `config` argument which will craft a `settings.json` configuration file and give it to `transmission`, the underlying program that is performing the fetch. The available config options for `transmission` can be found [here](https://github.com/transmission/transmission/blob/main/docs/Editing-Configuration-Files.md#options)
``` ```nix
{ fetchtorrent }: { fetchtorrent }:
fetchtorrent { fetchtorrent {

View file

@ -1177,6 +1177,7 @@ dockerTools.buildImage {
hello hello
dockerTools.binSh dockerTools.binSh
]; ];
}
``` ```
After building the image and loading it in Docker, we can create a container based on it and enter a shell inside the container. After building the image and loading it in Docker, we can create a container based on it and enter a shell inside the container.

View file

@ -9,13 +9,17 @@ However, we can tell Nix explicitly what the previous build state was, by repres
To change a normal derivation to a checkpoint based build, these steps must be taken: To change a normal derivation to a checkpoint based build, these steps must be taken:
- apply `prepareCheckpointBuild` on the desired derivation, e.g. - apply `prepareCheckpointBuild` on the desired derivation, e.g.
```nix ```nix
checkpointArtifacts = (pkgs.checkpointBuildTools.prepareCheckpointBuild pkgs.virtualbox); {
checkpointArtifacts = (pkgs.checkpointBuildTools.prepareCheckpointBuild pkgs.virtualbox);
}
``` ```
- change something you want in the sources of the package, e.g. use a source override: - change something you want in the sources of the package, e.g. use a source override:
```nix ```nix
changedVBox = pkgs.virtualbox.overrideAttrs (old: { {
src = path/to/vbox/sources; changedVBox = pkgs.virtualbox.overrideAttrs (old: {
}); src = path/to/vbox/sources;
});
}
``` ```
- use `mkCheckpointBuild changedVBox checkpointArtifacts` - use `mkCheckpointBuild changedVBox checkpointArtifacts`
- enjoy shorter build times - enjoy shorter build times

View file

@ -14,11 +14,13 @@ If the `moduleNames` argument is omitted, `hasPkgConfigModules` will use `meta.p
# Check that `pkg-config` modules are exposed using default values # Check that `pkg-config` modules are exposed using default values
```nix ```nix
passthru.tests.pkg-config = testers.hasPkgConfigModules { {
package = finalAttrs.finalPackage; passthru.tests.pkg-config = testers.hasPkgConfigModules {
}; package = finalAttrs.finalPackage;
};
meta.pkgConfigModules = [ "libfoo" ]; meta.pkgConfigModules = [ "libfoo" ];
}
``` ```
::: :::
@ -28,10 +30,12 @@ meta.pkgConfigModules = [ "libfoo" ];
# Check that `pkg-config` modules are exposed using explicit module names # Check that `pkg-config` modules are exposed using explicit module names
```nix ```nix
passthru.tests.pkg-config = testers.hasPkgConfigModules { {
package = finalAttrs.finalPackage; passthru.tests.pkg-config = testers.hasPkgConfigModules {
moduleNames = [ "libfoo" ]; package = finalAttrs.finalPackage;
}; moduleNames = [ "libfoo" ];
};
}
``` ```
::: :::
@ -55,7 +59,9 @@ The default argument to the command is `--version`, and the version to be checke
This example will run the command `hello --version`, and then check that the version of the `hello` package is in the output of the command. This example will run the command `hello --version`, and then check that the version of the `hello` package is in the output of the command.
```nix ```nix
passthru.tests.version = testers.testVersion { package = hello; }; {
passthru.tests.version = testers.testVersion { package = hello; };
}
``` ```
::: :::
@ -70,13 +76,15 @@ This means that an output like "leetcode 0.4.21" would fail the tests, and an ou
A common usage of the `version` attribute is to specify `version = "v${version}"`. A common usage of the `version` attribute is to specify `version = "v${version}"`.
```nix ```nix
version = "0.4.2"; {
version = "0.4.2";
passthru.tests.version = testers.testVersion { passthru.tests.version = testers.testVersion {
package = leetcode-cli; package = leetcode-cli;
command = "leetcode -V"; command = "leetcode -V";
version = "leetcode ${version}"; version = "leetcode ${version}";
}; };
}
``` ```
::: :::
@ -116,7 +124,7 @@ runCommand "example" {
grep -F 'failing though' $failed/testBuildFailure.log grep -F 'failing though' $failed/testBuildFailure.log
[[ 3 = $(cat $failed/testBuildFailure.exit) ]] [[ 3 = $(cat $failed/testBuildFailure.exit) ]]
touch $out touch $out
''; ''
``` ```
::: :::
@ -193,12 +201,14 @@ once to get a derivation hash, and again to produce the final fixed output deriv
# Prevent nix from reusing the output of a fetcher # Prevent nix from reusing the output of a fetcher
```nix ```nix
tests.fetchgit = testers.invalidateFetcherByDrvHash fetchgit { {
name = "nix-source"; tests.fetchgit = testers.invalidateFetcherByDrvHash fetchgit {
url = "https://github.com/NixOS/nix"; name = "nix-source";
rev = "9d9dbe6ed05854e03811c361a3380e09183f4f4a"; url = "https://github.com/NixOS/nix";
hash = "sha256-7DszvbCNTjpzGRmpIVAWXk20P0/XTrWZ79KSOGLrUWY="; rev = "9d9dbe6ed05854e03811c361a3380e09183f4f4a";
}; hash = "sha256-7DszvbCNTjpzGRmpIVAWXk20P0/XTrWZ79KSOGLrUWY=";
};
}
``` ```
::: :::

View file

@ -76,12 +76,14 @@ If you need to refer to the resulting files somewhere else in a Nix expression,
For example, if the file destination is a directory: For example, if the file destination is a directory:
```nix ```nix
my-file = writeTextFile { {
name = "my-file"; my-file = writeTextFile {
text = '' name = "my-file";
Contents of File text = ''
''; Contents of File
destination = "/share/my-file"; '';
destination = "/share/my-file";
};
} }
``` ```
@ -90,7 +92,7 @@ Remember to append "/share/my-file" to the resulting store path when using it el
```nix ```nix
writeShellScript "evaluate-my-file.sh" '' writeShellScript "evaluate-my-file.sh" ''
cat ${my-file}/share/my-file cat ${my-file}/share/my-file
''; ''
``` ```
:::: ::::
@ -287,7 +289,7 @@ writeTextFile {
}; };
allowSubstitutes = true; allowSubstitutes = true;
preferLocalBuild = false; preferLocalBuild = false;
}; }
``` ```
::: :::
@ -351,7 +353,7 @@ Write the string `Contents of File` to `/nix/store/<store path>`:
writeText "my-file" writeText "my-file"
'' ''
Contents of File Contents of File
''; ''
``` ```
::: :::
@ -391,7 +393,7 @@ Write the string `Contents of File` to `/nix/store/<store path>/share/my-file`:
writeTextDir "share/my-file" writeTextDir "share/my-file"
'' ''
Contents of File Contents of File
''; ''
``` ```
::: :::
@ -433,7 +435,7 @@ Write the string `Contents of File` to `/nix/store/<store path>` and make the fi
writeScript "my-file" writeScript "my-file"
'' ''
Contents of File Contents of File
''; ''
``` ```
::: :::
@ -475,7 +477,7 @@ The store path will include the the name, and it will be a directory.
writeScriptBin "my-script" writeScriptBin "my-script"
'' ''
echo "hi" echo "hi"
''; ''
``` ```
::: :::
@ -519,7 +521,7 @@ This function is almost exactly like [](#trivial-builder-writeScript), except th
writeShellScript "my-script" writeShellScript "my-script"
'' ''
echo "hi" echo "hi"
''; ''
``` ```
::: :::
@ -562,7 +564,7 @@ This function is a combination of [](#trivial-builder-writeShellScript) and [](#
writeShellScriptBin "my-script" writeShellScriptBin "my-script"
'' ''
echo "hi" echo "hi"
''; ''
``` ```
::: :::
@ -674,7 +676,7 @@ writeClosure [ (writeScriptBin "hi" ''${hello}/bin/hello'') ]
produces an output path `/nix/store/<hash>-runtime-deps` containing produces an output path `/nix/store/<hash>-runtime-deps` containing
```nix ```
/nix/store/<hash>-hello-2.10 /nix/store/<hash>-hello-2.10
/nix/store/<hash>-hi /nix/store/<hash>-hi
/nix/store/<hash>-libidn2-2.3.0 /nix/store/<hash>-libidn2-2.3.0
@ -700,7 +702,7 @@ writeDirectReferencesToFile (writeScriptBin "hi" ''${hello}/bin/hello'')
produces an output path `/nix/store/<hash>-runtime-references` containing produces an output path `/nix/store/<hash>-runtime-references` containing
```nix ```
/nix/store/<hash>-hello-2.10 /nix/store/<hash>-hello-2.10
``` ```

View file

@ -7,27 +7,30 @@
`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. `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 ```nix
{ pkgs ? import <nixpkgs> {} }: { pkgs ? import <nixpkgs> {} }: {
nix-gitignore.gitignoreSource [] ./source src = nix-gitignore.gitignoreSource [] ./source;
# Simplest version # Simplest version
nix-gitignore.gitignoreSource "supplemental-ignores\n" ./source src = nix-gitignore.gitignoreSource "supplemental-ignores\n" ./source;
# This one reads the ./source/.gitignore and concats the auxiliary ignores # This one reads the ./source/.gitignore and concats the auxiliary ignores
nix-gitignore.gitignoreSourcePure "ignore-this\nignore-that\n" ./source src = nix-gitignore.gitignoreSourcePure "ignore-this\nignore-that\n" ./source;
# Use this string as gitignore, don't read ./source/.gitignore. # Use this string as gitignore, don't read ./source/.gitignore.
nix-gitignore.gitignoreSourcePure ["ignore-this\nignore-that\n", ~/.gitignore] ./source src = nix-gitignore.gitignoreSourcePure ["ignore-this\nignore-that\n" ~/.gitignore] ./source;
# It also accepts a list (of strings and paths) that will be concatenated # It also accepts a list (of strings and paths) that will be concatenated
# once the paths are turned to strings via readFile. # once the paths are turned to strings via readFile.
}
``` ```
These functions are derived from the `Filter` functions by setting the first filter argument to `(_: _: true)`: These functions are derived from the `Filter` functions by setting the first filter argument to `(_: _: true)`:
```nix ```nix
gitignoreSourcePure = gitignoreFilterSourcePure (_: _: true); {
gitignoreSource = gitignoreFilterSource (_: _: true); gitignoreSourcePure = gitignoreFilterSourcePure (_: _: true);
gitignoreSource = gitignoreFilterSource (_: _: true);
}
``` ```
Those filter functions accept the same arguments the `builtins.filterSource` function would pass to its filters, thus `fn: gitignoreFilterSourcePure fn ""` should be extensionally equivalent to `filterSource`. The file is blacklisted if it's blacklisted by either your filter or the gitignoreFilter. Those filter functions accept the same arguments the `builtins.filterSource` function would pass to its filters, thus `fn: gitignoreFilterSourcePure fn ""` should be extensionally equivalent to `filterSource`. The file is blacklisted if it's blacklisted by either your filter or the gitignoreFilter.
@ -35,7 +38,9 @@ Those filter functions accept the same arguments the `builtins.filterSource` fun
If you want to make your own filter from scratch, you may use If you want to make your own filter from scratch, you may use
```nix ```nix
gitignoreFilter = ign: root: filterPattern (gitignoreToPatterns ign) root; {
gitignoreFilter = ign: root: filterPattern (gitignoreToPatterns ign) root;
}
``` ```
## gitignore files in subdirectories {#sec-pkgs-nix-gitignore-usage-recursive} ## gitignore files in subdirectories {#sec-pkgs-nix-gitignore-usage-recursive}
@ -43,7 +48,9 @@ gitignoreFilter = ign: root: filterPattern (gitignoreToPatterns ign) root;
If you wish to use a filter that would search for .gitignore files in subdirectories, just like git does by default, use this function: If you wish to use a filter that would search for .gitignore files in subdirectories, just like git does by default, use this function:
```nix ```nix
gitignoreFilterRecursiveSource = filter: patterns: root: {
# OR # gitignoreFilterRecursiveSource = filter: patterns: root:
gitignoreRecursiveSource = gitignoreFilterSourcePure (_: _: true); # OR
gitignoreRecursiveSource = gitignoreFilterSourcePure (_: _: true);
}
``` ```

View file

@ -3,7 +3,9 @@
This hook will make a build pause instead of stopping when a failure happens. It prevents nix from cleaning up the build environment immediately and allows the user to attach to a build environment using the `cntr` command. Upon build error it will print instructions on how to use `cntr`, which can be used to enter the environment for debugging. Installing cntr and running the command will provide shell access to the build sandbox of failed build. At `/var/lib/cntr` the sandboxed filesystem is mounted. All commands and files of the system are still accessible within the shell. To execute commands from the sandbox use the cntr exec subcommand. `cntr` is only supported on Linux-based platforms. To use it first add `cntr` to your `environment.systemPackages` on NixOS or alternatively to the root user on non-NixOS systems. Then in the package that is supposed to be inspected, add `breakpointHook` to `nativeBuildInputs`. This hook will make a build pause instead of stopping when a failure happens. It prevents nix from cleaning up the build environment immediately and allows the user to attach to a build environment using the `cntr` command. Upon build error it will print instructions on how to use `cntr`, which can be used to enter the environment for debugging. Installing cntr and running the command will provide shell access to the build sandbox of failed build. At `/var/lib/cntr` the sandboxed filesystem is mounted. All commands and files of the system are still accessible within the shell. To execute commands from the sandbox use the cntr exec subcommand. `cntr` is only supported on Linux-based platforms. To use it first add `cntr` to your `environment.systemPackages` on NixOS or alternatively to the root user on non-NixOS systems. Then in the package that is supposed to be inspected, add `breakpointHook` to `nativeBuildInputs`.
```nix ```nix
nativeBuildInputs = [ breakpointHook ]; {
nativeBuildInputs = [ breakpointHook ];
}
``` ```
When a build failure happens there will be an instruction printed that shows how to attach with `cntr` to the build sandbox. When a build failure happens there will be an instruction printed that shows how to attach with `cntr` to the build sandbox.

View file

@ -7,19 +7,21 @@ The `installManPage` function takes one or more paths to manpages to install. Th
The `installShellCompletion` function takes one or more paths to shell completion files. By default it will autodetect the shell type from the completion file extension, but you may also specify it by passing one of `--bash`, `--fish`, or `--zsh`. These flags apply to all paths listed after them (up until another shell flag is given). Each path may also have a custom installation name provided by providing a flag `--name NAME` before the path. If this flag is not provided, zsh completions will be renamed automatically such that `foobar.zsh` becomes `_foobar`. A root name may be provided for all paths using the flag `--cmd NAME`; this synthesizes the appropriate name depending on the shell (e.g. `--cmd foo` will synthesize the name `foo.bash` for bash and `_foo` for zsh). The path may also be a fifo or named fd (such as produced by `<(cmd)`), in which case the shell and name must be provided. The `installShellCompletion` function takes one or more paths to shell completion files. By default it will autodetect the shell type from the completion file extension, but you may also specify it by passing one of `--bash`, `--fish`, or `--zsh`. These flags apply to all paths listed after them (up until another shell flag is given). Each path may also have a custom installation name provided by providing a flag `--name NAME` before the path. If this flag is not provided, zsh completions will be renamed automatically such that `foobar.zsh` becomes `_foobar`. A root name may be provided for all paths using the flag `--cmd NAME`; this synthesizes the appropriate name depending on the shell (e.g. `--cmd foo` will synthesize the name `foo.bash` for bash and `_foo` for zsh). The path may also be a fifo or named fd (such as produced by `<(cmd)`), in which case the shell and name must be provided.
```nix ```nix
nativeBuildInputs = [ installShellFiles ]; {
postInstall = '' nativeBuildInputs = [ installShellFiles ];
installManPage doc/foobar.1 doc/barfoo.3 postInstall = ''
# explicit behavior installManPage doc/foobar.1 doc/barfoo.3
installShellCompletion --bash --name foobar.bash share/completions.bash # explicit behavior
installShellCompletion --fish --name foobar.fish share/completions.fish installShellCompletion --bash --name foobar.bash share/completions.bash
installShellCompletion --zsh --name _foobar share/completions.zsh installShellCompletion --fish --name foobar.fish share/completions.fish
# implicit behavior installShellCompletion --zsh --name _foobar share/completions.zsh
installShellCompletion share/completions/foobar.{bash,fish,zsh} # implicit behavior
# using named fd installShellCompletion share/completions/foobar.{bash,fish,zsh}
installShellCompletion --cmd foobar \ # using named fd
--bash <($out/bin/foobar --bash-completion) \ installShellCompletion --cmd foobar \
--fish <($out/bin/foobar --fish-completion) \ --bash <($out/bin/foobar --bash-completion) \
--zsh <($out/bin/foobar --zsh-completion) --fish <($out/bin/foobar --fish-completion) \
''; --zsh <($out/bin/foobar --zsh-completion)
'';
}
``` ```

View file

@ -12,13 +12,14 @@ Example:
```nix ```nix
{ mpiCheckPhaseHook, mpi, ... }: { mpiCheckPhaseHook, mpi, ... }:
{
# ...
... nativeCheckInputs = [
openssh
nativeCheckInputs = [ mpiCheckPhaseHook
openssh ];
mpiCheckPhaseHook }
];
``` ```

View file

@ -114,7 +114,7 @@ This can be overridden by a different version of `ghc` as follows:
```nix ```nix
agda.withPackages { agda.withPackages {
pkgs = [ ... ]; pkgs = [ /* ... */ ];
ghc = haskell.compiler.ghcHEAD; ghc = haskell.compiler.ghcHEAD;
} }
``` ```
@ -180,6 +180,7 @@ To add an Agda package to `nixpkgs`, the derivation should be written to `pkgs/d
```nix ```nix
{ mkDerivation, standard-library, fetchFromGitHub }: { mkDerivation, standard-library, fetchFromGitHub }:
{}
``` ```
Note that the derivation function is called with `mkDerivation` set to `agdaPackages.mkDerivation`, therefore you Note that the derivation function is called with `mkDerivation` set to `agdaPackages.mkDerivation`, therefore you
@ -193,7 +194,7 @@ mkDerivation {
version = "1.5.0"; version = "1.5.0";
pname = "iowa-stdlib"; pname = "iowa-stdlib";
src = ... src = <...>;
libraryFile = ""; libraryFile = "";
libraryName = "IAL-1.3"; libraryName = "IAL-1.3";

View file

@ -104,18 +104,20 @@ pull from:
repo.json to the Nix store based on the given repository XMLs. repo.json to the Nix store based on the given repository XMLs.
```nix ```nix
repoXmls = { {
packages = [ ./xml/repository2-1.xml ]; repoXmls = {
images = [ packages = [ ./xml/repository2-1.xml ];
./xml/android-sys-img2-1.xml images = [
./xml/android-tv-sys-img2-1.xml ./xml/android-sys-img2-1.xml
./xml/android-wear-sys-img2-1.xml ./xml/android-tv-sys-img2-1.xml
./xml/android-wear-cn-sys-img2-1.xml ./xml/android-wear-sys-img2-1.xml
./xml/google_apis-sys-img2-1.xml ./xml/android-wear-cn-sys-img2-1.xml
./xml/google_apis_playstore-sys-img2-1.xml ./xml/google_apis-sys-img2-1.xml
]; ./xml/google_apis_playstore-sys-img2-1.xml
addons = [ ./xml/addon2-1.xml ]; ];
}; addons = [ ./xml/addon2-1.xml ];
};
}
``` ```
When building the above expression with: When building the above expression with:

View file

@ -117,6 +117,7 @@ If there are git dependencies.
- From the mix_deps.nix file, remove the dependencies that had git versions and pass them as an override to the import function. - From the mix_deps.nix file, remove the dependencies that had git versions and pass them as an override to the import function.
```nix ```nix
{
mixNixDeps = import ./mix.nix { mixNixDeps = import ./mix.nix {
inherit beamPackages lib; inherit beamPackages lib;
overrides = (final: prev: { overrides = (final: prev: {
@ -138,8 +139,9 @@ If there are git dependencies.
# you can re-use the same beamDeps argument as generated # you can re-use the same beamDeps argument as generated
beamDeps = with final; [ prometheus ]; beamDeps = with final; [ prometheus ];
}; };
}); });
}; };
}
``` ```
You will need to run the build process once to fix the hash to correspond to your new git src. You will need to run the build process once to fix the hash to correspond to your new git src.
@ -153,11 +155,13 @@ Practical steps
- start with the following argument to mixRelease - start with the following argument to mixRelease
```nix ```nix
{
mixFodDeps = fetchMixDeps { mixFodDeps = fetchMixDeps {
pname = "mix-deps-${pname}"; pname = "mix-deps-${pname}";
inherit src version; inherit src version;
hash = lib.fakeHash; hash = lib.fakeHash;
}; };
}
``` ```
The first build will complain about the hash value, you can replace with the suggested value after that. The first build will complain about the hash value, you can replace with the suggested value after that.

View file

@ -28,7 +28,7 @@ buildEnv { name = "bower-env"; ignoreCollisions = true; paths = [
(fetchbower "angular" "1.5.3" "~1.5.0" "1749xb0firxdra4rzadm4q9x90v6pzkbd7xmcyjk6qfza09ykk9y") (fetchbower "angular" "1.5.3" "~1.5.0" "1749xb0firxdra4rzadm4q9x90v6pzkbd7xmcyjk6qfza09ykk9y")
(fetchbower "bootstrap" "3.3.6" "~3.3.6" "1vvqlpbfcy0k5pncfjaiskj3y6scwifxygfqnw393sjfxiviwmbv") (fetchbower "bootstrap" "3.3.6" "~3.3.6" "1vvqlpbfcy0k5pncfjaiskj3y6scwifxygfqnw393sjfxiviwmbv")
(fetchbower "jquery" "2.2.2" "1.9.1 - 2" "10sp5h98sqwk90y4k6hbdviwqzvzwqf47r3r51pakch5ii2y7js1") (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. Using the `bower2nix` command line arguments, the output can be redirected to a file. A name like `bower-packages.nix` would be fine.
@ -42,11 +42,13 @@ The function is implemented in [pkgs/development/bower-modules/generic/default.n
### Example buildBowerComponents {#ex-buildBowerComponents} ### Example buildBowerComponents {#ex-buildBowerComponents}
```nix ```nix
bowerComponents = buildBowerComponents { {
name = "my-web-app"; bowerComponents = buildBowerComponents {
generated = ./bower-packages.nix; # note 1 name = "my-web-app";
src = myWebApp; # note 2 generated = ./bower-packages.nix; # note 1
}; src = myWebApp; # note 2
};
}
``` ```
In ["buildBowerComponents" example](#ex-buildBowerComponents) the following arguments are of special significance to the function: In ["buildBowerComponents" example](#ex-buildBowerComponents) the following arguments are of special significance to the function:

View file

@ -13,10 +13,12 @@ done in the typical Nix fashion. For example, to include support for [SRFI
might write: might write:
```nix ```nix
{
buildInputs = [ buildInputs = [
chicken chicken
chickenPackages.chickenEggs.srfi-189 chickenPackages.chickenEggs.srfi-189
]; ];
}
``` ```
Both `chicken` and its eggs have a setup hook which configures the environment Both `chicken` and its eggs have a setup hook which configures the environment
@ -67,12 +69,12 @@ let
chickenEggs = super.chickenEggs.overrideScope' (eggself: eggsuper: { chickenEggs = super.chickenEggs.overrideScope' (eggself: eggsuper: {
srfi-180 = eggsuper.srfi-180.overrideAttrs { srfi-180 = eggsuper.srfi-180.overrideAttrs {
# path to a local copy of srfi-180 # path to a local copy of srfi-180
src = ... src = <...>;
}; };
}); });
}); });
in in
# Here, `myChickenPackages.chickenEggs.json-rpc`, which depends on `srfi-180` will use # Here, `myChickenPackages.chickenEggs.json-rpc`, which depends on `srfi-180` will use
# the local copy of `srfi-180`. # the local copy of `srfi-180`.
# ... <...>
``` ```

View file

@ -56,22 +56,17 @@ Here is a simple package example. It is a pure Coq library, thus it depends on C
{ lib, mkCoqDerivation, version ? null { lib, mkCoqDerivation, version ? null
, coq, mathcomp, mathcomp-finmap, mathcomp-bigenough }: , coq, mathcomp, mathcomp-finmap, mathcomp-bigenough }:
let
inherit (lib) licenses maintainers switch;
inherit (lib.versions) range;
in
mkCoqDerivation { mkCoqDerivation {
/* namePrefix leads to e.g. `name = coq8.11-mathcomp1.11-multinomials-1.5.2` */ /* namePrefix leads to e.g. `name = coq8.11-mathcomp1.11-multinomials-1.5.2` */
namePrefix = [ "coq" "mathcomp" ]; namePrefix = [ "coq" "mathcomp" ];
pname = "multinomials"; pname = "multinomials";
owner = "math-comp"; owner = "math-comp";
inherit version; inherit version;
defaultVersion = with versions; switch [ coq.version mathcomp.version ] [ defaultVersion = with lib.versions; lib.switch [ coq.version mathcomp.version ] [
{ cases = [ (range "8.7" "8.12") "1.11.0" ]; out = "1.5.2"; } { 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.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 = [ (range "8.7" "8.10") (range "1.8" "1.10") ]; out = "1.4"; }
{ cases = [ "8.6" (range "1.6" "1.7") ]; out = "1.1"; } { cases = [ (isEq "8.6") (range "1.6" "1.7") ]; out = "1.1"; }
] null; ] null;
release = { release = {
"1.5.2".sha256 = "15aspf3jfykp1xgsxf8knqkxv8aav2p39c2fyirw7pwsfbsv2c4s"; "1.5.2".sha256 = "15aspf3jfykp1xgsxf8knqkxv8aav2p39c2fyirw7pwsfbsv2c4s";
@ -90,7 +85,7 @@ mkCoqDerivation {
meta = { meta = {
description = "A Coq/SSReflect Library for Monoidal Rings and Multinomials"; description = "A Coq/SSReflect Library for Monoidal Rings and Multinomials";
license = licenses.cecill-c; license = lib.licenses.cecill-c;
}; };
} }
``` ```

View file

@ -33,22 +33,26 @@ crystal.buildCrystalPackage rec {
# Insert the path to your shards.nix file here # Insert the path to your shards.nix file here
shardsFile = ./shards.nix; shardsFile = ./shards.nix;
... # ...
} }
``` ```
This won't build anything yet, because we haven't told it what files build. We can specify a mapping from binary names to source files with the `crystalBinaries` attribute. The project's compilation instructions should show this. For Mint, the binary is called "mint", which is compiled from the source file `src/mint.cr`, so we'll specify this as follows: This won't build anything yet, because we haven't told it what files build. We can specify a mapping from binary names to source files with the `crystalBinaries` attribute. The project's compilation instructions should show this. For Mint, the binary is called "mint", which is compiled from the source file `src/mint.cr`, so we'll specify this as follows:
```nix ```nix
{
crystalBinaries.mint.src = "src/mint.cr"; crystalBinaries.mint.src = "src/mint.cr";
# ... # ...
}
``` ```
Additionally you can override the default `crystal build` options (which are currently `--release --progress --no-debug --verbose`) with Additionally you can override the default `crystal build` options (which are currently `--release --progress --no-debug --verbose`) with
```nix ```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: 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:

View file

@ -16,24 +16,28 @@ To use one or more CUDA packages in an expression, give the expression a `cudaPa
, cudaSupport ? config.cudaSupport , cudaSupport ? config.cudaSupport
, cudaPackages ? { } , cudaPackages ? { }
, ... , ...
}: }: {}
``` ```
When using `callPackage`, you can choose to pass in a different variant, e.g. When using `callPackage`, you can choose to pass in a different variant, e.g.
when a different version of the toolkit suffices when a different version of the toolkit suffices
```nix ```nix
mypkg = callPackage { cudaPackages = cudaPackages_11_5; } {
mypkg = callPackage { cudaPackages = cudaPackages_11_5; };
}
``` ```
If another version of say `cudnn` or `cutensor` is needed, you can override the If another version of say `cudnn` or `cutensor` is needed, you can override the
package set to make it the default. This guarantees you get a consistent package package set to make it the default. This guarantees you get a consistent package
set. set.
```nix ```nix
mypkg = let {
cudaPackages = cudaPackages_11_5.overrideScope (final: prev: { mypkg = let
cudnn = prev.cudnn_8_3; cudaPackages = cudaPackages_11_5.overrideScope (final: prev: {
}}); cudnn = prev.cudnn_8_3;
in callPackage { inherit cudaPackages; }; });
in callPackage { inherit cudaPackages; };
}
``` ```
The CUDA NVCC compiler requires flags to determine which hardware you The CUDA NVCC compiler requires flags to determine which hardware you

View file

@ -26,7 +26,7 @@ Cuelang schemas are similar to JSON, here is a quick cheatsheet:
Nixpkgs provides a `pkgs.writeCueValidator` helper, which will write a validation script based on the provided Cuelang schema. Nixpkgs provides a `pkgs.writeCueValidator` helper, which will write a validation script based on the provided Cuelang schema.
Here is an example: Here is an example:
``` ```nix
pkgs.writeCueValidator pkgs.writeCueValidator
(pkgs.writeText "schema.cue" '' (pkgs.writeText "schema.cue" ''
#Def1: { #Def1: {
@ -42,7 +42,7 @@ pkgs.writeCueValidator
`document` : match your input data against this fragment of structure or definition, e.g. you may use the same schema file but different documents based on the data you are validating. `document` : match your input data against this fragment of structure or definition, e.g. you may use the same schema file but different documents based on the data you are validating.
Another example, given the following `validator.nix` : Another example, given the following `validator.nix` :
``` ```nix
{ pkgs ? import <nixpkgs> {} }: { pkgs ? import <nixpkgs> {} }:
let let
genericValidator = version: genericValidator = version:

View file

@ -187,6 +187,7 @@ wish to specify `source = true` for all Dhall packages, then you can amend the
Dhall overlay like this: Dhall overlay like this:
```nix ```nix
{
dhallOverrides = self: super: { dhallOverrides = self: super: {
# Enable source for all Dhall packages # Enable source for all Dhall packages
buildDhallPackage = buildDhallPackage =
@ -194,6 +195,7 @@ Dhall overlay like this:
true = self.callPackage ./true.nix { }; true = self.callPackage ./true.nix { };
}; };
}
``` ```
… and now the Prelude will contain the fully decoded result of interpreting … and now the Prelude will contain the fully decoded result of interpreting
@ -429,22 +431,26 @@ $ dhall-to-nixpkgs github https://github.com/dhall-lang/dhall-lang.git \
the Prelude globally for all packages, like this: the Prelude globally for all packages, like this:
```nix ```nix
{
dhallOverrides = self: super: { dhallOverrides = self: super: {
true = self.callPackage ./true.nix { }; true = self.callPackage ./true.nix { };
Prelude = self.callPackage ./Prelude.nix { }; Prelude = self.callPackage ./Prelude.nix { };
}; };
}
``` ```
… or selectively overriding the Prelude dependency for just the `true` package, … or selectively overriding the Prelude dependency for just the `true` package,
like this: like this:
```nix ```nix
{
dhallOverrides = self: super: { dhallOverrides = self: super: {
true = self.callPackage ./true.nix { true = self.callPackage ./true.nix {
Prelude = self.callPackage ./Prelude.nix { }; Prelude = self.callPackage ./Prelude.nix { };
}; };
}; };
}
``` ```
## Overrides {#ssec-dhall-overrides} ## Overrides {#ssec-dhall-overrides}
@ -454,11 +460,13 @@ You can override any of the arguments to `buildDhallGitHubPackage` or
For example, suppose we wanted to selectively enable `source = true` just for the Prelude. We can do that like this: For example, suppose we wanted to selectively enable `source = true` just for the Prelude. We can do that like this:
```nix ```nix
{
dhallOverrides = self: super: { dhallOverrides = self: super: {
Prelude = super.Prelude.overridePackage { source = true; }; Prelude = super.Prelude.overridePackage { source = true; };
# ...
}; };
}
``` ```
[semantic-integrity-checks]: https://docs.dhall-lang.org/tutorials/Language-Tour.html#installing-packages [semantic-integrity-checks]: https://docs.dhall-lang.org/tutorials/Language-Tour.html#installing-packages

View file

@ -134,7 +134,7 @@ Here is an example `default.nix`, using some of the previously discussed argumen
{ lib, buildDotnetModule, dotnetCorePackages, ffmpeg }: { lib, buildDotnetModule, dotnetCorePackages, ffmpeg }:
let let
referencedProject = import ../../bar { ... }; referencedProject = import ../../bar { /* ... */ };
in buildDotnetModule rec { in buildDotnetModule rec {
pname = "someDotnetApplication"; pname = "someDotnetApplication";
version = "0.1"; version = "0.1";
@ -236,7 +236,7 @@ the packages inside the `out` directory.
$ nuget-to-nix out > deps.nix $ nuget-to-nix out > deps.nix
``` ```
Which `nuget-to-nix` will generate an output similar to below Which `nuget-to-nix` will generate an output similar to below
``` ```nix
{ fetchNuGet }: [ { fetchNuGet }: [
(fetchNuGet { pname = "FosterFramework"; version = "0.1.15-alpha"; sha256 = "0pzsdfbsfx28xfqljcwy100xhbs6wyx0z1d5qxgmv3l60di9xkll"; }) (fetchNuGet { pname = "FosterFramework"; version = "0.1.15-alpha"; sha256 = "0pzsdfbsfx28xfqljcwy100xhbs6wyx0z1d5qxgmv3l60di9xkll"; })
(fetchNuGet { pname = "Microsoft.AspNetCore.App.Runtime.linux-x64"; version = "8.0.1"; sha256 = "1gjz379y61ag9whi78qxx09bwkwcznkx2mzypgycibxk61g11da1"; }) (fetchNuGet { pname = "Microsoft.AspNetCore.App.Runtime.linux-x64"; version = "8.0.1"; sha256 = "1gjz379y61ag9whi78qxx09bwkwcznkx2mzypgycibxk61g11da1"; })

View file

@ -47,6 +47,7 @@ When an application uses icons, an icon theme should be available in `XDG_DATA_D
In the rare case you need to use icons from dependencies (e.g. when an app forces an icon theme), you can use the following to pick them up: In the rare case you need to use icons from dependencies (e.g. when an app forces an icon theme), you can use the following to pick them up:
```nix ```nix
{
buildInputs = [ buildInputs = [
pantheon.elementary-icon-theme pantheon.elementary-icon-theme
]; ];
@ -56,6 +57,7 @@ In the rare case you need to use icons from dependencies (e.g. when an app force
--prefix XDG_DATA_DIRS : "$XDG_ICON_DIRS" --prefix XDG_DATA_DIRS : "$XDG_ICON_DIRS"
) )
''; '';
}
``` ```
To avoid costly file system access when locating icons, GTK, [as well as Qt](https://woboq.com/blog/qicon-reads-gtk-icon-cache-in-qt57.html), can rely on `icon-theme.cache` files from the themes' top-level directories. These files are generated using `gtk-update-icon-cache`, which is expected to be run whenever an icon is added or removed to an icon theme (typically an application icon into `hicolor` theme) and some programs do indeed run this after icon installation. However, since packages are installed into their own prefix by Nix, this would lead to conflicts. For that reason, `gtk3` provides a [setup hook](#ssec-gnome-hooks-gtk-drop-icon-theme-cache) that will clean the file from installation. Since most applications only ship their own icon that will be loaded on start-up, it should not affect them too much. On the other hand, icon themes are much larger and more widely used so we need to cache them. Because we recommend installing icon themes globally, we will generate the cache files from all packages in a profile using a NixOS module. You can enable the cache generation using `gtk.iconCache.enable` option if your desktop environment does not already do that. To avoid costly file system access when locating icons, GTK, [as well as Qt](https://woboq.com/blog/qicon-reads-gtk-icon-cache-in-qt57.html), can rely on `icon-theme.cache` files from the themes' top-level directories. These files are generated using `gtk-update-icon-cache`, which is expected to be run whenever an icon is added or removed to an icon theme (typically an application icon into `hicolor` theme) and some programs do indeed run this after icon installation. However, since packages are installed into their own prefix by Nix, this would lead to conflicts. For that reason, `gtk3` provides a [setup hook](#ssec-gnome-hooks-gtk-drop-icon-theme-cache) that will clean the file from installation. Since most applications only ship their own icon that will be loaded on start-up, it should not affect them too much. On the other hand, icon themes are much larger and more widely used so we need to cache them. Because we recommend installing icon themes globally, we will generate the cache files from all packages in a profile using a NixOS module. You can enable the cache generation using `gtk.iconCache.enable` option if your desktop environment does not already do that.
@ -85,17 +87,19 @@ If your application uses [GStreamer](https://gstreamer.freedesktop.org/) or [Gri
Given the requirements above, the package expression would become messy quickly: Given the requirements above, the package expression would become messy quickly:
```nix ```nix
preFixup = '' {
for f in $(find $out/bin/ $out/libexec/ -type f -executable); do preFixup = ''
wrapProgram "$f" \ for f in $(find $out/bin/ $out/libexec/ -type f -executable); do
--prefix GIO_EXTRA_MODULES : "${getLib dconf}/lib/gio/modules" \ wrapProgram "$f" \
--prefix XDG_DATA_DIRS : "$out/share" \ --prefix GIO_EXTRA_MODULES : "${getLib dconf}/lib/gio/modules" \
--prefix XDG_DATA_DIRS : "$out/share/gsettings-schemas/${name}" \ --prefix XDG_DATA_DIRS : "$out/share" \
--prefix XDG_DATA_DIRS : "${gsettings-desktop-schemas}/share/gsettings-schemas/${gsettings-desktop-schemas.name}" \ --prefix XDG_DATA_DIRS : "$out/share/gsettings-schemas/${name}" \
--prefix XDG_DATA_DIRS : "${hicolor-icon-theme}/share" \ --prefix XDG_DATA_DIRS : "${gsettings-desktop-schemas}/share/gsettings-schemas/${gsettings-desktop-schemas.name}" \
--prefix GI_TYPELIB_PATH : "${lib.makeSearchPath "lib/girepository-1.0" [ pango json-glib ]}" --prefix XDG_DATA_DIRS : "${hicolor-icon-theme}/share" \
done --prefix GI_TYPELIB_PATH : "${lib.makeSearchPath "lib/girepository-1.0" [ pango json-glib ]}"
''; done
'';
}
``` ```
Fortunately, there is [`wrapGAppsHook`]{#ssec-gnome-hooks-wrapgappshook}. It works in conjunction with other setup hooks that populate environment variables, and it will then wrap all executables in `bin` and `libexec` directories using said variables. Fortunately, there is [`wrapGAppsHook`]{#ssec-gnome-hooks-wrapgappshook}. It works in conjunction with other setup hooks that populate environment variables, and it will then wrap all executables in `bin` and `libexec` directories using said variables.
@ -121,14 +125,16 @@ For convenience, it also adds `dconf.lib` for a GIO module implementing a GSetti
You can also pass additional arguments to `makeWrapper` using `gappsWrapperArgs` in `preFixup` hook: You can also pass additional arguments to `makeWrapper` using `gappsWrapperArgs` in `preFixup` hook:
```nix ```nix
preFixup = '' {
gappsWrapperArgs+=( preFixup = ''
# Thumbnailers gappsWrapperArgs+=(
--prefix XDG_DATA_DIRS : "${gdk-pixbuf}/share" # Thumbnailers
--prefix XDG_DATA_DIRS : "${librsvg}/share" --prefix XDG_DATA_DIRS : "${gdk-pixbuf}/share"
--prefix XDG_DATA_DIRS : "${shared-mime-info}/share" --prefix XDG_DATA_DIRS : "${librsvg}/share"
) --prefix XDG_DATA_DIRS : "${shared-mime-info}/share"
''; )
'';
}
``` ```
## Updating GNOME packages {#ssec-gnome-updating} ## Updating GNOME packages {#ssec-gnome-updating}
@ -159,7 +165,7 @@ python3.pkgs.buildPythonApplication {
nativeBuildInputs = [ nativeBuildInputs = [
wrapGAppsHook wrapGAppsHook
gobject-introspection gobject-introspection
... # ...
]; ];
dontWrapGApps = true; dontWrapGApps = true;
@ -181,7 +187,7 @@ mkDerivation {
nativeBuildInputs = [ nativeBuildInputs = [
wrapGAppsHook wrapGAppsHook
qmake qmake
... # ...
]; ];
dontWrapGApps = true; dontWrapGApps = true;

View file

@ -38,24 +38,26 @@ The `buildGoModule` function accepts the following parameters in addition to the
The following is an example expression using `buildGoModule`: The following is an example expression using `buildGoModule`:
```nix ```nix
pet = buildGoModule rec { {
pname = "pet"; pet = buildGoModule rec {
version = "0.3.4"; pname = "pet";
version = "0.3.4";
src = fetchFromGitHub { src = fetchFromGitHub {
owner = "knqyf263"; owner = "knqyf263";
repo = "pet"; repo = "pet";
rev = "v${version}"; rev = "v${version}";
hash = "sha256-Gjw1dRrgM8D3G7v6WIM2+50r4HmTXvx0Xxme2fH9TlQ="; hash = "sha256-Gjw1dRrgM8D3G7v6WIM2+50r4HmTXvx0Xxme2fH9TlQ=";
}; };
vendorHash = "sha256-ciBIR+a1oaYH+H1PcC8cD8ncfJczk1IiJ8iYNM+R6aA="; vendorHash = "sha256-ciBIR+a1oaYH+H1PcC8cD8ncfJczk1IiJ8iYNM+R6aA=";
meta = { meta = {
description = "Simple command-line snippet manager, written in Go"; description = "Simple command-line snippet manager, written in Go";
homepage = "https://github.com/knqyf263/pet"; homepage = "https://github.com/knqyf263/pet";
license = lib.licenses.mit; license = lib.licenses.mit;
maintainers = with lib.maintainers; [ kalbasit ]; maintainers = with lib.maintainers; [ kalbasit ];
};
}; };
} }
``` ```
@ -72,20 +74,22 @@ In the following is an example expression using `buildGoPackage`, the following
- `goDeps` is where the Go dependencies of a Go program are listed as a list of package source identified by Go import path. It could be imported as a separate `deps.nix` file for readability. The dependency data structure is described below. - `goDeps` is where the Go dependencies of a Go program are listed as a list of package source identified by Go import path. It could be imported as a separate `deps.nix` file for readability. The dependency data structure is described below.
```nix ```nix
deis = buildGoPackage rec { {
pname = "deis"; deis = buildGoPackage rec {
version = "1.13.0"; pname = "deis";
version = "1.13.0";
goPackagePath = "github.com/deis/deis"; goPackagePath = "github.com/deis/deis";
src = fetchFromGitHub { src = fetchFromGitHub {
owner = "deis"; owner = "deis";
repo = "deis"; repo = "deis";
rev = "v${version}"; rev = "v${version}";
hash = "sha256-XCPD4LNWtAd8uz7zyCLRfT8rzxycIUmTACjU03GnaeM="; hash = "sha256-XCPD4LNWtAd8uz7zyCLRfT8rzxycIUmTACjU03GnaeM=";
};
goDeps = ./deps.nix;
}; };
goDeps = ./deps.nix;
} }
``` ```
@ -153,10 +157,12 @@ A string list of flags to pass to the Go linker tool via the `-ldflags` argument
The most common use case for this argument is to make the resulting executable aware of its own version by injecting the value of string variable using the `-X` flag. For example: The most common use case for this argument is to make the resulting executable aware of its own version by injecting the value of string variable using the `-X` flag. For example:
```nix ```nix
{
ldflags = [ ldflags = [
"-X main.Version=${version}" "-X main.Version=${version}"
"-X main.Commit=${version}" "-X main.Commit=${version}"
]; ];
}
``` ```
### `tags` {#var-go-tags} ### `tags` {#var-go-tags}
@ -164,16 +170,20 @@ The most common use case for this argument is to make the resulting executable a
A string list of [Go build tags (also called build constraints)](https://pkg.go.dev/cmd/go#hdr-Build_constraints) that are passed via the `-tags` argument of `go build`. These constraints control whether Go files from the source should be included in the build. For example: A string list of [Go build tags (also called build constraints)](https://pkg.go.dev/cmd/go#hdr-Build_constraints) that are passed via the `-tags` argument of `go build`. These constraints control whether Go files from the source should be included in the build. For example:
```nix ```nix
{
tags = [ tags = [
"production" "production"
"sqlite" "sqlite"
]; ];
}
``` ```
Tags can also be set conditionally: Tags can also be set conditionally:
```nix ```nix
{
tags = [ "production" ] ++ lib.optionals withSqlite [ "sqlite" ]; tags = [ "production" ] ++ lib.optionals withSqlite [ "sqlite" ];
}
``` ```
### `deleteVendor` {#var-go-deleteVendor} ### `deleteVendor` {#var-go-deleteVendor}
@ -188,10 +198,12 @@ Many Go projects keep the main package in a `cmd` directory.
Following example could be used to only build the example-cli and example-server binaries: Following example could be used to only build the example-cli and example-server binaries:
```nix ```nix
subPackages = [ {
"cmd/example-cli" subPackages = [
"cmd/example-server" "cmd/example-cli"
]; "cmd/example-server"
];
}
``` ```
### `excludedPackages` {#var-go-excludedPackages} ### `excludedPackages` {#var-go-excludedPackages}
@ -213,10 +225,12 @@ on a per package level using build tags (`tags`). In case CGO is disabled, these
When a Go program depends on C libraries, place those dependencies in `buildInputs`: When a Go program depends on C libraries, place those dependencies in `buildInputs`:
```nix ```nix
{
buildInputs = [ buildInputs = [
libvirt libvirt
libxml2 libxml2
]; ];
}
``` ```
`CGO_ENABLED` defaults to `1`. `CGO_ENABLED` defaults to `1`.
@ -245,15 +259,18 @@ This is done with the [`-skip` or `-run`](https://pkg.go.dev/cmd/go#hdr-Testing_
For example, only a selection of tests could be run with: For example, only a selection of tests could be run with:
```nix ```nix
{
# -run and -skip accept regular expressions # -run and -skip accept regular expressions
checkFlags = [ checkFlags = [
"-run=^Test(Simple|Fast)$" "-run=^Test(Simple|Fast)$"
]; ];
}
``` ```
If a larger amount of tests should be skipped, the following pattern can be used: If a larger amount of tests should be skipped, the following pattern can be used:
```nix ```nix
{
checkFlags = checkFlags =
let let
# Skip tests that require network access # Skip tests that require network access
@ -264,6 +281,7 @@ If a larger amount of tests should be skipped, the following pattern can be used
]; ];
in in
[ "-skip=^${builtins.concatStringsSep "$|^" skippedTests}$" ]; [ "-skip=^${builtins.concatStringsSep "$|^" skippedTests}$" ];
}
``` ```
To disable tests altogether, set `doCheck = false;`. To disable tests altogether, set `doCheck = false;`.

View file

@ -134,9 +134,9 @@ For example you could set
```nix ```nix
build-idris-package { build-idris-package {
idrisBuildOptions = [ "--log" "1" "--verbose" ] idrisBuildOptions = [ "--log" "1" "--verbose" ];
... # ...
} }
``` ```

View file

@ -7,7 +7,7 @@ stdenv.mkDerivation {
pname = "..."; pname = "...";
version = "..."; version = "...";
src = fetchurl { ... }; src = fetchurl { /* ... */ };
nativeBuildInputs = [ nativeBuildInputs = [
ant ant
@ -48,8 +48,10 @@ installs a JAR named `foo.jar` in its `share/java` directory, and
another package declares the attribute another package declares the attribute
```nix ```nix
buildInputs = [ libfoo ]; {
nativeBuildInputs = [ jdk ]; buildInputs = [ libfoo ];
nativeBuildInputs = [ jdk ];
}
``` ```
then `CLASSPATH` will be set to then `CLASSPATH` will be set to
@ -62,13 +64,15 @@ If your Java package provides a program, you need to generate a wrapper
script to run it using a JRE. You can use `makeWrapper` for this: script to run it using a JRE. You can use `makeWrapper` for this:
```nix ```nix
nativeBuildInputs = [ makeWrapper ]; {
nativeBuildInputs = [ makeWrapper ];
installPhase = '' installPhase = ''
mkdir -p $out/bin mkdir -p $out/bin
makeWrapper ${jre}/bin/java $out/bin/foo \ makeWrapper ${jre}/bin/java $out/bin/foo \
--add-flags "-cp $out/share/java/foo.jar org.foo.Main" --add-flags "-cp $out/share/java/foo.jar org.foo.Main"
''; '';
}
``` ```
Since the introduction of the Java Platform Module System in Java 9, Since the introduction of the Java Platform Module System in Java 9,
@ -92,16 +96,18 @@ let
something = (pkgs.something.override { jre = my_jre; }); something = (pkgs.something.override { jre = my_jre; });
other = (pkgs.other.override { jre = my_jre; }); other = (pkgs.other.override { jre = my_jre; });
in in
... <...>
``` ```
You can also specify what JDK your JRE should be based on, for example You can also specify what JDK your JRE should be based on, for example
selecting a 'headless' build to avoid including a link to GTK+: selecting a 'headless' build to avoid including a link to GTK+:
```nix ```nix
my_jre = pkgs.jre_minimal.override { {
jdk = jdk11_headless; my_jre = pkgs.jre_minimal.override {
}; jdk = jdk11_headless;
};
}
``` ```
Note all JDKs passthru `home`, so if your application requires Note all JDKs passthru `home`, so if your application requires
@ -116,7 +122,9 @@ It is possible to use a different Java compiler than `javac` from the
OpenJDK. For instance, to use the GNU Java Compiler: OpenJDK. For instance, to use the GNU Java Compiler:
```nix ```nix
nativeBuildInputs = [ gcj ant ]; {
nativeBuildInputs = [ gcj ant ];
}
``` ```
Here, Ant will automatically use `gij` (the GNU Java Runtime) instead of Here, Ant will automatically use `gij` (the GNU Java Runtime) instead of

View file

@ -46,7 +46,7 @@ If a particular lock file is present, it is a strong indication of which package
It's better to try to use a Nix tool that understand the lock file. It's better to try to use a Nix tool that understand the lock file.
Using a different tool might give you hard to understand error because different packages have been installed. Using a different tool might give you hard to understand error because different packages have been installed.
An example of problems that could arise can be found [here](https://github.com/NixOS/nixpkgs/pull/126629). An example of problems that could arise can be found [here](https://github.com/NixOS/nixpkgs/pull/126629).
Upstream use NPM, but this is an attempt to package it with `yarn2nix` (that uses yarn.lock). Upstream use npm, but this is an attempt to package it with `yarn2nix` (that uses yarn.lock).
Using a different tool forces to commit a lock file to the repository. Using a different tool forces to commit a lock file to the repository.
Those files are fairly large, so when packaging for nixpkgs, this approach does not scale well. Those files are fairly large, so when packaging for nixpkgs, this approach does not scale well.
@ -54,8 +54,8 @@ Those files are fairly large, so when packaging for nixpkgs, this approach does
Exceptions to this rule are: Exceptions to this rule are:
- When you encounter one of the bugs from a Nix tool. In each of the tool specific instructions, known problems will be detailed. If you have a problem with a particular tool, then it's best to try another tool, even if this means you will have to recreate a lock file and commit it to nixpkgs. In general `yarn2nix` has less known problems and so a simple search in nixpkgs will reveal many yarn.lock files committed. - When you encounter one of the bugs from a Nix tool. In each of the tool specific instructions, known problems will be detailed. If you have a problem with a particular tool, then it's best to try another tool, even if this means you will have to recreate a lock file and commit it to nixpkgs. In general `yarn2nix` has less known problems and so a simple search in nixpkgs will reveal many yarn.lock files committed.
- Some lock files contain particular version of a package that has been pulled off NPM for some reason. In that case, you can recreate upstream lock (by removing the original and `npm install`, `yarn`, ...) and commit this to nixpkgs. - Some lock files contain particular version of a package that has been pulled off npm for some reason. In that case, you can recreate upstream lock (by removing the original and `npm install`, `yarn`, ...) and commit this to nixpkgs.
- The only tool that supports workspaces (a feature of NPM that helps manage sub-directories with different package.json from a single top level package.json) is `yarn2nix`. If upstream has workspaces you should try `yarn2nix`. - The only tool that supports workspaces (a feature of npm that helps manage sub-directories with different package.json from a single top level package.json) is `yarn2nix`. If upstream has workspaces you should try `yarn2nix`.
### Try to use upstream package.json {#javascript-upstream-package-json} ### Try to use upstream package.json {#javascript-upstream-package-json}
@ -76,11 +76,13 @@ Exceptions to this rule are:
when you need to override a package.json. It's nice to use the one from the upstream source and do some explicit override. Here is an example: when you need to override a package.json. It's nice to use the one from the upstream source and do some explicit override. Here is an example:
```nix ```nix
patchedPackageJSON = final.runCommand "package.json" { } '' {
${jq}/bin/jq '.version = "0.4.0" | patchedPackageJSON = final.runCommand "package.json" { } ''
.devDependencies."@jsdoc/cli" = "^0.2.5" ${jq}/bin/jq '.version = "0.4.0" |
${sonar-src}/package.json > $out .devDependencies."@jsdoc/cli" = "^0.2.5"
''; ${sonar-src}/package.json > $out
'';
}
``` ```
You will still need to commit the modified version of the lock files, but at least the overrides are explicit for everyone to see. You will still need to commit the modified version of the lock files, but at least the overrides are explicit for everyone to see.
@ -95,12 +97,12 @@ Then when building the frontend you can just symlink the node_modules directory.
## Javascript packages inside nixpkgs {#javascript-packages-nixpkgs} ## Javascript packages inside nixpkgs {#javascript-packages-nixpkgs}
The [pkgs/development/node-packages](https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/node-packages) folder contains a generated collection of [NPM packages](https://npmjs.com/) that can be installed with the Nix package manager. The [pkgs/development/node-packages](https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/node-packages) folder contains a generated collection of [npm packages](https://npmjs.com/) that can be installed with the Nix package manager.
As a rule of thumb, the package set should only provide _end user_ software packages, such as command-line utilities. As a rule of thumb, the package set should only provide _end user_ software packages, such as command-line utilities.
Libraries should only be added to the package set if there is a non-NPM package that requires it. Libraries should only be added to the package set if there is a non-npm package that requires it.
When it is desired to use NPM libraries in a development project, use the `node2nix` generator directly on the `package.json` configuration file of the project. When it is desired to use npm libraries in a development project, use the `node2nix` generator directly on the `package.json` configuration file of the project.
The package set provides support for the official stable Node.js versions. The package set provides support for the official stable Node.js versions.
The latest stable LTS release in `nodePackages`, as well as the latest stable current release in `nodePackages_latest`. The latest stable LTS release in `nodePackages`, as well as the latest stable current release in `nodePackages_latest`.
@ -115,15 +117,17 @@ 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): 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 ```nix
{
dat = prev.dat.override (oldAttrs: { dat = prev.dat.override (oldAttrs: {
buildInputs = [ final.node-gyp-build pkgs.libtool pkgs.autoconf pkgs.automake ]; buildInputs = [ final.node-gyp-build pkgs.libtool pkgs.autoconf pkgs.automake ];
meta = oldAttrs.meta // { broken = since "12"; }; meta = oldAttrs.meta // { broken = since "12"; };
}); });
}
``` ```
### Adding and Updating Javascript packages in nixpkgs {#javascript-adding-or-updating-packages} ### Adding and Updating Javascript packages in nixpkgs {#javascript-adding-or-updating-packages}
To add a package from NPM to nixpkgs: To add a package from npm to nixpkgs:
1. Modify [pkgs/development/node-packages/node-packages.json](https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/node-packages/node-packages.json) to add, update or remove package entries to have it included in `nodePackages` and `nodePackages_latest`. 1. Modify [pkgs/development/node-packages/node-packages.json](https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/node-packages/node-packages.json) to add, update or remove package entries to have it included in `nodePackages` and `nodePackages_latest`.
2. Run the script: 2. Run the script:
@ -150,7 +154,7 @@ To add a package from NPM to nixpkgs:
For more information about the generation process, consult the [README.md](https://github.com/svanderburg/node2nix) file of the `node2nix` tool. For more information about the generation process, consult the [README.md](https://github.com/svanderburg/node2nix) file of the `node2nix` tool.
To update NPM packages in nixpkgs, run the same `generate.sh` script: To update npm packages in nixpkgs, run the same `generate.sh` script:
```sh ```sh
./pkgs/development/node-packages/generate.sh ./pkgs/development/node-packages/generate.sh
@ -303,8 +307,8 @@ See `node2nix` [docs](https://github.com/svanderburg/node2nix) for more info.
#### Pitfalls {#javascript-node2nix-pitfalls} #### Pitfalls {#javascript-node2nix-pitfalls}
- If upstream package.json does not have a "version" attribute, `node2nix` will crash. You will need to add it like shown in [the package.json section](#javascript-upstream-package-json). - If upstream package.json does not have a "version" attribute, `node2nix` will crash. You will need to add it like shown in [the package.json section](#javascript-upstream-package-json).
- `node2nix` has some [bugs](https://github.com/svanderburg/node2nix/issues/238) related to working with lock files from NPM distributed with `nodejs_16`. - `node2nix` has some [bugs](https://github.com/svanderburg/node2nix/issues/238) related to working with lock files from npm distributed with `nodejs_16`.
- `node2nix` does not like missing packages from NPM. If you see something like `Cannot resolve version: vue-loader-v16@undefined` then you might want to try another tool. The package might have been pulled off of NPM. - `node2nix` does not like missing packages from npm. If you see something like `Cannot resolve version: vue-loader-v16@undefined` then you might want to try another tool. The package might have been pulled off of npm.
### yarn2nix {#javascript-yarn2nix} ### yarn2nix {#javascript-yarn2nix}
@ -315,10 +319,12 @@ You will need at least a `yarn.lock` file. If upstream does not have one you nee
If the downloaded files contain the `package.json` and `yarn.lock` files they can be used like this: If the downloaded files contain the `package.json` and `yarn.lock` files they can be used like this:
```nix ```nix
offlineCache = fetchYarnDeps { {
yarnLock = src + "/yarn.lock"; offlineCache = fetchYarnDeps {
hash = "...."; yarnLock = src + "/yarn.lock";
}; hash = "....";
};
}
``` ```
#### mkYarnPackage {#javascript-yarn2nix-mkYarnPackage} #### mkYarnPackage {#javascript-yarn2nix-mkYarnPackage}
@ -328,33 +334,41 @@ offlineCache = fetchYarnDeps {
It's important to use the `--offline` flag. For example if you script is `"build": "something"` in `package.json` use: It's important to use the `--offline` flag. For example if you script is `"build": "something"` in `package.json` use:
```nix ```nix
buildPhase = '' {
export HOME=$(mktemp -d) buildPhase = ''
yarn --offline build export HOME=$(mktemp -d)
''; yarn --offline build
'';
}
``` ```
The `distPhase` is packing the package's dependencies in a tarball using `yarn pack`. You can disable it using: The `distPhase` is packing the package's dependencies in a tarball using `yarn pack`. You can disable it using:
```nix ```nix
doDist = false; {
doDist = false;
}
``` ```
The configure phase can sometimes fail because it makes many assumptions which may not always apply. One common override is: The configure phase can sometimes fail because it makes many assumptions which may not always apply. One common override is:
```nix ```nix
configurePhase = '' {
ln -s $node_modules node_modules configurePhase = ''
''; ln -s $node_modules node_modules
'';
}
``` ```
or if you need a writeable node_modules directory: or if you need a writeable node_modules directory:
```nix ```nix
configurePhase = '' {
cp -r $node_modules node_modules configurePhase = ''
chmod +w node_modules cp -r $node_modules node_modules
''; chmod +w node_modules
'';
}
``` ```
#### mkYarnModules {#javascript-yarn2nix-mkYarnModules} #### mkYarnModules {#javascript-yarn2nix-mkYarnModules}
@ -394,12 +408,14 @@ mkYarnPackage rec {
- Having trouble with `node-gyp`? Try adding these lines to the `yarnPreBuild` steps: - Having trouble with `node-gyp`? Try adding these lines to the `yarnPreBuild` steps:
```nix ```nix
yarnPreBuild = '' {
mkdir -p $HOME/.node-gyp/${nodejs.version} yarnPreBuild = ''
echo 9 > $HOME/.node-gyp/${nodejs.version}/installVersion mkdir -p $HOME/.node-gyp/${nodejs.version}
ln -sfv ${nodejs}/include $HOME/.node-gyp/${nodejs.version} echo 9 > $HOME/.node-gyp/${nodejs.version}/installVersion
export npm_config_nodedir=${nodejs} ln -sfv ${nodejs}/include $HOME/.node-gyp/${nodejs.version}
''; export npm_config_nodedir=${nodejs}
'';
}
``` ```
- The `echo 9` steps comes from this answer: <https://stackoverflow.com/a/49139496> - The `echo 9` steps comes from this answer: <https://stackoverflow.com/a/49139496>

View file

@ -45,7 +45,7 @@ $ sbcl
Also one can create a `pkgs.mkShell` environment in `shell.nix`/`flake.nix`: Also one can create a `pkgs.mkShell` environment in `shell.nix`/`flake.nix`:
``` ```nix
let let
sbcl' = sbcl.withPackages (ps: [ ps.alexandria ]); sbcl' = sbcl.withPackages (ps: [ ps.alexandria ]);
in mkShell { in mkShell {
@ -55,10 +55,12 @@ in mkShell {
Such a Lisp can be now used e.g. to compile your sources: Such a Lisp can be now used e.g. to compile your sources:
``` ```nix
buildPhase = '' {
${sbcl'}/bin/sbcl --load my-build-file.lisp buildPhase = ''
'' ${sbcl'}/bin/sbcl --load my-build-file.lisp
'';
}
``` ```
## Importing packages from Quicklisp {#lisp-importing-packages-from-quicklisp} ## Importing packages from Quicklisp {#lisp-importing-packages-from-quicklisp}
@ -173,7 +175,7 @@ into the package scope with `withOverrides`.
A package defined outside Nixpkgs using `buildASDFSystem` can be woven into the A package defined outside Nixpkgs using `buildASDFSystem` can be woven into the
Nixpkgs-provided scope like this: Nixpkgs-provided scope like this:
``` ```nix
let let
alexandria = sbcl.buildASDFSystem rec { alexandria = sbcl.buildASDFSystem rec {
pname = "alexandria"; pname = "alexandria";
@ -199,7 +201,7 @@ new package with different parameters.
Example of overriding `alexandria`: Example of overriding `alexandria`:
``` ```nix
sbcl.pkgs.alexandria.overrideLispAttrs (oldAttrs: rec { sbcl.pkgs.alexandria.overrideLispAttrs (oldAttrs: rec {
version = "1.4"; version = "1.4";
src = fetchFromGitLab { src = fetchFromGitLab {
@ -225,7 +227,7 @@ vice versa.
To package slashy systems, use `overrideLispAttrs`, like so: To package slashy systems, use `overrideLispAttrs`, like so:
``` ```nix
ecl.pkgs.alexandria.overrideLispAttrs (oldAttrs: { ecl.pkgs.alexandria.overrideLispAttrs (oldAttrs: {
systems = oldAttrs.systems ++ [ "alexandria/tests" ]; systems = oldAttrs.systems ++ [ "alexandria/tests" ];
lispLibs = oldAttrs.lispLibs ++ [ ecl.pkgs.rt ]; lispLibs = oldAttrs.lispLibs ++ [ ecl.pkgs.rt ];
@ -290,7 +292,7 @@ derivation.
This example wraps CLISP: This example wraps CLISP:
``` ```nix
wrapLisp { wrapLisp {
pkg = clisp; pkg = clisp;
faslExt = "fas"; faslExt = "fas";

View file

@ -17,6 +17,9 @@ The main package set contains aliases to these package sets, e.g.
`luaPackages` refers to `lua5_1.pkgs` and `lua52Packages` to `luaPackages` refers to `lua5_1.pkgs` and `lua52Packages` to
`lua5_2.pkgs`. `lua5_2.pkgs`.
Note that nixpkgs patches the non-luajit interpreters to avoid referring to
`/usr` and have `;;` (a [placeholder](https://www.lua.org/manual/5.1/manual.html#pdf-package.path) replaced with the default LUA_PATH) work correctly.
### Installing Lua and packages {#installing-lua-and-packages} ### Installing Lua and packages {#installing-lua-and-packages}
#### Lua environment defined in separate `.nix` file {#lua-environment-defined-in-separate-.nix-file} #### Lua environment defined in separate `.nix` file {#lua-environment-defined-in-separate-.nix-file}
@ -87,6 +90,7 @@ final: prev:
pname = "luarocks-nix"; pname = "luarocks-nix";
src = /home/my_luarocks/repository; src = /home/my_luarocks/repository;
}); });
};
}; };
luaPackages = lua.pkgs; luaPackages = lua.pkgs;
@ -154,7 +158,9 @@ You can develop your package as you usually would, just don't forget to wrap it
within a `toLuaModule` call, for instance within a `toLuaModule` call, for instance
```nix ```nix
mynewlib = toLuaModule ( stdenv.mkDerivation { ... }); {
mynewlib = toLuaModule ( stdenv.mkDerivation { /* ... */ });
}
``` ```
There is also the `buildLuaPackage` function that can be used when lua modules There is also the `buildLuaPackage` function that can be used when lua modules
@ -182,24 +188,26 @@ Each interpreter has the following attributes:
The `buildLuarocksPackage` function is implemented in `pkgs/development/interpreters/lua-5/build-luarocks-package.nix` The `buildLuarocksPackage` function is implemented in `pkgs/development/interpreters/lua-5/build-luarocks-package.nix`
The following is an example: The following is an example:
```nix ```nix
luaposix = buildLuarocksPackage { {
pname = "luaposix"; luaposix = buildLuarocksPackage {
version = "34.0.4-1"; pname = "luaposix";
version = "34.0.4-1";
src = fetchurl { 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="; hash = "sha256-4mLJG8n4m6y4Fqd0meUDfsOb9RHSR0qa/KD5KCwrNXs=";
}; };
disabled = (luaOlder "5.1") || (luaAtLeast "5.4"); disabled = (luaOlder "5.1") || (luaAtLeast "5.4");
propagatedBuildInputs = [ bit32 lua std_normalize ]; propagatedBuildInputs = [ bit32 lua std_normalize ];
meta = { meta = {
homepage = "https://github.com/luaposix/luaposix/"; homepage = "https://github.com/luaposix/luaposix/";
description = "Lua bindings for POSIX"; description = "Lua bindings for POSIX";
maintainers = with lib.maintainers; [ vyp lblasc ]; maintainers = with lib.maintainers; [ vyp lblasc ];
license.fullName = "MIT/X11"; license.fullName = "MIT/X11";
};
}; };
}; }
``` ```
The `buildLuarocksPackage` delegates most tasks to luarocks: The `buildLuarocksPackage` delegates most tasks to luarocks:

View file

@ -40,7 +40,7 @@ maven.buildMavenPackage rec {
license = lib.licenses.gpl3Plus; license = lib.licenses.gpl3Plus;
maintainers = with lib.maintainers; [ majiir ]; maintainers = with lib.maintainers; [ majiir ];
}; };
}: }
``` ```
This package calls `maven.buildMavenPackage` to do its work. The primary difference from `stdenv.mkDerivation` is the `mvnHash` variable, which is a hash of all of the Maven dependencies. This package calls `maven.buildMavenPackage` to do its work. The primary difference from `stdenv.mkDerivation` is the `mvnHash` variable, which is a hash of all of the Maven dependencies.

View file

@ -92,6 +92,7 @@ buildDunePackage rec {
license = lib.licenses.bsd3; license = lib.licenses.bsd3;
maintainers = with lib.maintainers; [ sternenseemann ]; maintainers = with lib.maintainers; [ sternenseemann ];
}; };
}
``` ```
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. 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.

View file

@ -34,23 +34,27 @@ Nixpkgs provides a function `buildPerlPackage`, a generic package builder functi
Perl packages from CPAN are defined in [pkgs/top-level/perl-packages.nix](https://github.com/NixOS/nixpkgs/blob/master/pkgs/top-level/perl-packages.nix) rather than `pkgs/all-packages.nix`. Most Perl packages are so straight-forward to build that they are defined here directly, rather than having a separate function for each package called from `perl-packages.nix`. However, more complicated packages should be put in a separate file, typically in `pkgs/development/perl-modules`. Here is an example of the former: Perl packages from CPAN are defined in [pkgs/top-level/perl-packages.nix](https://github.com/NixOS/nixpkgs/blob/master/pkgs/top-level/perl-packages.nix) rather than `pkgs/all-packages.nix`. Most Perl packages are so straight-forward to build that they are defined here directly, rather than having a separate function for each package called from `perl-packages.nix`. However, more complicated packages should be put in a separate file, typically in `pkgs/development/perl-modules`. Here is an example of the former:
```nix ```nix
ClassC3 = buildPerlPackage rec { {
pname = "Class-C3"; ClassC3 = buildPerlPackage rec {
version = "0.21"; pname = "Class-C3";
src = fetchurl { version = "0.21";
url = "mirror://cpan/authors/id/F/FL/FLORA/${pname}-${version}.tar.gz"; src = fetchurl {
hash = "sha256-/5GE5xHT0uYGOQxroqj6LMU7CtKn2s6vMVoSXxL4iK4="; url = "mirror://cpan/authors/id/F/FL/FLORA/${pname}-${version}.tar.gz";
hash = "sha256-/5GE5xHT0uYGOQxroqj6LMU7CtKn2s6vMVoSXxL4iK4=";
};
}; };
}; }
``` ```
Note the use of `mirror://cpan/`, and the `pname` and `version` in the URL definition to ensure that the `pname` attribute is consistent with the source that were actually downloading. Perl packages are made available in `all-packages.nix` through the variable `perlPackages`. For instance, if you have a package that needs `ClassC3`, you would typically write Note the use of `mirror://cpan/`, and the `pname` and `version` in the URL definition to ensure that the `pname` attribute is consistent with the source that were actually downloading. Perl packages are made available in `all-packages.nix` through the variable `perlPackages`. For instance, if you have a package that needs `ClassC3`, you would typically write
```nix ```nix
foo = import ../path/to/foo.nix { {
inherit stdenv fetchurl ...; foo = import ../path/to/foo.nix {
inherit (perlPackages) ClassC3; inherit stdenv fetchurl /* ... */;
}; inherit (perlPackages) ClassC3;
};
}
``` ```
in `all-packages.nix`. You can test building a Perl package as follows: in `all-packages.nix`. You can test building a Perl package as follows:
@ -91,17 +95,19 @@ buildPerlPackage rec {
Dependencies on other Perl packages can be specified in the `buildInputs` and `propagatedBuildInputs` attributes. If something is exclusively a build-time dependency, use `buildInputs`; if its (also) a runtime dependency, use `propagatedBuildInputs`. For instance, this builds a Perl module that has runtime dependencies on a bunch of other modules: Dependencies on other Perl packages can be specified in the `buildInputs` and `propagatedBuildInputs` attributes. If something is exclusively a build-time dependency, use `buildInputs`; if its (also) a runtime dependency, use `propagatedBuildInputs`. For instance, this builds a Perl module that has runtime dependencies on a bunch of other modules:
```nix ```nix
ClassC3Componentised = buildPerlPackage rec { {
pname = "Class-C3-Componentised"; ClassC3Componentised = buildPerlPackage rec {
version = "1.0004"; pname = "Class-C3-Componentised";
src = fetchurl { version = "1.0004";
url = "mirror://cpan/authors/id/A/AS/ASH/${pname}-${version}.tar.gz"; src = fetchurl {
hash = "sha256-ASO9rV/FzJYZ0BH572Fxm2ZrFLMZLFATJng1NuU4FHc="; url = "mirror://cpan/authors/id/A/AS/ASH/${pname}-${version}.tar.gz";
hash = "sha256-ASO9rV/FzJYZ0BH572Fxm2ZrFLMZLFATJng1NuU4FHc=";
};
propagatedBuildInputs = [
ClassC3 ClassInspector TestException MROCompat
];
}; };
propagatedBuildInputs = [ }
ClassC3 ClassInspector TestException MROCompat
];
};
``` ```
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: 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:
@ -109,20 +115,22 @@ On Darwin, if a script has too many `-Idir` flags in its first line (its “sheb
```nix ```nix
{ lib, stdenv, buildPerlPackage, fetchurl, shortenPerlShebang }: { lib, stdenv, buildPerlPackage, fetchurl, shortenPerlShebang }:
ImageExifTool = buildPerlPackage { {
pname = "Image-ExifTool"; ImageExifTool = buildPerlPackage {
version = "12.50"; pname = "Image-ExifTool";
version = "12.50";
src = fetchurl { src = fetchurl {
url = "https://exiftool.org/${pname}-${version}.tar.gz"; url = "https://exiftool.org/${pname}-${version}.tar.gz";
hash = "sha256-vOhB/FwQMC8PPvdnjDvxRpU6jAZcC6GMQfc0AH4uwKg="; hash = "sha256-vOhB/FwQMC8PPvdnjDvxRpU6jAZcC6GMQfc0AH4uwKg=";
};
nativeBuildInputs = lib.optional stdenv.isDarwin shortenPerlShebang;
postInstall = lib.optionalString stdenv.isDarwin ''
shortenPerlShebang $out/bin/exiftool
'';
}; };
}
nativeBuildInputs = lib.optional stdenv.isDarwin shortenPerlShebang;
postInstall = lib.optionalString stdenv.isDarwin ''
shortenPerlShebang $out/bin/exiftool
'';
};
``` ```
This will remove the `-I` flags from the shebang line, rewrite them in the `use lib` form, and put them on the next line instead. This function can be given any number of Perl scripts as arguments; it will modify them in-place. This will remove the `-I` flags from the shebang line, rewrite them in the `use lib` form, and put them on the next line instead. This function can be given any number of Perl scripts as arguments; it will modify them in-place.

View file

@ -97,7 +97,7 @@ let
myPhp = php.withExtensions ({ all, ... }: with all; [ imagick opcache ]); myPhp = php.withExtensions ({ all, ... }: with all; [ imagick opcache ]);
in { in {
services.phpfpm.pools."foo".phpPackage = myPhp; services.phpfpm.pools."foo".phpPackage = myPhp;
}; }
``` ```
```nix ```nix
@ -108,7 +108,7 @@ let
}; };
in { in {
services.phpfpm.pools."foo".phpPackage = myPhp; services.phpfpm.pools."foo".phpPackage = myPhp;
}; }
``` ```
#### Example usage with `nix-shell` {#ssec-php-user-guide-installing-with-extensions-nix-shell} #### Example usage with `nix-shell` {#ssec-php-user-guide-installing-with-extensions-nix-shell}
@ -149,7 +149,7 @@ php.override {
extensions = prev.extensions // { extensions = prev.extensions // {
mysqlnd = prev.extensions.mysqlnd.overrideAttrs (attrs: { mysqlnd = prev.extensions.mysqlnd.overrideAttrs (attrs: {
patches = attrs.patches or [] ++ [ patches = attrs.patches or [] ++ [
# ...
]; ];
}); });
}; };

View file

@ -12,18 +12,18 @@ Additionally, the [`validatePkgConfig` setup hook](https://nixos.org/manual/nixp
A good example of all these things is zlib: A good example of all these things is zlib:
``` ```nix
{ pkg-config, testers, ... }: { pkg-config, testers, ... }:
stdenv.mkDerivation (finalAttrs: { stdenv.mkDerivation (finalAttrs: {
... /* ... */
nativeBuildInputs = [ pkg-config validatePkgConfig ]; nativeBuildInputs = [ pkg-config validatePkgConfig ];
passthru.tests.pkg-config = testers.testMetaPkgConfig finalAttrs.finalPackage; passthru.tests.pkg-config = testers.testMetaPkgConfig finalAttrs.finalPackage;
meta = { meta = {
... /* ... */
pkgConfigModules = [ "zlib" ]; pkgConfigModules = [ "zlib" ];
}; };
}) })

View file

@ -254,17 +254,19 @@ The next example shows a non trivial overriding of the `blas` implementation to
be used through out all of the Python package set: be used through out all of the Python package set:
```nix ```nix
python3MyBlas = pkgs.python3.override { {
packageOverrides = self: super: { python3MyBlas = pkgs.python3.override {
# We need toPythonModule for the package set to evaluate this packageOverrides = self: super: {
blas = super.toPythonModule(super.pkgs.blas.override { # We need toPythonModule for the package set to evaluate this
blasProvider = 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; lapack = super.toPythonModule(super.pkgs.lapack.override {
}); lapackProvider = super.pkgs.mkl;
});
};
}; };
}; }
``` ```
This is particularly useful for numpy and scipy users who want to gain speed with other blas implementations. This is particularly useful for numpy and scipy users who want to gain speed with other blas implementations.
@ -322,7 +324,9 @@ python3Packages.buildPythonApplication rec {
This is then added to `all-packages.nix` just as any other application would be. This is then added to `all-packages.nix` just as any other application would be.
```nix ```nix
luigi = callPackage ../applications/networking/cluster/luigi { }; {
luigi = callPackage ../applications/networking/cluster/luigi { };
}
``` ```
Since the package is an application, a consumer doesn't need to care about Since the package is an application, a consumer doesn't need to care about
@ -342,7 +346,9 @@ the attribute in `python-packages.nix`, and the `toPythonApplication` shall be
applied to the reference: applied to the reference:
```nix ```nix
youtube-dl = with python3Packages; toPythonApplication youtube-dl; {
youtube-dl = with python3Packages; toPythonApplication youtube-dl;
}
``` ```
#### `toPythonModule` function {#topythonmodule-function} #### `toPythonModule` function {#topythonmodule-function}
@ -354,10 +360,12 @@ bindings should be made available from `python-packages.nix`. The
modifications. modifications.
```nix ```nix
opencv = toPythonModule (pkgs.opencv.override { {
enablePython = true; opencv = toPythonModule (pkgs.opencv.override {
pythonPackages = self; enablePython = true;
}); pythonPackages = self;
});
}
``` ```
Do pay attention to passing in the right Python version! Do pay attention to passing in the right Python version!
@ -1197,7 +1205,8 @@ a good indication that the package is not in a valid state.
Pytest is the most common test runner for python repositories. A trivial Pytest is the most common test runner for python repositories. A trivial
test run would be: test run would be:
``` ```nix
{
nativeCheckInputs = [ pytest ]; nativeCheckInputs = [ pytest ];
checkPhase = '' checkPhase = ''
runHook preCheck runHook preCheck
@ -1206,6 +1215,7 @@ test run would be:
runHook postCheck runHook postCheck
''; '';
}
``` ```
However, many repositories' test suites do not translate well to nix's build However, many repositories' test suites do not translate well to nix's build
@ -1213,7 +1223,8 @@ sandbox, and will generally need many tests to be disabled.
To filter tests using pytest, one can do the following: To filter tests using pytest, one can do the following:
``` ```nix
{
nativeCheckInputs = [ pytest ]; nativeCheckInputs = [ pytest ];
# avoid tests which need additional data or touch network # avoid tests which need additional data or touch network
checkPhase = '' checkPhase = ''
@ -1223,6 +1234,7 @@ To filter tests using pytest, one can do the following:
runHook postCheck runHook postCheck
''; '';
}
``` ```
`--ignore` will tell pytest to ignore that file or directory from being `--ignore` will tell pytest to ignore that file or directory from being
@ -1248,7 +1260,8 @@ when a package may need many items disabled to run the test suite.
Using the example above, the analogous `pytestCheckHook` usage would be: Using the example above, the analogous `pytestCheckHook` usage would be:
``` ```nix
{
nativeCheckInputs = [ nativeCheckInputs = [
pytestCheckHook pytestCheckHook
]; ];
@ -1268,12 +1281,14 @@ Using the example above, the analogous `pytestCheckHook` usage would be:
disabledTestPaths = [ disabledTestPaths = [
"tests/test_failing.py" "tests/test_failing.py"
]; ];
}
``` ```
This is especially useful when tests need to be conditionally disabled, This is especially useful when tests need to be conditionally disabled,
for example: for example:
``` ```nix
{
disabledTests = [ disabledTests = [
# touches network # touches network
"download" "download"
@ -1285,6 +1300,7 @@ for example:
# can fail when building with other packages # can fail when building with other packages
"socket" "socket"
]; ];
}
``` ```
Trying to concatenate the related strings to disable tests in a regular Trying to concatenate the related strings to disable tests in a regular
@ -1298,20 +1314,24 @@ all packages have test suites that can be run easily, and some have none at all.
To help ensure the package still works, [`pythonImportsCheck`](#using-pythonimportscheck) can attempt to import To help ensure the package still works, [`pythonImportsCheck`](#using-pythonimportscheck) can attempt to import
the listed modules. the listed modules.
``` ```nix
{
pythonImportsCheck = [ pythonImportsCheck = [
"requests" "requests"
"urllib" "urllib"
]; ];
}
``` ```
roughly translates to: roughly translates to:
``` ```nix
{
postCheck = '' postCheck = ''
PYTHONPATH=$out/${python.sitePackages}:$PYTHONPATH PYTHONPATH=$out/${python.sitePackages}:$PYTHONPATH
python -c "import requests; import urllib" python -c "import requests; import urllib"
''; '';
}
``` ```
However, this is done in its own phase, and not dependent on whether [`doCheck = true;`](#var-stdenv-doCheck). However, this is done in its own phase, and not dependent on whether [`doCheck = true;`](#var-stdenv-doCheck).
@ -1342,7 +1362,8 @@ pkg3>=1.0,<=2.0
we can do: we can do:
``` ```nix
{
nativeBuildInputs = [ nativeBuildInputs = [
pythonRelaxDepsHook pythonRelaxDepsHook
]; ];
@ -1353,6 +1374,7 @@ we can do:
pythonRemoveDeps = [ pythonRemoveDeps = [
"pkg2" "pkg2"
]; ];
}
``` ```
which would result in the following `requirements.txt` file: which would result in the following `requirements.txt` file:
@ -1365,9 +1387,11 @@ pkg3
Another option is to pass `true`, that will relax/remove all dependencies, for Another option is to pass `true`, that will relax/remove all dependencies, for
example: example:
``` ```nix
{
nativeBuildInputs = [ pythonRelaxDepsHook ]; nativeBuildInputs = [ pythonRelaxDepsHook ];
pythonRelaxDeps = true; pythonRelaxDeps = true;
}
``` ```
which would result in the following `requirements.txt` file: which would result in the following `requirements.txt` file:
@ -1392,7 +1416,8 @@ work with any of the [existing hooks](#setup-hooks).
`unittestCheckHook` is a hook which will substitute the setuptools `test` command for a [`checkPhase`](#ssec-check-phase) which runs `python -m unittest discover`: `unittestCheckHook` is a hook which will substitute the setuptools `test` command for a [`checkPhase`](#ssec-check-phase) which runs `python -m unittest discover`:
``` ```nix
{
nativeCheckInputs = [ nativeCheckInputs = [
unittestCheckHook unittestCheckHook
]; ];
@ -1400,6 +1425,7 @@ work with any of the [existing hooks](#setup-hooks).
unittestFlagsArray = [ unittestFlagsArray = [
"-s" "tests" "-v" "-s" "tests" "-v"
]; ];
}
``` ```
#### Using sphinxHook {#using-sphinxhook} #### Using sphinxHook {#using-sphinxhook}
@ -1409,7 +1435,8 @@ using the popular Sphinx documentation generator.
It is setup to automatically find common documentation source paths and It is setup to automatically find common documentation source paths and
render them using the default `html` style. render them using the default `html` style.
``` ```nix
{
outputs = [ outputs = [
"out" "out"
"doc" "doc"
@ -1418,13 +1445,15 @@ render them using the default `html` style.
nativeBuildInputs = [ nativeBuildInputs = [
sphinxHook sphinxHook
]; ];
}
``` ```
The hook will automatically build and install the artifact into the The hook will automatically build and install the artifact into the
`doc` output, if it exists. It also provides an automatic diversion `doc` output, if it exists. It also provides an automatic diversion
for the artifacts of the `man` builder into the `man` target. for the artifacts of the `man` builder into the `man` target.
``` ```nix
{
outputs = [ outputs = [
"out" "out"
"doc" "doc"
@ -1436,14 +1465,17 @@ for the artifacts of the `man` builder into the `man` target.
"singlehtml" "singlehtml"
"man" "man"
]; ];
}
``` ```
Overwrite `sphinxRoot` when the hook is unable to find your Overwrite `sphinxRoot` when the hook is unable to find your
documentation source root. documentation source root.
``` ```nix
{
# Configure sphinxRoot for uncommon paths # Configure sphinxRoot for uncommon paths
sphinxRoot = "weird/docs/path"; sphinxRoot = "weird/docs/path";
}
``` ```
The hook is also available to packages outside the python ecosystem by The hook is also available to packages outside the python ecosystem by
@ -1827,6 +1859,7 @@ folder and not downloaded again.
If you need to change a package's attribute(s) from `configuration.nix` you could do: If you need to change a package's attribute(s) from `configuration.nix` you could do:
```nix ```nix
{
nixpkgs.config.packageOverrides = super: { nixpkgs.config.packageOverrides = super: {
python3 = super.python3.override { python3 = super.python3.override {
packageOverrides = python-self: python-super: { packageOverrides = python-self: python-super: {
@ -1841,6 +1874,7 @@ If you need to change a package's attribute(s) from `configuration.nix` you coul
}; };
}; };
}; };
}
``` ```
`python3Packages.twisted` is now globally overridden. `python3Packages.twisted` is now globally overridden.
@ -1853,11 +1887,13 @@ To modify only a Python package set instead of a whole Python derivation, use
this snippet: this snippet:
```nix ```nix
{
myPythonPackages = python3Packages.override { myPythonPackages = python3Packages.override {
overrides = self: super: { overrides = self: super: {
twisted = ...; twisted = <...>;
}; };
} };
}
``` ```
### How to override a Python package using overlays? {#how-to-override-a-python-package-using-overlays} ### How to override a Python package using overlays? {#how-to-override-a-python-package-using-overlays}
@ -1893,7 +1929,7 @@ final: prev: {
( (
python-final: python-prev: { python-final: python-prev: {
foo = python-prev.foo.overridePythonAttrs (oldAttrs: { foo = python-prev.foo.overridePythonAttrs (oldAttrs: {
... # ...
}); });
} }
) )
@ -1920,7 +1956,7 @@ The Python interpreters are by default not built with optimizations enabled, bec
the builds are in that case not reproducible. To enable optimizations, override the the builds are in that case not reproducible. To enable optimizations, override the
interpreter of interest, e.g using interpreter of interest, e.g using
``` ```nix
let let
pkgs = import ./. {}; pkgs = import ./. {};
mypython = pkgs.python3.override { mypython = pkgs.python3.override {
@ -1938,17 +1974,21 @@ Some packages define optional dependencies for additional features. With
`extras-require`, while PEP 621 calls these `optional-dependencies`. `extras-require`, while PEP 621 calls these `optional-dependencies`.
```nix ```nix
optional-dependencies = { {
complete = [ distributed ]; optional-dependencies = {
}; complete = [ distributed ];
};
}
``` ```
and letting the package requiring the extra add the list to its dependencies and letting the package requiring the extra add the list to its dependencies
```nix ```nix
dependencies = [ {
... dependencies = [
] ++ dask.optional-dependencies.complete; # ...
] ++ dask.optional-dependencies.complete;
}
``` ```
This method is using `passthru`, meaning that changing `optional-dependencies` of a package won't cause it to rebuild. This method is using `passthru`, meaning that changing `optional-dependencies` of a package won't cause it to rebuild.

View file

@ -124,11 +124,13 @@ 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: 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:
```nix ```nix
{
gems = bundlerEnv { gems = bundlerEnv {
name = "gems-for-some-project"; name = "gems-for-some-project";
gemdir = ./.; gemdir = ./.;
extraConfigPaths = [ "${./.}/.ruby-version" ]; extraConfigPaths = [ "${./.}/.ruby-version" ];
}; };
}
``` ```
### Gem-specific configurations and workarounds {#gem-specific-configurations-and-workarounds} ### Gem-specific configurations and workarounds {#gem-specific-configurations-and-workarounds}

View file

@ -3,10 +3,12 @@
To install the rust compiler and cargo put To install the rust compiler and cargo put
```nix ```nix
environment.systemPackages = [ {
rustc environment.systemPackages = [
cargo rustc
]; cargo
];
}
``` ```
into your `configuration.nix` or bring them into scope with `nix-shell -p rustc cargo`. into your `configuration.nix` or bring them into scope with `nix-shell -p rustc cargo`.
@ -51,7 +53,9 @@ preferred over `cargoSha256` which was used for traditional Nix SHA-256 hashes.
For example: For example:
```nix ```nix
{
cargoHash = "sha256-l1vL2ZdtDRxSGvP0X/l3nMw8+6WF67KPutJEzUROjg8="; cargoHash = "sha256-l1vL2ZdtDRxSGvP0X/l3nMw8+6WF67KPutJEzUROjg8=";
}
``` ```
Exception: If the application has cargo `git` dependencies, the `cargoHash`/`cargoSha256` Exception: If the application has cargo `git` dependencies, the `cargoHash`/`cargoSha256`
@ -67,13 +71,17 @@ then be taken from the failed build. A fake hash can be used for
`cargoHash` as follows: `cargoHash` as follows:
```nix ```nix
{
cargoHash = lib.fakeHash; cargoHash = lib.fakeHash;
}
``` ```
For `cargoSha256` you can use: For `cargoSha256` you can use:
```nix ```nix
{
cargoSha256 = lib.fakeSha256; cargoSha256 = lib.fakeSha256;
}
``` ```
Per the instructions in the [Cargo Book](https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html) Per the instructions in the [Cargo Book](https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html)
@ -162,9 +170,11 @@ doesn't add a `Cargo.lock` to your `src`, and a `Cargo.lock` is still
required to build a rust package. A simple fix is to use: required to build a rust package. A simple fix is to use:
```nix ```nix
postPatch = '' {
ln -s ${./Cargo.lock} Cargo.lock postPatch = ''
''; ln -s ${./Cargo.lock} Cargo.lock
'';
}
``` ```
The output hash of each dependency that uses a git source must be The output hash of each dependency that uses a git source must be
@ -409,7 +419,7 @@ the `cargoPatches` attribute to update or add it.
```nix ```nix
rustPlatform.buildRustPackage rec { rustPlatform.buildRustPackage rec {
(...) # ...
cargoPatches = [ cargoPatches = [
# a patch file to add/update Cargo.lock in the source code # a patch file to add/update Cargo.lock in the source code
./add-Cargo.lock.patch ./add-Cargo.lock.patch
@ -433,10 +443,12 @@ containing `Cargo.toml` and `Cargo.lock`, `fetchCargoTarball`
can be used as follows: can be used as follows:
```nix ```nix
cargoDeps = rustPlatform.fetchCargoTarball { {
inherit src; cargoDeps = rustPlatform.fetchCargoTarball {
hash = "sha256-BoHIN/519Top1NUBjpB/oEMqi86Omt3zTQcXFWqrek0="; inherit src;
}; hash = "sha256-BoHIN/519Top1NUBjpB/oEMqi86Omt3zTQcXFWqrek0=";
};
}
``` ```
The `src` attribute is required, as well as a hash specified through The `src` attribute is required, as well as a hash specified through
@ -458,23 +470,27 @@ function does not require a hash (unless git dependencies are used)
and fetches every dependency as a separate fixed-output derivation. and fetches every dependency as a separate fixed-output derivation.
`importCargoLock` can be used as follows: `importCargoLock` can be used as follows:
``` ```nix
cargoDeps = rustPlatform.importCargoLock { {
lockFile = ./Cargo.lock; cargoDeps = rustPlatform.importCargoLock {
}; lockFile = ./Cargo.lock;
};
}
``` ```
If the `Cargo.lock` file includes git dependencies, then their output If the `Cargo.lock` file includes git dependencies, then their output
hashes need to be specified since they are not available through the hashes need to be specified since they are not available through the
lock file. For example: lock file. For example:
``` ```nix
cargoDeps = rustPlatform.importCargoLock { {
lockFile = ./Cargo.lock; cargoDeps = rustPlatform.importCargoLock {
outputHashes = { lockFile = ./Cargo.lock;
"rand-0.8.3" = "0ya2hia3cn31qa8894s3av2s8j5bjwb6yq92k0jsnlx7jid0jwqa"; outputHashes = {
"rand-0.8.3" = "0ya2hia3cn31qa8894s3av2s8j5bjwb6yq92k0jsnlx7jid0jwqa";
};
}; };
}; }
``` ```
If you do not specify an output hash for a git dependency, building If you do not specify an output hash for a git dependency, building
@ -792,27 +808,27 @@ general. A number of other parameters can be overridden:
- The version of `rustc` used to compile the crate: - The version of `rustc` used to compile the crate:
```nix ```nix
(hello {}).override { rust = pkgs.rust; }; (hello {}).override { rust = pkgs.rust; }
``` ```
- Whether to build in release mode or debug mode (release mode by - Whether to build in release mode or debug mode (release mode by
default): default):
```nix ```nix
(hello {}).override { release = false; }; (hello {}).override { release = false; }
``` ```
- Whether to print the commands sent to `rustc` when building - Whether to print the commands sent to `rustc` when building
(equivalent to `--verbose` in cargo: (equivalent to `--verbose` in cargo:
```nix ```nix
(hello {}).override { verbose = false; }; (hello {}).override { verbose = false; }
``` ```
- Extra arguments to be passed to `rustc`: - Extra arguments to be passed to `rustc`:
```nix ```nix
(hello {}).override { extraRustcOpts = "-Z debuginfo=2"; }; (hello {}).override { extraRustcOpts = "-Z debuginfo=2"; }
``` ```
- Phases, just like in any other derivation, can be specified using - Phases, just like in any other derivation, can be specified using
@ -828,7 +844,7 @@ general. A number of other parameters can be overridden:
preConfigure = '' preConfigure = ''
echo "pub const PATH=\"${hi.out}\";" >> src/path.rs" echo "pub const PATH=\"${hi.out}\";" >> src/path.rs"
''; '';
}; }
``` ```
### Setting Up `nix-shell` {#setting-up-nix-shell} ### Setting Up `nix-shell` {#setting-up-nix-shell}

View file

@ -112,13 +112,17 @@ stdenv.mkDerivation rec {
If you'd like to build a different configuration than `release`: If you'd like to build a different configuration than `release`:
```nix ```nix
swiftpmBuildConfig = "debug"; {
swiftpmBuildConfig = "debug";
}
``` ```
It is also possible to provide additional flags to `swift build`: It is also possible to provide additional flags to `swift build`:
```nix ```nix
swiftpmFlags = [ "--disable-dead-strip" ]; {
swiftpmFlags = [ "--disable-dead-strip" ];
}
``` ```
The default `buildPhase` already passes `-j` for parallel building. The default `buildPhase` already passes `-j` for parallel building.
@ -132,7 +136,9 @@ Including `swiftpm` in your `nativeBuildInputs` also provides a default
`checkPhase`, but it must be enabled with: `checkPhase`, but it must be enabled with:
```nix ```nix
doCheck = true; {
doCheck = true;
}
``` ```
This essentially runs: `swift test -c release` This essentially runs: `swift test -c release`
@ -147,13 +153,15 @@ them, we need to make them writable.
A special function `swiftpmMakeMutable` is available to replace the symlink A special function `swiftpmMakeMutable` is available to replace the symlink
with a writable copy: with a writable copy:
``` ```nix
configurePhase = generated.configure ++ '' {
# Replace the dependency symlink with a writable copy. configurePhase = generated.configure ++ ''
swiftpmMakeMutable swift-crypto # Replace the dependency symlink with a writable copy.
# Now apply a patch. swiftpmMakeMutable swift-crypto
patch -p1 -d .build/checkouts/swift-crypto -i ${./some-fix.patch} # Now apply a patch.
''; patch -p1 -d .build/checkouts/swift-crypto -i ${./some-fix.patch}
'';
}
``` ```
## Considerations for custom build tools {#ssec-swift-considerations-for-custom-build-tools} ## Considerations for custom build tools {#ssec-swift-considerations-for-custom-build-tools}

View file

@ -219,9 +219,11 @@ After running the updater, if nvim-treesitter received an update, also run [`nvi
Some plugins require overrides in order to function properly. Overrides are placed in [overrides.nix](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/editors/vim/plugins/overrides.nix). Overrides are most often required when a plugin requires some dependencies, or extra steps are required during the build process. For example `deoplete-fish` requires both `deoplete-nvim` and `vim-fish`, and so the following override was added: Some plugins require overrides in order to function properly. Overrides are placed in [overrides.nix](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/editors/vim/plugins/overrides.nix). Overrides are most often required when a plugin requires some dependencies, or extra steps are required during the build process. For example `deoplete-fish` requires both `deoplete-nvim` and `vim-fish`, and so the following override was added:
```nix ```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 ];
});
}
``` ```
Sometimes plugins require an override that must be changed when the plugin is updated. This can cause issues when Vim plugins are auto-updated but the associated override isn't updated. For these plugins, the override should be written so that it specifies all information required to install the plugin, and running `./update.py` doesn't change the derivation for the plugin. Manually updating the override is required to update these types of plugins. An example of such a plugin is `LanguageClient-neovim`. Sometimes plugins require an override that must be changed when the plugin is updated. This can cause issues when Vim plugins are auto-updated but the associated override isn't updated. For these plugins, the override should be written so that it specifies all information required to install the plugin, and running `./update.py` doesn't change the derivation for the plugin. Manually updating the override is required to update these types of plugins. An example of such a plugin is `LanguageClient-neovim`.
@ -264,8 +266,10 @@ pwntester/octo.nvim,,
You can then reference the generated vim plugins via: You can then reference the generated vim plugins via:
```nix ```nix
myVimPlugins = pkgs.vimPlugins.extend ( {
(pkgs.callPackage ./generated.nix {}) myVimPlugins = pkgs.vimPlugins.extend (
); (pkgs.callPackage ./generated.nix {})
);
}
``` ```

View file

@ -320,5 +320,7 @@
"login.defs(5)": "https://man.archlinux.org/man/login.defs.5", "login.defs(5)": "https://man.archlinux.org/man/login.defs.5",
"unshare(1)": "https://man.archlinux.org/man/unshare.1.en", "unshare(1)": "https://man.archlinux.org/man/unshare.1.en",
"nix-shell(1)": "https://nixos.org/manual/nix/stable/command-ref/nix-shell.html", "nix-shell(1)": "https://nixos.org/manual/nix/stable/command-ref/nix-shell.html",
"mksquashfs(1)": "https://man.archlinux.org/man/extra/squashfs-tools/mksquashfs.1.en" "mksquashfs(1)": "https://man.archlinux.org/man/extra/squashfs-tools/mksquashfs.1.en",
"curl(1)": "https://curl.se/docs/manpage.html",
"netrc(5)": "https://man.cx/netrc"
} }

View file

@ -81,7 +81,7 @@ $ sudo launchctl kickstart -k system/org.nixos.nix-daemon
## Example flake usage {#sec-darwin-builder-example-flake} ## Example flake usage {#sec-darwin-builder-example-flake}
``` ```nix
{ {
inputs = { inputs = {
nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-22.11-darwin"; nixpkgs.url = "github:nixos/nixpkgs/nixpkgs-22.11-darwin";
@ -153,7 +153,8 @@ you may use it to build a modified remote builder with additional storage or mem
To do this, you just need to set the `virtualisation.darwin-builder.*` parameters as To do this, you just need to set the `virtualisation.darwin-builder.*` parameters as
in the example below and rebuild. in the example below and rebuild.
``` ```nix
{
darwin-builder = nixpkgs.lib.nixosSystem { darwin-builder = nixpkgs.lib.nixosSystem {
system = linuxSystem; system = linuxSystem;
modules = [ modules = [
@ -166,6 +167,8 @@ in the example below and rebuild.
virtualisation.darwin-builder.workingDirectory = "/var/lib/darwin-builder"; virtualisation.darwin-builder.workingDirectory = "/var/lib/darwin-builder";
} }
]; ];
};
}
``` ```
You may make any other changes to your VM in this attribute set. For example, You may make any other changes to your VM in this attribute set. For example,

View file

@ -13,11 +13,13 @@ Once an Eclipse variant is installed, it can be run using the `eclipse` command,
If you prefer to install plugins in a more declarative manner, then Nixpkgs also offer a number of Eclipse plugins that can be installed in an _Eclipse environment_. This type of environment is created using the function `eclipseWithPlugins` found inside the `nixpkgs.eclipses` attribute set. This function takes as argument `{ eclipse, plugins ? [], jvmArgs ? [] }` where `eclipse` is a one of the Eclipse packages described above, `plugins` is a list of plugin derivations, and `jvmArgs` is a list of arguments given to the JVM running the Eclipse. For example, say you wish to install the latest Eclipse Platform with the popular Eclipse Color Theme plugin and also allow Eclipse to use more RAM. You could then add: If you prefer to install plugins in a more declarative manner, then Nixpkgs also offer a number of Eclipse plugins that can be installed in an _Eclipse environment_. This type of environment is created using the function `eclipseWithPlugins` found inside the `nixpkgs.eclipses` attribute set. This function takes as argument `{ eclipse, plugins ? [], jvmArgs ? [] }` where `eclipse` is a one of the Eclipse packages described above, `plugins` is a list of plugin derivations, and `jvmArgs` is a list of arguments given to the JVM running the Eclipse. For example, say you wish to install the latest Eclipse Platform with the popular Eclipse Color Theme plugin and also allow Eclipse to use more RAM. You could then add:
```nix ```nix
packageOverrides = pkgs: { {
myEclipse = with pkgs.eclipses; eclipseWithPlugins { packageOverrides = pkgs: {
eclipse = eclipse-platform; myEclipse = with pkgs.eclipses; eclipseWithPlugins {
jvmArgs = [ "-Xmx2048m" ]; eclipse = eclipse-platform;
plugins = [ plugins.color-theme ]; jvmArgs = [ "-Xmx2048m" ];
plugins = [ plugins.color-theme ];
};
}; };
} }
``` ```
@ -33,32 +35,34 @@ If there is a need to install plugins that are not available in Nixpkgs then it
Expanding the previous example with two plugins using the above functions, we have: Expanding the previous example with two plugins using the above functions, we have:
```nix ```nix
packageOverrides = pkgs: { {
myEclipse = with pkgs.eclipses; eclipseWithPlugins { packageOverrides = pkgs: {
eclipse = eclipse-platform; myEclipse = with pkgs.eclipses; eclipseWithPlugins {
jvmArgs = [ "-Xmx2048m" ]; eclipse = eclipse-platform;
plugins = [ jvmArgs = [ "-Xmx2048m" ];
plugins.color-theme plugins = [
(plugins.buildEclipsePlugin { plugins.color-theme
name = "myplugin1-1.0"; (plugins.buildEclipsePlugin {
srcFeature = fetchurl { name = "myplugin1-1.0";
url = "http://…/features/myplugin1.jar"; srcFeature = fetchurl {
hash = "sha256-123…"; url = "http://…/features/myplugin1.jar";
}; hash = "sha256-123…";
srcPlugin = fetchurl { };
url = "http://…/plugins/myplugin1.jar"; srcPlugin = fetchurl {
hash = "sha256-123…"; url = "http://…/plugins/myplugin1.jar";
}; hash = "sha256-123…";
}); };
(plugins.buildEclipseUpdateSite { })
name = "myplugin2-1.0"; (plugins.buildEclipseUpdateSite {
src = fetchurl { name = "myplugin2-1.0";
stripRoot = false; src = fetchurl {
url = "http://…/myplugin2.zip"; stripRoot = false;
hash = "sha256-123…"; url = "http://…/myplugin2.zip";
}; hash = "sha256-123…";
}); };
]; })
];
};
}; };
} }
``` ```

View file

@ -16,7 +16,7 @@ The Emacs package comes with some extra helpers to make it easier to configure.
projectile projectile
use-package use-package
])); ]));
} };
} }
``` ```
@ -102,10 +102,12 @@ This provides a fairly full Emacs start file. It will load in addition to the us
Sometimes `emacs.pkgs.withPackages` is not enough, as this package set has some priorities imposed on packages (with the lowest priority assigned to GNU-devel ELPA, and the highest for packages manually defined in `pkgs/applications/editors/emacs/elisp-packages/manual-packages`). But you can't control these priorities when some package is installed as a dependency. You can override it on a per-package-basis, providing all the required dependencies manually, but it's tedious and there is always a possibility that an unwanted dependency will sneak in through some other package. To completely override such a package, you can use `overrideScope`. Sometimes `emacs.pkgs.withPackages` is not enough, as this package set has some priorities imposed on packages (with the lowest priority assigned to GNU-devel ELPA, and the highest for packages manually defined in `pkgs/applications/editors/emacs/elisp-packages/manual-packages`). But you can't control these priorities when some package is installed as a dependency. You can override it on a per-package-basis, providing all the required dependencies manually, but it's tedious and there is always a possibility that an unwanted dependency will sneak in through some other package. To completely override such a package, you can use `overrideScope`.
```nix ```nix
overrides = self: super: rec { let
haskell-mode = self.melpaPackages.haskell-mode; overrides = self: super: rec {
... haskell-mode = self.melpaPackages.haskell-mode;
}; # ...
};
in
((emacsPackagesFor emacs).overrideScope overrides).withPackages ((emacsPackagesFor emacs).overrideScope overrides).withPackages
(p: with p; [ (p: with p; [
# here both these package will use haskell-mode of our own choice # here both these package will use haskell-mode of our own choice
@ -113,3 +115,4 @@ overrides = self: super: rec {
dante dante
]) ])
``` ```
}

View file

@ -51,7 +51,7 @@ Use `programs.steam.enable = true;` if you want to add steam to `systemPackages`
you need to add: you need to add:
```nix ```nix
steam.override { withJava = true; }; steam.override { withJava = true; }
``` ```
## steam-run {#sec-steam-run} ## steam-run {#sec-steam-run}

View file

@ -65,7 +65,9 @@ A plugin can be any kind of derivation, the only requirement is that it should a
If the plugin is itself a Perl package that needs to be imported from other plugins or scripts, add the following passthrough: If the plugin is itself a Perl package that needs to be imported from other plugins or scripts, add the following passthrough:
```nix ```nix
passthru.perlPackages = [ "self" ]; {
passthru.perlPackages = [ "self" ];
}
``` ```
This will make the urxvt wrapper pick up the dependency and set up the Perl path accordingly. This will make the urxvt wrapper pick up the dependency and set up the Perl path accordingly.

View file

@ -3,9 +3,9 @@
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: 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 ```nix
weechat.override {configure = {availablePlugins, ...}: { weechat.override {configure = ({availablePlugins, ...}: {
plugins = with availablePlugins; [ python perl ]; plugins = with availablePlugins; [ python perl ];
} });
} }
``` ```
@ -59,7 +59,7 @@ weechat.override {
]; ];
init = '' init = ''
/set plugins.var.python.jabber.key "val" /set plugins.var.python.jabber.key "val"
'': '';
}; };
} }
``` ```

View file

@ -15,7 +15,9 @@ Nixpkgs follows the [conventions of GNU autoconf](https://gcc.gnu.org/onlinedocs
In Nixpkgs, these three platforms are defined as attribute sets under the names `buildPlatform`, `hostPlatform`, and `targetPlatform`. They are always defined as attributes in the standard environment. That means one can access them like: In Nixpkgs, these three platforms are defined as attribute sets under the names `buildPlatform`, `hostPlatform`, and `targetPlatform`. They are always defined as attributes in the standard environment. That means one can access them like:
```nix ```nix
{ stdenv, fooDep, barDep, ... }: ...stdenv.buildPlatform... { stdenv, fooDep, barDep, ... }: {
# ...stdenv.buildPlatform...
}
``` ```
`buildPlatform` `buildPlatform`
@ -127,7 +129,9 @@ Some frequently encountered problems when packaging for cross-compilation should
Many packages assume that an unprefixed binutils (`cc`/`ar`/`ld` etc.) is available, but Nix doesn't provide one. It only provides a prefixed one, just as it only does for all the other binutils programs. It may be necessary to patch the package to fix the build system to use a prefix. For instance, instead of `cc`, use `${stdenv.cc.targetPrefix}cc`. Many packages assume that an unprefixed binutils (`cc`/`ar`/`ld` etc.) is available, but Nix doesn't provide one. It only provides a prefixed one, just as it only does for all the other binutils programs. It may be necessary to patch the package to fix the build system to use a prefix. For instance, instead of `cc`, use `${stdenv.cc.targetPrefix}cc`.
```nix ```nix
makeFlags = [ "CC=${stdenv.cc.targetPrefix}cc" ]; {
makeFlags = [ "CC=${stdenv.cc.targetPrefix}cc" ];
}
``` ```
#### How do I avoid compiling a GCC cross-compiler from source? {#cross-qa-avoid-compiling-gcc-cross-compiler} #### How do I avoid compiling a GCC cross-compiler from source? {#cross-qa-avoid-compiling-gcc-cross-compiler}
@ -142,7 +146,9 @@ $ nix-build '<nixpkgs>' -A pkgsCross.raspberryPi.hello
Add the following to your `mkDerivation` invocation. Add the following to your `mkDerivation` invocation.
```nix ```nix
depsBuildBuild = [ buildPackages.stdenv.cc ]; {
depsBuildBuild = [ buildPackages.stdenv.cc ];
}
``` ```
#### My packages testsuite needs to run host platform code. {#cross-testsuite-runs-host-code} #### My packages testsuite needs to run host platform code. {#cross-testsuite-runs-host-code}
@ -150,7 +156,9 @@ depsBuildBuild = [ buildPackages.stdenv.cc ];
Add the following to your `mkDerivation` invocation. Add the following to your `mkDerivation` invocation.
```nix ```nix
doCheck = stdenv.buildPlatform.canExecute stdenv.hostPlatform; {
doCheck = stdenv.buildPlatform.canExecute stdenv.hostPlatform;
}
``` ```
#### Package using Meson needs to run binaries for the host platform during build. {#cross-meson-runs-host-code} #### Package using Meson needs to run binaries for the host platform during build. {#cross-meson-runs-host-code}
@ -159,12 +167,14 @@ Add `mesonEmulatorHook` to `nativeBuildInputs` conditionally on if the target bi
e.g. e.g.
``` ```nix
nativeBuildInputs = [ {
meson nativeBuildInputs = [
] ++ lib.optionals (!stdenv.buildPlatform.canExecute stdenv.hostPlatform) [ meson
mesonEmulatorHook ] ++ lib.optionals (!stdenv.buildPlatform.canExecute stdenv.hostPlatform) [
]; mesonEmulatorHook
];
}
``` ```
Example of an error which this fixes. Example of an error which this fixes.

View file

@ -3,17 +3,19 @@
Nix packages can declare *meta-attributes* that contain information about a package such as a description, its homepage, its license, and so on. For instance, the GNU Hello package has a `meta` declaration like this: Nix packages can declare *meta-attributes* that contain information about a package such as a description, its homepage, its license, and so on. For instance, the GNU Hello package has a `meta` declaration like this:
```nix ```nix
meta = { {
description = "A program that produces a familiar, friendly greeting"; meta = {
longDescription = '' description = "A program that produces a familiar, friendly greeting";
GNU Hello is a program that prints "Hello, world!" when you run it. longDescription = ''
It is fully customizable. GNU Hello is a program that prints "Hello, world!" when you run it.
''; It is fully customizable.
homepage = "https://www.gnu.org/software/hello/manual/"; '';
license = lib.licenses.gpl3Plus; homepage = "https://www.gnu.org/software/hello/manual/";
maintainers = with lib.maintainers; [ eelco ]; license = lib.licenses.gpl3Plus;
platforms = lib.platforms.all; maintainers = with lib.maintainers; [ eelco ];
}; platforms = lib.platforms.all;
};
}
``` ```
Meta-attributes are not passed to the builder of the package. Thus, a change to a meta-attribute doesnt trigger a recompilation of the package. Meta-attributes are not passed to the builder of the package. Thus, a change to a meta-attribute doesnt trigger a recompilation of the package.
@ -82,7 +84,9 @@ The *priority* of the package, used by `nix-env` to resolve file name conflicts
The list of Nix platform types on which the package is supported. Hydra builds packages according to the platform specified. If no platform is specified, the package does not have prebuilt binaries. An example is: The list of Nix platform types on which the package is supported. Hydra builds packages according to the platform specified. If no platform is specified, the package does not have prebuilt binaries. An example is:
```nix ```nix
meta.platforms = lib.platforms.linux; {
meta.platforms = lib.platforms.linux;
}
``` ```
Attribute Set `lib.platforms` defines [various common lists](https://github.com/NixOS/nixpkgs/blob/master/lib/systems/doubles.nix) of platforms types. Attribute Set `lib.platforms` defines [various common lists](https://github.com/NixOS/nixpkgs/blob/master/lib/systems/doubles.nix) of platforms types.
@ -95,8 +99,10 @@ In general it is preferable to set `meta.platforms = lib.platforms.all` and then
For example, a package which requires dynamic linking and cannot be linked statically could use this: For example, a package which requires dynamic linking and cannot be linked statically could use this:
```nix ```nix
meta.platforms = lib.platforms.all; {
meta.badPlatforms = [ lib.systems.inspect.patterns.isStatic ]; meta.platforms = lib.platforms.all;
meta.badPlatforms = [ lib.systems.inspect.patterns.isStatic ];
}
``` ```
The [`lib.meta.availableOn`](https://github.com/NixOS/nixpkgs/blob/b03ac42b0734da3e7be9bf8d94433a5195734b19/lib/meta.nix#L95-L106) function can be used to test whether or not a package is available (i.e. buildable) on a given platform. The [`lib.meta.availableOn`](https://github.com/NixOS/nixpkgs/blob/b03ac42b0734da3e7be9bf8d94433a5195734b19/lib/meta.nix#L95-L106) function can be used to test whether or not a package is available (i.e. buildable) on a given platform.
@ -136,7 +142,7 @@ For more on how to write and run package tests, see [](#sec-package-tests).
The NixOS tests are available as `nixosTests` in parameters of derivations. For instance, the OpenSMTPD derivation includes lines similar to: The NixOS tests are available as `nixosTests` in parameters of derivations. For instance, the OpenSMTPD derivation includes lines similar to:
```nix ```nix
{ /* ... */, nixosTests }: { /* ... , */ nixosTests }:
{ {
# ... # ...
passthru.tests = { passthru.tests = {
@ -194,8 +200,10 @@ To be effective, it must be presented directly to an evaluation process that han
The list of Nix platform types for which the [Hydra](https://github.com/nixos/hydra) [instance at `hydra.nixos.org`](https://nixos.org/hydra) will build the package. (Hydra is the Nix-based continuous build system.) It defaults to the value of `meta.platforms`. Thus, the only reason to set `meta.hydraPlatforms` is if you want `hydra.nixos.org` to build the package on a subset of `meta.platforms`, or not at all, e.g. The list of Nix platform types for which the [Hydra](https://github.com/nixos/hydra) [instance at `hydra.nixos.org`](https://nixos.org/hydra) will build the package. (Hydra is the Nix-based continuous build system.) It defaults to the value of `meta.platforms`. Thus, the only reason to set `meta.hydraPlatforms` is if you want `hydra.nixos.org` to build the package on a subset of `meta.platforms`, or not at all, e.g.
```nix ```nix
meta.platforms = lib.platforms.linux; {
meta.hydraPlatforms = []; meta.platforms = lib.platforms.linux;
meta.hydraPlatforms = [];
}
``` ```
### `broken` {#var-meta-broken} ### `broken` {#var-meta-broken}
@ -209,13 +217,17 @@ This means that `broken` can be used to express constraints, for example:
- Does not cross compile - Does not cross compile
```nix ```nix
meta.broken = !(stdenv.buildPlatform.canExecute stdenv.hostPlatform) {
meta.broken = !(stdenv.buildPlatform.canExecute stdenv.hostPlatform);
}
``` ```
- Broken if all of a certain set of its dependencies are broken - Broken if all of a certain set of its dependencies are broken
```nix ```nix
meta.broken = lib.all (map (p: p.meta.broken) [ glibc musl ]) {
meta.broken = lib.all (map (p: p.meta.broken) [ glibc musl ]);
}
``` ```
This makes `broken` strictly more powerful than `meta.badPlatforms`. This makes `broken` strictly more powerful than `meta.badPlatforms`.

View file

@ -30,7 +30,9 @@ Here you find how to write a derivation that produces multiple outputs.
In nixpkgs there is a framework supporting multiple-output derivations. It tries to cover most cases by default behavior. You can find the source separated in `<nixpkgs/pkgs/build-support/setup-hooks/multiple-outputs.sh>`; its relatively well-readable. The whole machinery is triggered by defining the `outputs` attribute to contain the list of desired output names (strings). In nixpkgs there is a framework supporting multiple-output derivations. It tries to cover most cases by default behavior. You can find the source separated in `<nixpkgs/pkgs/build-support/setup-hooks/multiple-outputs.sh>`; its relatively well-readable. The whole machinery is triggered by defining the `outputs` attribute to contain the list of desired output names (strings).
```nix ```nix
outputs = [ "bin" "dev" "out" "doc" ]; {
outputs = [ "bin" "dev" "out" "doc" ];
}
``` ```
Often such a single line is enough. For each output an equally named environment variable is passed to the builder and contains the path in nix store for that output. Typically you also want to have the main `out` output, as it catches any files that didnt get elsewhere. Often such a single line is enough. For each output an equally named environment variable is passed to the builder and contains the path in nix store for that output. Typically you also want to have the main `out` output, as it catches any files that didnt get elsewhere.

View file

@ -36,7 +36,7 @@ Many packages have dependencies that are not provided in the standard environmen
stdenv.mkDerivation { stdenv.mkDerivation {
pname = "libfoo"; pname = "libfoo";
version = "1.2.3"; version = "1.2.3";
... # ...
buildInputs = [libbar perl ncurses]; buildInputs = [libbar perl ncurses];
} }
``` ```
@ -49,7 +49,7 @@ Often it is necessary to override or modify some aspect of the build. To make th
stdenv.mkDerivation { stdenv.mkDerivation {
pname = "fnord"; pname = "fnord";
version = "4.5"; version = "4.5";
... # ...
buildPhase = '' buildPhase = ''
gcc foo.c -o foo gcc foo.c -o foo
''; '';
@ -70,7 +70,7 @@ While the standard environment provides a generic builder, you can still supply
stdenv.mkDerivation { stdenv.mkDerivation {
pname = "libfoo"; pname = "libfoo";
version = "1.2.3"; version = "1.2.3";
... # ...
builder = ./builder.sh; builder = ./builder.sh;
} }
``` ```
@ -449,11 +449,13 @@ Unless set to `false`, some build systems with good support for parallel buildin
This is an attribute set which can be filled with arbitrary values. For example: This is an attribute set which can be filled with arbitrary values. For example:
```nix ```nix
passthru = { {
foo = "bar"; passthru = {
baz = { foo = "bar";
value1 = 4; baz = {
value2 = 5; value1 = 4;
value2 = 5;
};
}; };
} }
``` ```
@ -467,27 +469,33 @@ A script to be run by `maintainers/scripts/update.nix` when the package is match
- []{#var-passthru-updateScript-command} an executable file, either on the file system: - []{#var-passthru-updateScript-command} an executable file, either on the file system:
```nix ```nix
passthru.updateScript = ./update.sh; {
passthru.updateScript = ./update.sh;
}
``` ```
or inside the expression itself: or inside the expression itself:
```nix ```nix
passthru.updateScript = writeScript "update-zoom-us" '' {
#!/usr/bin/env nix-shell passthru.updateScript = writeScript "update-zoom-us" ''
#!nix-shell -i bash -p curl pcre2 common-updater-scripts #!/usr/bin/env nix-shell
#!nix-shell -i bash -p curl pcre2 common-updater-scripts
set -eu -o pipefail set -eu -o pipefail
version="$(curl -sI https://zoom.us/client/latest/zoom_x86_64.tar.xz | grep -Fi 'Location:' | pcre2grep -o1 '/(([0-9]\.?)+)/')" version="$(curl -sI https://zoom.us/client/latest/zoom_x86_64.tar.xz | grep -Fi 'Location:' | pcre2grep -o1 '/(([0-9]\.?)+)/')"
update-source-version zoom-us "$version" update-source-version zoom-us "$version"
''; '';
}
``` ```
- a list, a script followed by arguments to be passed to it: - a list, a script followed by arguments to be passed to it:
```nix ```nix
passthru.updateScript = [ ../../update.sh pname "--requested-release=unstable" ]; {
passthru.updateScript = [ ../../update.sh pname "--requested-release=unstable" ];
}
``` ```
- an attribute set containing: - an attribute set containing:
@ -496,18 +504,22 @@ A script to be run by `maintainers/scripts/update.nix` when the package is match
- [`supportedFeatures`]{#var-passthru-updateScript-set-supportedFeatures} (optional) a list of the [extra features](#var-passthru-updateScript-supported-features) the script supports. - [`supportedFeatures`]{#var-passthru-updateScript-set-supportedFeatures} (optional) a list of the [extra features](#var-passthru-updateScript-supported-features) the script supports.
```nix ```nix
passthru.updateScript = { {
command = [ ../../update.sh pname ]; passthru.updateScript = {
attrPath = pname; command = [ ../../update.sh pname ];
supportedFeatures = [ … ]; attrPath = pname;
}; supportedFeatures = [ /* ... */ ];
};
}
``` ```
::: {.tip} ::: {.tip}
A common pattern is to use the [`nix-update-script`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/common-updater/nix-update.nix) attribute provided in Nixpkgs, which runs [`nix-update`](https://github.com/Mic92/nix-update): A common pattern is to use the [`nix-update-script`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/common-updater/nix-update.nix) attribute provided in Nixpkgs, which runs [`nix-update`](https://github.com/Mic92/nix-update):
```nix ```nix
passthru.updateScript = nix-update-script { }; {
passthru.updateScript = nix-update-script { };
}
``` ```
For simple packages, this is often enough, and will ensure that the package is updated automatically by [`nixpkgs-update`](https://ryantm.github.io/nixpkgs-update) when a new version is released. The [update bot](https://nix-community.org/update-bot) runs periodically to attempt to automatically update packages, and will run `passthru.updateScript` if set. While not strictly necessary if the project is listed on [Repology](https://repology.org), using `nix-update-script` allows the package to update via many more sources (e.g. GitHub releases). For simple packages, this is often enough, and will ensure that the package is updated automatically by [`nixpkgs-update`](https://ryantm.github.io/nixpkgs-update) when a new version is released. The [update bot](https://nix-community.org/update-bot) runs periodically to attempt to automatically update packages, and will run `passthru.updateScript` if set. While not strictly necessary if the project is listed on [Repology](https://repology.org), using `nix-update-script` allows the package to update via many more sources (e.g. GitHub releases).
@ -846,7 +858,9 @@ The file name of the Makefile.
A list of strings passed as additional flags to `make`. These flags are also used by the default install and check phase. For setting make flags specific to the build phase, use `buildFlags` (see below). A list of strings passed as additional flags to `make`. These flags are also used by the default install and check phase. For setting make flags specific to the build phase, use `buildFlags` (see below).
```nix ```nix
makeFlags = [ "PREFIX=$(out)" ]; {
makeFlags = [ "PREFIX=$(out)" ];
}
``` ```
::: {.note} ::: {.note}
@ -858,9 +872,11 @@ The flags are quoted in bash, but environment variables can be specified by usin
A shell array containing additional arguments passed to `make`. You must use this instead of `makeFlags` if the arguments contain spaces, e.g. A shell array containing additional arguments passed to `make`. You must use this instead of `makeFlags` if the arguments contain spaces, e.g.
```nix ```nix
preBuild = '' {
makeFlagsArray+=(CFLAGS="-O0 -g" LDFLAGS="-lfoo -lbar") preBuild = ''
''; makeFlagsArray+=(CFLAGS="-O0 -g" LDFLAGS="-lfoo -lbar")
'';
}
``` ```
Note that shell arrays cannot be passed through environment variables, so you cannot set `makeFlagsArray` in a derivation attribute (because those are passed through environment variables): you have to define them in shell code. Note that shell arrays cannot be passed through environment variables, so you cannot set `makeFlagsArray` in a derivation attribute (because those are passed through environment variables): you have to define them in shell code.
@ -892,7 +908,9 @@ The check phase checks whether the package was built correctly by running its te
Controls whether the check phase is executed. By default it is skipped, but if `doCheck` is set to true, the check phase is usually executed. Thus you should set Controls whether the check phase is executed. By default it is skipped, but if `doCheck` is set to true, the check phase is usually executed. Thus you should set
```nix ```nix
doCheck = true; {
doCheck = true;
}
``` ```
in the derivation to enable checks. The exception is cross compilation. Cross compiled builds never run tests, no matter how `doCheck` is set, as the newly-built program wont run on the platform used to build it. in the derivation to enable checks. The exception is cross compilation. Cross compiled builds never run tests, no matter how `doCheck` is set, as the newly-built program wont run on the platform used to build it.
@ -945,7 +963,9 @@ See the [build phase](#var-stdenv-makeFlags) for details.
The make targets that perform the installation. Defaults to `install`. Example: The make targets that perform the installation. Defaults to `install`. Example:
```nix ```nix
installTargets = "install-bin install-doc"; {
installTargets = "install-bin install-doc";
}
``` ```
##### `installFlags` / `installFlagsArray` {#var-stdenv-installFlags} ##### `installFlags` / `installFlagsArray` {#var-stdenv-installFlags}
@ -1024,7 +1044,7 @@ This example prevents all `*.rlib` files from being stripped:
```nix ```nix
stdenv.mkDerivation { stdenv.mkDerivation {
# ... # ...
stripExclude = [ "*.rlib" ] stripExclude = [ "*.rlib" ];
} }
``` ```
@ -1033,7 +1053,7 @@ This example prevents files within certain paths from being stripped:
```nix ```nix
stdenv.mkDerivation { stdenv.mkDerivation {
# ... # ...
stripExclude = [ "lib/modules/*/build/* ] stripExclude = [ "lib/modules/*/build/*" ];
} }
``` ```
@ -1134,7 +1154,9 @@ It is often better to add tests that are not part of the source distribution to
Controls whether the installCheck phase is executed. By default it is skipped, but if `doInstallCheck` is set to true, the installCheck phase is usually executed. Thus you should set Controls whether the installCheck phase is executed. By default it is skipped, but if `doInstallCheck` is set to true, the installCheck phase is usually executed. Thus you should set
```nix ```nix
doInstallCheck = true; {
doInstallCheck = true;
}
``` ```
in the derivation to enable install checks. The exception is cross compilation. Cross compiled builds never run tests, no matter how `doInstallCheck` is set, as the newly-built program wont run on the platform used to build it. in the derivation to enable install checks. The exception is cross compilation. Cross compiled builds never run tests, no matter how `doInstallCheck` is set, as the newly-built program wont run on the platform used to build it.
@ -1244,9 +1266,11 @@ To use this, add `removeReferencesTo` to `nativeBuildInputs`.
As `remove-references-to` is an actual executable and not a shell function, it can be used with `find`. As `remove-references-to` is an actual executable and not a shell function, it can be used with `find`.
Example removing all references to the compiler in the output: Example removing all references to the compiler in the output:
```nix ```nix
postInstall = '' {
find "$out" -type f -exec remove-references-to -t ${stdenv.cc} '{}' + postInstall = ''
''; find "$out" -type f -exec remove-references-to -t ${stdenv.cc} '{}' +
'';
}
``` ```
### `substitute` \<infile\> \<outfile\> \<subs\> {#fun-substitute} ### `substitute` \<infile\> \<outfile\> \<subs\> {#fun-substitute}

View file

@ -176,7 +176,7 @@ You can define a function called `packageOverrides` in your local `~/.config/nix
```nix ```nix
{ {
packageOverrides = pkgs: rec { packageOverrides = pkgs: rec {
foo = pkgs.foo.override { ... }; foo = pkgs.foo.override { /* ... */ };
}; };
} }
``` ```

View file

@ -141,7 +141,7 @@ For BLAS/LAPACK switching to work correctly, all packages must depend on `blas`
assert (!blas.isILP64) && (!lapack.isILP64); assert (!blas.isILP64) && (!lapack.isILP64);
stdenv.mkDerivation { stdenv.mkDerivation {
... # ...
} }
``` ```

View file

@ -13,13 +13,13 @@ It is used to override the arguments passed to a function.
Example usages: Example usages:
```nix ```nix
pkgs.foo.override { arg1 = val1; arg2 = val2; ... } pkgs.foo.override { arg1 = val1; arg2 = val2; /* ... */ }
``` ```
It's also possible to access the previous arguments. It's also possible to access the previous arguments.
```nix ```nix
pkgs.foo.override (previous: { arg1 = previous.arg1; ... }) pkgs.foo.override (previous: { arg1 = previous.arg1; /* ... */ })
``` ```
<!-- TODO: move below programlisting to a new section about extending and overlays and reference it --> <!-- TODO: move below programlisting to a new section about extending and overlays and reference it -->
@ -27,13 +27,15 @@ pkgs.foo.override (previous: { arg1 = previous.arg1; ... })
```nix ```nix
import pkgs.path { overlays = [ (self: super: { import pkgs.path { overlays = [ (self: super: {
foo = super.foo.override { barSupport = true ; }; foo = super.foo.override { barSupport = true ; };
})]}; })];}
``` ```
```nix ```nix
mypkg = pkgs.callPackage ./mypkg.nix { {
mydep = pkgs.mydep.override { ... }; mypkg = pkgs.callPackage ./mypkg.nix {
} mydep = pkgs.mydep.override { /* ... */ };
};
}
``` ```
In the first example, `pkgs.foo` is the result of a function call with some default arguments, usually a derivation. Using `pkgs.foo.override` will call the same function with the given new arguments. In the first example, `pkgs.foo` is the result of a function call with some default arguments, usually a derivation. Using `pkgs.foo.override` will call the same function with the given new arguments.
@ -45,9 +47,11 @@ The function `overrideAttrs` allows overriding the attribute set passed to a `st
Example usages: Example usages:
```nix ```nix
helloBar = pkgs.hello.overrideAttrs (finalAttrs: previousAttrs: { {
pname = previousAttrs.pname + "-bar"; helloBar = pkgs.hello.overrideAttrs (finalAttrs: previousAttrs: {
}); pname = previousAttrs.pname + "-bar";
});
}
``` ```
In the above example, "-bar" is appended to the pname attribute, while all other attributes will be retained from the original `hello` package. In the above example, "-bar" is appended to the pname attribute, while all other attributes will be retained from the original `hello` package.
@ -61,9 +65,11 @@ If only a one-argument function is written, the argument has the meaning of `pre
Function arguments can be omitted entirely if there is no need to access `previousAttrs` or `finalAttrs`. Function arguments can be omitted entirely if there is no need to access `previousAttrs` or `finalAttrs`.
```nix ```nix
helloWithDebug = pkgs.hello.overrideAttrs { {
separateDebugInfo = true; helloWithDebug = pkgs.hello.overrideAttrs {
}; separateDebugInfo = true;
};
}
``` ```
In the above example, the `separateDebugInfo` attribute is overridden to be true, thus building debug info for `helloWithDebug`. In the above example, the `separateDebugInfo` attribute is overridden to be true, thus building debug info for `helloWithDebug`.
@ -87,14 +93,16 @@ The function `overrideDerivation` creates a new derivation based on an existing
Example usage: Example usage:
```nix ```nix
mySed = pkgs.gnused.overrideDerivation (oldAttrs: { {
name = "sed-4.2.2-pre"; mySed = pkgs.gnused.overrideDerivation (oldAttrs: {
src = fetchurl { name = "sed-4.2.2-pre";
url = "ftp://alpha.gnu.org/gnu/sed/sed-4.2.2-pre.tar.bz2"; src = fetchurl {
hash = "sha256-MxBJRcM2rYzQYwJ5XKxhXTQByvSg5jZc5cSHEZoB2IY="; url = "ftp://alpha.gnu.org/gnu/sed/sed-4.2.2-pre.tar.bz2";
}; hash = "sha256-MxBJRcM2rYzQYwJ5XKxhXTQByvSg5jZc5cSHEZoB2IY=";
patches = []; };
}); patches = [];
});
}
``` ```
In the above example, the `name`, `src`, and `patches` of the derivation will be overridden, while all other attributes will be retained from the original derivation. In the above example, the `name`, `src`, and `patches` of the derivation will be overridden, while all other attributes will be retained from the original derivation.
@ -112,8 +120,10 @@ The function `lib.makeOverridable` is used to make the result of a function easi
Example usage: Example usage:
```nix ```nix
f = { a, b }: { result = a+b; }; {
c = lib.makeOverridable f { a = 1; b = 2; }; f = { a, b }: { result = a+b; };
c = lib.makeOverridable f { a = 1; b = 2; };
}
``` ```
The variable `c` is the value of the `f` function applied with some default arguments. Hence the value of `c.result` is `3`, in this example. The variable `c` is the value of the `f` function applied with some default arguments. Hence the value of `c.result` is `3`, in this example.

View file

@ -97,7 +97,7 @@ let
inherit (self.strings) concatStrings concatMapStrings concatImapStrings inherit (self.strings) concatStrings concatMapStrings concatImapStrings
intersperse concatStringsSep concatMapStringsSep intersperse concatStringsSep concatMapStringsSep
concatImapStringsSep concatLines makeSearchPath makeSearchPathOutput concatImapStringsSep concatLines makeSearchPath makeSearchPathOutput
makeLibraryPath makeBinPath optionalString makeLibraryPath makeIncludePath makeBinPath optionalString
hasInfix hasPrefix hasSuffix stringToCharacters stringAsChars escape hasInfix hasPrefix hasSuffix stringToCharacters stringAsChars escape
escapeShellArg escapeShellArgs escapeShellArg escapeShellArgs
isStorePath isStringLike isStorePath isStringLike

View file

@ -206,6 +206,18 @@ rec {
*/ */
makeLibraryPath = makeSearchPathOutput "lib" "lib"; makeLibraryPath = makeSearchPathOutput "lib" "lib";
/* Construct an include search path (such as C_INCLUDE_PATH) containing the
header files for a set of packages or paths.
Example:
makeIncludePath [ "/usr" "/usr/local" ]
=> "/usr/include:/usr/local/include"
pkgs = import <nixpkgs> { }
makeIncludePath [ pkgs.openssl pkgs.zlib ]
=> "/nix/store/9rz8gxhzf8sw4kf2j2f1grr49w8zx5vj-openssl-1.0.1r-dev/include:/nix/store/wwh7mhwh269sfjkm6k5665b5kgp7jrk2-zlib-1.2.8-dev/include"
*/
makeIncludePath = makeSearchPathOutput "dev" "include";
/* Construct a binary search path (such as $PATH) containing the /* Construct a binary search path (such as $PATH) containing the
binaries for a set of packages. binaries for a set of packages.

View file

@ -64,6 +64,7 @@ let
lists lists
listToAttrs listToAttrs
makeExtensible makeExtensible
makeIncludePath
makeOverridable makeOverridable
mapAttrs mapAttrs
matchAttrs matchAttrs
@ -296,6 +297,35 @@ runTests {
expected = "a\nb\nc\n"; expected = "a\nb\nc\n";
}; };
testMakeIncludePathWithPkgs = {
expr = (makeIncludePath [
# makeIncludePath preferably selects the "dev" output
{ dev.outPath = "/dev"; out.outPath = "/out"; outPath = "/default"; }
# "out" is used if "dev" is not found
{ out.outPath = "/out"; outPath = "/default"; }
# And it returns the derivation directly if there's no "out" either
{ outPath = "/default"; }
# Same if the output is specified explicitly, even if there's a "dev"
{ dev.outPath = "/dev"; outPath = "/default"; outputSpecified = true; }
]);
expected = "/dev/include:/out/include:/default/include:/default/include";
};
testMakeIncludePathWithEmptyList = {
expr = (makeIncludePath [ ]);
expected = "";
};
testMakeIncludePathWithOneString = {
expr = (makeIncludePath [ "/usr" ]);
expected = "/usr/include";
};
testMakeIncludePathWithManyString = {
expr = (makeIncludePath [ "/usr" "/usr/local" ]);
expected = "/usr/include:/usr/local/include";
};
testReplicateString = { testReplicateString = {
expr = strings.replicate 5 "hello"; expr = strings.replicate 5 "hello";
expected = "hellohellohellohellohello"; expected = "hellohellohellohellohello";

View file

@ -87,8 +87,8 @@ checks should be performed:
keys = [{ keys = [{
fingerprint = "0000 0000 2A70 6423 0AED 3C11 F04F 7A19 AAA6 3AFE"; fingerprint = "0000 0000 2A70 6423 0AED 3C11 F04F 7A19 AAA6 3AFE";
}]; }];
} };
}; }
``` ```
First receive their key from a keyserver: First receive their key from a keyserver:
@ -133,8 +133,8 @@ checks should be performed:
name = "Example User"; name = "Example User";
github = "ghost"; github = "ghost";
githubId = 10137; githubId = 10137;
} };
}; }
``` ```
First, make sure that the listed GitHub handle matches the author of First, make sure that the listed GitHub handle matches the author of

View file

@ -256,6 +256,12 @@
githubId = 381298; githubId = 381298;
name = "9R"; name = "9R";
}; };
A1ca7raz = {
email = "aya@wtm.moe";
github = "A1ca7raz";
githubId = 7345998;
name = "A1ca7raz";
};
a1russell = { a1russell = {
email = "adamlr6+pub@gmail.com"; email = "adamlr6+pub@gmail.com";
github = "a1russell"; github = "a1russell";
@ -1784,6 +1790,13 @@
fingerprint = "C919 E69E A7C0 E147 9E0F C26E 1EDA D0C6 70BD 062D"; fingerprint = "C919 E69E A7C0 E147 9E0F C26E 1EDA D0C6 70BD 062D";
}]; }];
}; };
assistant = {
email = "assistant.moetron@gmail.com";
github = "Assistant";
githubId = 2748721;
matrix = "@assistant:pygmalion.chat";
name = "Assistant Moetron";
};
astavie = { astavie = {
email = "astavie@pm.me"; email = "astavie@pm.me";
github = "astavie"; github = "astavie";
@ -2544,6 +2557,12 @@
githubId = 34919100; githubId = 34919100;
name = "Brendan Hall"; name = "Brendan Hall";
}; };
bhankas = {
email = "payas@relekar.org";
github = "bhankas";
githubId = 24254289;
name = "Payas Relekar";
};
bhipple = { bhipple = {
email = "bhipple@protonmail.com"; email = "bhipple@protonmail.com";
github = "bhipple"; github = "bhipple";
@ -3680,6 +3699,13 @@
githubId = 46303707; githubId = 46303707;
name = "Christian Lütke-Stetzkamp"; name = "Christian Lütke-Stetzkamp";
}; };
clot27 = {
name = "Clot";
email = "adityayadav11082@protonmail.com";
github = "clot27";
githubId = 69784758;
matrix = "@clot27:matrix.org";
};
clr-cera = { clr-cera = {
email = "clrcera05@gmail.com"; email = "clrcera05@gmail.com";
github = "clr-cera"; github = "clr-cera";
@ -4745,6 +4771,12 @@
githubId = 4956158; githubId = 4956158;
name = "Robin Stumm"; name = "Robin Stumm";
}; };
DerRockWolf = {
email = "git@rockwolf.eu";
github = "DerRockWolf";
githubId = 50499906;
name = "DerRockWolf";
};
DerTim1 = { DerTim1 = {
email = "tim.digel@active-group.de"; email = "tim.digel@active-group.de";
github = "DerTim1"; github = "DerTim1";
@ -4826,6 +4858,12 @@
github = "dfithian"; github = "dfithian";
githubId = 8409320; githubId = 8409320;
}; };
dflores = {
email = "dflores.country455@passinbox.com";
name = "David Flores";
github = "dflores1";
githubId = 8538265;
};
dfordivam = { dfordivam = {
email = "dfordivam+nixpkgs@gmail.com"; email = "dfordivam+nixpkgs@gmail.com";
github = "dfordivam"; github = "dfordivam";
@ -5825,6 +5863,13 @@
githubId = 418227; githubId = 418227;
name = "Jean-Philippe Braun"; name = "Jean-Philippe Braun";
}; };
eopb = {
email = "ethanboxx@gmail.com";
github = "eopb";
githubId = 8074468;
matrix = "@efun:matrix.org";
name = "Ethan Brierley";
};
eownerdead = { eownerdead = {
name = "EOWNERDEAD"; name = "EOWNERDEAD";
email = "eownerdead@disroot.org"; email = "eownerdead@disroot.org";
@ -6795,6 +6840,15 @@
githubId = 21362942; githubId = 21362942;
name = "Fugi"; name = "Fugi";
}; };
funkeleinhorn = {
email = "git@funkeleinhorn.com";
github = "funkeleinhorn";
githubId = 103313934;
name = "Funkeleinhorn";
keys = [{
fingerprint = "689D 1C81 DA0D 1EB2 F029 D24E C7BE A25A 0A33 5A72";
}];
};
fusion809 = { fusion809 = {
email = "brentonhorne77@gmail.com"; email = "brentonhorne77@gmail.com";
github = "fusion809"; github = "fusion809";
@ -7459,6 +7513,13 @@
githubId = 201997; githubId = 201997;
name = "Eric Seidel"; name = "Eric Seidel";
}; };
grimmauld = {
name = "Sören Bender";
email = "soeren@benjos.de";
github = "LordGrimmauld";
githubId = 49513131;
matrix = "@grimmauld:grimmauld.de";
};
grindhold = { grindhold = {
name = "grindhold"; name = "grindhold";
email = "grindhold+nix@skarphed.org"; email = "grindhold+nix@skarphed.org";
@ -7613,6 +7674,12 @@
githubId = 22756350; githubId = 22756350;
name = "Emile Hansmaennel"; name = "Emile Hansmaennel";
}; };
HannahMR = {
name = "Hannah Rosenberg";
email = "hannah@velascommerce.com";
github = "HannahMR";
githubId = 9088467;
};
hansjoergschurr = { hansjoergschurr = {
email = "commits@schurr.at"; email = "commits@schurr.at";
github = "hansjoergschurr"; github = "hansjoergschurr";
@ -7788,6 +7855,12 @@
matrix = "@chris:netsoj.nl"; matrix = "@chris:netsoj.nl";
name = "Chris Josten"; name = "Chris Josten";
}; };
hennk = {
email = "henning.kiel@gmail.com";
github = "hennk";
githubId = 328259;
name = "Henning Kiel";
};
henrikolsson = { henrikolsson = {
email = "henrik@fixme.se"; email = "henrik@fixme.se";
github = "henrikolsson"; github = "henrikolsson";
@ -8666,6 +8739,12 @@
github = "j4m3s-s"; github = "j4m3s-s";
githubId = 9413812; githubId = 9413812;
}; };
jab = {
name = "Joshua Bronson";
email = "jabronson@gmail.com";
github = "jab";
githubId = 64992;
};
jacbart = { jacbart = {
name = "Jack Bartlett"; name = "Jack Bartlett";
email = "jacbart@gmail.com"; email = "jacbart@gmail.com";
@ -10061,6 +10140,11 @@
githubId = 15855440; githubId = 15855440;
name = "Keanu Ashwell"; name = "Keanu Ashwell";
}; };
katanallama = {
github = "katanallama";
githubId = 70604257;
name = "katanallama";
};
katexochen = { katexochen = {
github = "katexochen"; github = "katexochen";
githubId = 49727155; githubId = 49727155;
@ -10329,6 +10413,12 @@
githubId = 691290; githubId = 691290;
name = "Keshav Kini"; name = "Keshav Kini";
}; };
kintrix = {
email = "kintrix007@proton.me";
github = "kintrix007";
githubId = 60898798;
name = "kintrix";
};
kinzoku = { kinzoku = {
email = "kinzokudev4869@gmail.com"; email = "kinzokudev4869@gmail.com";
github = "kinzoku-dev"; github = "kinzoku-dev";
@ -10821,6 +10911,12 @@
githubId = 695526; githubId = 695526;
name = "Benjamin Kober"; name = "Benjamin Kober";
}; };
lampros = {
email = "hauahx@gmail.com";
github = "LamprosPitsillos";
githubId = 61395246;
name = "Lampros Pitsillos";
};
larsr = { larsr = {
email = "Lars.Rasmusson@gmail.com"; email = "Lars.Rasmusson@gmail.com";
github = "larsr"; github = "larsr";
@ -11179,6 +11275,12 @@
fingerprint = "92D8 A09D 03DD B774 AABD 53B9 E136 2F07 D750 DB5C"; fingerprint = "92D8 A09D 03DD B774 AABD 53B9 E136 2F07 D750 DB5C";
}]; }];
}; };
lilacious = {
email = "yuchenhe126@gmail.com";
github = "Lilacious";
githubId = 101508537;
name = "Yuchen He";
};
lillycham = { lillycham = {
email = "lillycat332@gmail.com"; email = "lillycat332@gmail.com";
github = "lillycat332"; github = "lillycat332";
@ -11497,6 +11599,15 @@
githubId = 3717454; githubId = 3717454;
name = "Lucas Bergman"; name = "Lucas Bergman";
}; };
lucas-deangelis = {
email = "deangelis.lucas@outlook.com";
github = "lucas-deangelis";
githubId = 55180995;
name = "Lucas De Angelis";
keys = [{
fingerprint = "3C8B D3AD 93BB 1F36 B8FF 30BD 8627 E5ED F74B 5BF4";
}];
};
lucasew = { lucasew = {
email = "lucas59356@gmail.com"; email = "lucas59356@gmail.com";
github = "lucasew"; github = "lucasew";
@ -12495,6 +12606,12 @@
fingerprint = "D709 03C8 0BE9 ACDC 14F0 3BFB 77BF E531 397E DE94"; fingerprint = "D709 03C8 0BE9 ACDC 14F0 3BFB 77BF E531 397E DE94";
}]; }];
}; };
mdorman = {
email = "mdorman@jaunder.io";
github = "mdorman";
githubId = 333344;
name = "Michael Alan Dorman";
};
mdr = { mdr = {
email = "MattRussellUK@gmail.com"; email = "MattRussellUK@gmail.com";
github = "mdr"; github = "mdr";
@ -13615,6 +13732,14 @@
fingerprint = "9E6A 25F2 C1F2 9D76 ED00 1932 1261 173A 01E1 0298"; fingerprint = "9E6A 25F2 C1F2 9D76 ED00 1932 1261 173A 01E1 0298";
}]; }];
}; };
n8henrie = {
name = "Nathan Henrie";
github = "n8henrie";
githubId = 1234956;
"keys" = [{
"fingerprint" = "F21A 6194 C9DB 9899 CD09 E24E 434B 2C14 B8C3 3422";
}];
};
nadir-ishiguro = { nadir-ishiguro = {
github = "nadir-ishiguro"; github = "nadir-ishiguro";
githubId = 23151917; githubId = 23151917;
@ -15035,12 +15160,6 @@
githubId = 116740; githubId = 116740;
name = "Paweł Pacana"; name = "Paweł Pacana";
}; };
payas = {
email = "relekarpayas@gmail.com";
github = "bhankas";
githubId = 24254289;
name = "Payas Relekar";
};
pb- = { pb- = {
email = "pbaecher@gmail.com"; email = "pbaecher@gmail.com";
github = "pb-"; github = "pb-";
@ -15675,6 +15794,12 @@
githubId = 4201956; githubId = 4201956;
name = "pongo1231"; name = "pongo1231";
}; };
poptart = {
email = "poptart@hosakacorp.net";
github = "terrorbyte";
githubId = 1601039;
name = "Cale Black";
};
portothree = { portothree = {
name = "Gustavo Porto"; name = "Gustavo Porto";
email = "gus@p8s.co"; email = "gus@p8s.co";
@ -16091,6 +16216,12 @@
githubId = 39039420; githubId = 39039420;
name = "Quinn Dougherty"; name = "Quinn Dougherty";
}; };
qusic = {
email = "qusicx@gmail.com";
github = "Qusic";
githubId = 2141853;
name = "Bang Lee";
};
qyliss = { qyliss = {
email = "hi@alyssa.is"; email = "hi@alyssa.is";
github = "alyssais"; github = "alyssais";
@ -16293,6 +16424,12 @@
githubId = 25647735; githubId = 25647735;
name = "Victor Freire"; name = "Victor Freire";
}; };
ravenz46 = {
email = "goldraven0406@gmail.com";
github = "RAVENz46";
githubId = 86608952;
name = "RAVENz46";
};
rawkode = { rawkode = {
email = "david.andrew.mckay@gmail.com"; email = "david.andrew.mckay@gmail.com";
github = "rawkode"; github = "rawkode";
@ -16964,6 +17101,12 @@
github = "rski"; github = "rski";
githubId = 2960312; githubId = 2960312;
}; };
rsniezek = {
email = "radoslaw.sniezek@protonmail.com";
github = "rsniezek";
githubId = 19433256;
name = "Radoslaw Sniezek";
};
rsynnest = { rsynnest = {
email = "contact@rsynnest.com"; email = "contact@rsynnest.com";
github = "rsynnest"; github = "rsynnest";
@ -17347,6 +17490,12 @@
githubId = 92817635; githubId = 92817635;
name = "Sanskar Gurdasani"; name = "Sanskar Gurdasani";
}; };
sarahec = {
email = "sarahec@nextquestion.net";
github = "sarahec";
githubId = 11277967;
name = "Sarah Clark";
};
sarcasticadmin = { sarcasticadmin = {
email = "rob@sarcasticadmin.com"; email = "rob@sarcasticadmin.com";
github = "sarcasticadmin"; github = "sarcasticadmin";
@ -18017,6 +18166,16 @@
github = "silky"; github = "silky";
githubId = 129525; githubId = 129525;
}; };
sils = {
name = "Silas Schöffel";
email = "sils@sils.li";
matrix = "@sils:vhack.eu";
github = "s1ls";
githubId = 91412114;
keys = [{
fingerprint = "C1DA A551 B422 7A6F 3FD9 6B3A 467B 7D12 9EA7 3AC9";
}];
};
Silver-Golden = { Silver-Golden = {
name = "Brendan Golden"; name = "Brendan Golden";
email = "github+nixpkgs@brendan.ie"; email = "github+nixpkgs@brendan.ie";
@ -18435,6 +18594,12 @@
githubId = 20756843; githubId = 20756843;
name = "Sofi"; name = "Sofi";
}; };
soyouzpanda = {
name = "soyouzpanda";
email = "soyouzpanda@soyouzpanda.fr";
github = "soyouzpanda";
githubId = 23421201;
};
soywod = { soywod = {
name = "Clément DOUIN"; name = "Clément DOUIN";
email = "clement.douin@posteo.net"; email = "clement.douin@posteo.net";
@ -18508,6 +18673,12 @@
fingerprint = "652F FAAD 5CB8 AF1D 3F96 9521 929E D6C4 0414 D3F5"; fingerprint = "652F FAAD 5CB8 AF1D 3F96 9521 929E D6C4 0414 D3F5";
}]; }];
}; };
spk = {
email = "laurent@spkdev.net";
github = "spk";
githubId = 98590;
name = "Laurent Arnoud";
};
spoonbaker = { spoonbaker = {
github = "Spoonbaker"; github = "Spoonbaker";
githubId = 47164123; githubId = 47164123;
@ -18613,6 +18784,12 @@
githubId = 6362238; githubId = 6362238;
name = "Christoph Honal"; name = "Christoph Honal";
}; };
starkca90 = {
email = "starkca90@gmail.com";
github = "starkca90";
githubId = 2060836;
name = "Casey Stark";
};
starsep = { starsep = {
email = "nix@starsep.com"; email = "nix@starsep.com";
github = "starsep"; github = "starsep";
@ -18693,6 +18870,15 @@
githubId = 89950; githubId = 89950;
name = "Stéphan Kochen"; name = "Stéphan Kochen";
}; };
stephen-huan = {
name = "Stephen Huan";
email = "stephen.huan@cgdct.moe";
github = "stephen-huan";
githubId = 20411956;
keys = [{
fingerprint = "EA6E 2794 8C7D BF5D 0DF0 85A1 0FBC 2E3B A99D D60E";
}];
};
stephenmw = { stephenmw = {
email = "stephen@q5comm.com"; email = "stephen@q5comm.com";
github = "stephenmw"; github = "stephenmw";
@ -21184,6 +21370,15 @@
githubId = 8378365; githubId = 8378365;
name = "P. R. d. O."; name = "P. R. d. O.";
}; };
wolfgangwalther = {
name = "Wolfgang Walther";
email = "walther@technowledgy.de";
github = "wolfgangwalther";
githubId = 9132420;
keys = [{
fingerprint = "F943 A0BC 720C 5BEF 73CD E02D B398 93FA 5F65 CAE1";
}];
};
womfoo = { womfoo = {
email = "kranium@gikos.net"; email = "kranium@gikos.net";
github = "womfoo"; github = "womfoo";

View file

@ -78,6 +78,7 @@ import Network.HTTP.Req (
) )
import System.Directory (XdgDirectory (XdgCache), getXdgDirectory) import System.Directory (XdgDirectory (XdgCache), getXdgDirectory)
import System.Environment (getArgs) import System.Environment (getArgs)
import System.Exit (die)
import System.Process (readProcess) import System.Process (readProcess)
import Prelude hiding (id) import Prelude hiding (id)
import Data.List (sortOn) import Data.List (sortOn)
@ -155,17 +156,20 @@ data Build = Build
data HydraSlownessWorkaroundFlag = HydraSlownessWorkaround | NoHydraSlownessWorkaround data HydraSlownessWorkaroundFlag = HydraSlownessWorkaround | NoHydraSlownessWorkaround
data RequestLogsFlag = RequestLogs | NoRequestLogs data RequestLogsFlag = RequestLogs | NoRequestLogs
usage :: IO a
usage = die "Usage: get-report [--slow] [EVAL-ID] | ping-maintainers | mark-broken-list [--no-request-logs] | eval-info"
main :: IO () main :: IO ()
main = do main = do
args <- getArgs args <- getArgs
case args of case args of
["get-report", "--slow"] -> getBuildReports HydraSlownessWorkaround "get-report":"--slow":id -> getBuildReports HydraSlownessWorkaround id
["get-report"] -> getBuildReports NoHydraSlownessWorkaround "get-report":id -> getBuildReports NoHydraSlownessWorkaround id
["ping-maintainers"] -> printMaintainerPing ["ping-maintainers"] -> printMaintainerPing
["mark-broken-list", "--no-request-logs"] -> printMarkBrokenList NoRequestLogs ["mark-broken-list", "--no-request-logs"] -> printMarkBrokenList NoRequestLogs
["mark-broken-list"] -> printMarkBrokenList RequestLogs ["mark-broken-list"] -> printMarkBrokenList RequestLogs
["eval-info"] -> printEvalInfo ["eval-info"] -> printEvalInfo
_ -> putStrLn "Usage: get-report [--slow] | ping-maintainers | mark-broken-list [--no-request-logs] | eval-info" _ -> usage
reportFileName :: IO FilePath reportFileName :: IO FilePath
reportFileName = getXdgDirectory XdgCache "haskell-updates-build-report.json" reportFileName = getXdgDirectory XdgCache "haskell-updates-build-report.json"
@ -173,23 +177,26 @@ reportFileName = getXdgDirectory XdgCache "haskell-updates-build-report.json"
showT :: Show a => a -> Text showT :: Show a => a -> Text
showT = Text.pack . show showT = Text.pack . show
getBuildReports :: HydraSlownessWorkaroundFlag -> IO () getBuildReports :: HydraSlownessWorkaroundFlag -> [String] -> IO ()
getBuildReports opt = runReq defaultHttpConfig do getBuildReports opt args = runReq defaultHttpConfig do
evalMay <- Seq.lookup 0 . evals <$> hydraJSONQuery mempty ["jobset", "nixpkgs", "haskell-updates", "evals"] eval@Eval{id} <- case args of
eval@Eval{id} <- maybe (liftIO $ fail "No Evaluation found") pure evalMay [id] -> hydraJSONQuery mempty ["eval", Text.pack id]
[] -> do
evalMay <- Seq.lookup 0 . evals <$> hydraJSONQuery mempty ["jobset", "nixpkgs", "haskell-updates", "evals"]
maybe (liftIO $ fail "No Evaluation found") pure evalMay
_ -> liftIO usage
liftIO . putStrLn $ "Fetching evaluation " <> show id <> " from Hydra. This might take a few minutes..." liftIO . putStrLn $ "Fetching evaluation " <> show id <> " from Hydra. This might take a few minutes..."
buildReports <- getEvalBuilds opt id buildReports <- getEvalBuilds opt eval
liftIO do liftIO do
fileName <- reportFileName fileName <- reportFileName
putStrLn $ "Finished fetching all builds from Hydra, saving report as " <> fileName putStrLn $ "Finished fetching all builds from Hydra, saving report as " <> fileName
now <- getCurrentTime now <- getCurrentTime
encodeFile fileName (eval, now, buildReports) encodeFile fileName (eval, now, buildReports)
getEvalBuilds :: HydraSlownessWorkaroundFlag -> Int -> Req (Seq Build) getEvalBuilds :: HydraSlownessWorkaroundFlag -> Eval -> Req (Seq Build)
getEvalBuilds NoHydraSlownessWorkaround id = getEvalBuilds NoHydraSlownessWorkaround Eval{id} =
hydraJSONQuery mempty ["eval", showT id, "builds"] hydraJSONQuery mempty ["eval", showT id, "builds"]
getEvalBuilds HydraSlownessWorkaround id = do getEvalBuilds HydraSlownessWorkaround Eval{builds} = do
Eval{builds} <- hydraJSONQuery mempty [ "eval", showT id ]
forM builds $ \buildId -> do forM builds $ \buildId -> do
liftIO $ putStrLn $ "Querying build " <> show buildId liftIO $ putStrLn $ "Querying build " <> show buildId
hydraJSONQuery mempty [ "build", showT buildId ] hydraJSONQuery mempty [ "build", showT buildId ]

View file

@ -8,6 +8,7 @@ busted,,,,,,
cassowary,,,,,,marsam alerque cassowary,,,,,,marsam alerque
cldr,,,,,,alerque cldr,,,,,,alerque
compat53,,,,,,vcunat compat53,,,,,,vcunat
commons.nvim,,,,,,mrcjkb
cosmo,,,,,,marsam cosmo,,,,,,marsam
coxpcall,,,,1.17.0-1,, coxpcall,,,,1.17.0-1,,
cqueues,,,,,,vcunat cqueues,,,,,,vcunat
@ -18,6 +19,8 @@ fennel,,,,,,misterio77
fidget.nvim,,,,,,mrcjkb fidget.nvim,,,,,,mrcjkb
fifo,,,,,, fifo,,,,,,
fluent,,,,,,alerque fluent,,,,,,alerque
funnyfiles.nvim,,,,,,mrcjkb
fzf-lua,,,,,,mrcjkb
fzy,,,,,,mrcjkb fzy,,,,,,mrcjkb
gitsigns.nvim,https://github.com/lewis6991/gitsigns.nvim.git,,,,5.1, gitsigns.nvim,https://github.com/lewis6991/gitsigns.nvim.git,,,,5.1,
haskell-tools.nvim,,,,,, haskell-tools.nvim,,,,,,
@ -85,6 +88,7 @@ luaunbound,,,,,,
luaunit,,,,,,lockejan luaunit,,,,,,lockejan
luautf8,,,,,,pstn luautf8,,,,,,pstn
luazip,,,,,, luazip,,,,,,
lua-utils.nvim,,,,,,mrcjkb
lua-yajl,,,,,,pstn lua-yajl,,,,,,pstn
lua-iconv,,,,7.0.0,, lua-iconv,,,,7.0.0,,
luuid,,,,20120509-2,, luuid,,,,20120509-2,,
@ -98,6 +102,7 @@ middleclass,,,,,,
mimetypes,,,,,, mimetypes,,,,,,
mpack,,,,,, mpack,,,,,,
moonscript,https://github.com/leafo/moonscript.git,dev-1,,,,arobyn moonscript,https://github.com/leafo/moonscript.git,dev-1,,,,arobyn
neotest,,,,,,mrcjkb
nlua,,,,,,teto nlua,,,,,,teto
nui.nvim,,,,,,mrcjkb nui.nvim,,,,,,mrcjkb
nvim-cmp,https://github.com/hrsh7th/nvim-cmp,,,,, nvim-cmp,https://github.com/hrsh7th/nvim-cmp,,,,,
@ -107,6 +112,10 @@ plenary.nvim,https://github.com/nvim-lua/plenary.nvim.git,,,,5.1,
rapidjson,https://github.com/xpol/lua-rapidjson.git,,,,, rapidjson,https://github.com/xpol/lua-rapidjson.git,,,,,
rocks.nvim,,,,,5.1,teto mrcjkb rocks.nvim,,,,,5.1,teto mrcjkb
rest.nvim,,,,,5.1,teto rest.nvim,,,,,5.1,teto
rocks.nvim,,,,,,mrcjkb
rocks-git.nvim,,,,,,mrcjkb
rocks-config.nvim,,,,,,mrcjkb
rocks-dev.nvim,,,,,,mrcjkb
rustaceanvim,,,,,,mrcjkb rustaceanvim,,,,,,mrcjkb
say,https://github.com/Olivine-Labs/say.git,,,,, say,https://github.com/Olivine-Labs/say.git,,,,,
serpent,,,,,,lockejan serpent,,,,,,lockejan

1 name src ref server version luaversion maintainers
8 cassowary marsam alerque
9 cldr alerque
10 compat53 vcunat
11 commons.nvim mrcjkb
12 cosmo marsam
13 coxpcall 1.17.0-1
14 cqueues vcunat
19 fidget.nvim mrcjkb
20 fifo
21 fluent alerque
22 funnyfiles.nvim mrcjkb
23 fzf-lua mrcjkb
24 fzy mrcjkb
25 gitsigns.nvim https://github.com/lewis6991/gitsigns.nvim.git 5.1
26 haskell-tools.nvim
88 luaunit lockejan
89 luautf8 pstn
90 luazip
91 lua-utils.nvim mrcjkb
92 lua-yajl pstn
93 lua-iconv 7.0.0
94 luuid 20120509-2
102 mimetypes
103 mpack
104 moonscript https://github.com/leafo/moonscript.git dev-1 arobyn
105 neotest mrcjkb
106 nlua teto
107 nui.nvim mrcjkb
108 nvim-cmp https://github.com/hrsh7th/nvim-cmp
112 rapidjson https://github.com/xpol/lua-rapidjson.git
113 rocks.nvim 5.1 teto mrcjkb
114 rest.nvim 5.1 teto
115 rocks.nvim mrcjkb
116 rocks-git.nvim mrcjkb
117 rocks-config.nvim mrcjkb
118 rocks-dev.nvim mrcjkb
119 rustaceanvim mrcjkb
120 say https://github.com/Olivine-Labs/say.git
121 serpent lockejan

View file

@ -1,83 +0,0 @@
#! /usr/bin/env nix-shell
#! nix-shell -I nixpkgs=. -i bash -p delta jq perl
set -euo pipefail
shopt -s inherit_errexit
cat <<'EOF'
This script attempts to automatically convert option descriptions from
DocBook syntax to markdown. Naturally this process is incomplete and
imperfect, so any changes generated by this script MUST be reviewed.
Possible problems include: incorrectly replaced tags, badly formatted
markdown, DocBook tags this script doesn't recognize remaining in the
output and crashing the docs build, incorrect escaping of markdown
metacharacters, incorrect unescaping of XML entities—and the list goes on.
Always review the generated changes!
Some known limitations:
- Does not transform literalDocBook items
- Replacements can occur in non-option code, such as string literals
EOF
build-options-json() {
nix-build --no-out-link --expr '
let
sys = import ./nixos/default.nix {
configuration = {};
};
in
[
sys.config.system.build.manual.optionsJSON
]
'
}
git diff --quiet || {
echo "Worktree is dirty. Please stash or commit first."
exit 1
}
echo "Building options.json ..."
old_options=$(build-options-json)
echo "Applying replacements ..."
perl -pi -e '
BEGIN {
undef $/;
}
s,<literal>([^`]*?)</literal>,`$1`,smg;
s,<replaceable>([]*?)</replaceable>,«$1»,smg;
s,<filename>([^`]*?)</filename>,{file}`$1`,smg;
s,<option>([^`]*?)</option>,{option}`$1`,smg;
s,<code>([^`]*?)</code>,`$1`,smg;
s,<command>([^`]*?)</command>,{command}`$1`,smg;
s,<link xlink:href="(.+?)" ?/>,<$1>,smg;
s,<link xlink:href="(.+?)">(.*?)</link>,[$2]($1),smg;
s,<package>([^`]*?)</package>,`$1`,smg;
s,<emphasis>([^*]*?)</emphasis>,*$1*,smg;
s,<citerefentry>\s*
<refentrytitle>\s*(.*?)\s*</refentrytitle>\s*
<manvolnum>\s*(.*?)\s*</manvolnum>\s*
</citerefentry>,{manpage}`$1($2)`,smgx;
s,^( +description =),\1 lib.mdDoc,smg;
' "$@"
echo "Building options.json again ..."
new_options=$(build-options-json)
! cmp -s {$old_options,$new_options}/share/doc/nixos/options.json && {
diff -U10 \
<(jq . <$old_options/share/doc/nixos/options.json) \
<(jq . <$new_options/share/doc/nixos/options.json) \
| delta
}

View file

@ -559,7 +559,7 @@ with lib.maintainers; {
ericson2314 ericson2314
lovek323 lovek323
qyliss qyliss
raitobezarius RossComputerGuy
rrbutani rrbutani
sternenseemann sternenseemann
]; ];

View file

@ -21,8 +21,10 @@ You can tell NixOS in `configuration.nix` to run this unit automatically
at certain points in time, for instance, every night at 03:15: at certain points in time, for instance, every night at 03:15:
```nix ```nix
nix.gc.automatic = true; {
nix.gc.dates = "03:15"; nix.gc.automatic = true;
nix.gc.dates = "03:15";
}
``` ```
The commands above do not remove garbage collector roots, such as old The commands above do not remove garbage collector roots, such as old

View file

@ -26,9 +26,11 @@ host to rewrite container traffic to use your external IP address. This
can be accomplished using the following configuration on the host: can be accomplished using the following configuration on the host:
```nix ```nix
networking.nat.enable = true; {
networking.nat.internalInterfaces = ["ve-+"]; networking.nat.enable = true;
networking.nat.externalInterface = "eth0"; networking.nat.internalInterfaces = ["ve-+"];
networking.nat.externalInterface = "eth0";
}
``` ```
where `eth0` should be replaced with the desired external interface. where `eth0` should be replaced with the desired external interface.
@ -38,7 +40,9 @@ If you are using Network Manager, you need to explicitly prevent it from
managing container interfaces: managing container interfaces:
```nix ```nix
networking.networkmanager.unmanaged = [ "interface-name:ve-*" ]; {
networking.networkmanager.unmanaged = [ "interface-name:ve-*" ];
}
``` ```
You may need to restart your system for the changes to take effect. You may need to restart your system for the changes to take effect.

View file

@ -39,7 +39,9 @@ they were in the same cgroup, then the PostgreSQL process would get
`configuration.nix`: `configuration.nix`:
```nix ```nix
systemd.services.httpd.serviceConfig.CPUShares = 512; {
systemd.services.httpd.serviceConfig.CPUShares = 512;
}
``` ```
By default, every cgroup has 1024 CPU shares, so this will halve the CPU By default, every cgroup has 1024 CPU shares, so this will halve the CPU
@ -52,7 +54,9 @@ limits can be specified in `configuration.nix`; for instance, to limit
`httpd.service` to 512 MiB of RAM (excluding swap): `httpd.service` to 512 MiB of RAM (excluding swap):
```nix ```nix
systemd.services.httpd.serviceConfig.MemoryLimit = "512M"; {
systemd.services.httpd.serviceConfig.MemoryLimit = "512M";
}
``` ```
The command `systemd-cgtop` shows a continuously updated list of all The command `systemd-cgtop` shows a continuously updated list of all

View file

@ -5,13 +5,15 @@ You can also specify containers and their configuration in the host's
shall be a container named `database` running PostgreSQL: shall be a container named `database` running PostgreSQL:
```nix ```nix
containers.database = {
{ config = containers.database =
{ config, pkgs, ... }: { config =
{ services.postgresql.enable = true; { config, pkgs, ... }:
services.postgresql.package = pkgs.postgresql_14; { services.postgresql.enable = true;
}; services.postgresql.package = pkgs.postgresql_14;
}; };
};
}
``` ```
If you run `nixos-rebuild switch`, the container will be built. If the If you run `nixos-rebuild switch`, the container will be built. If the
@ -25,11 +27,13 @@ cannot change the network configuration. You can give a container its
own network as follows: own network as follows:
```nix ```nix
containers.database = { {
privateNetwork = true; containers.database = {
hostAddress = "192.168.100.10"; privateNetwork = true;
localAddress = "192.168.100.11"; hostAddress = "192.168.100.10";
}; localAddress = "192.168.100.11";
};
}
``` ```
This gives the container a private virtual Ethernet interface with IP This gives the container a private virtual Ethernet interface with IP

View file

@ -82,7 +82,9 @@ In order to enable a systemd *system* service with provided upstream
package, use (e.g): package, use (e.g):
```nix ```nix
systemd.packages = [ pkgs.packagekit ]; {
systemd.packages = [ pkgs.packagekit ];
}
``` ```
Usually NixOS modules written by the community do the above, plus take Usually NixOS modules written by the community do the above, plus take

View file

@ -7,7 +7,7 @@ However, it is possible and not-uncommon to create [impermanent systems], whose
`rootfs` is either a `tmpfs` or reset during boot. While NixOS itself supports `rootfs` is either a `tmpfs` or reset during boot. While NixOS itself supports
this kind of configuration, special care needs to be taken. this kind of configuration, special care needs to be taken.
[impermanent systems]: https://nixos.wiki/wiki/Impermanence [impermanent systems]: https://wiki.nixos.org/wiki/Impermanence
```{=include=} sections ```{=include=} sections

View file

@ -47,9 +47,9 @@ You can write a `let` wherever an expression is allowed. Thus, you also could ha
```nix ```nix
{ {
services.httpd.virtualHosts = services.httpd.virtualHosts =
let commonConfig = ...; in let commonConfig = { /* ... */ }; in
{ "blog.example.org" = (commonConfig // { ... }) { "blog.example.org" = (commonConfig // { /* ... */ });
"wiki.example.org" = (commonConfig // { ... }) "wiki.example.org" = (commonConfig // { /* ... */ });
}; };
} }
``` ```

View file

@ -6,8 +6,10 @@ is useful for doing network configuration not covered by the existing NixOS
modules. For instance, to statically configure an IPv6 address: modules. For instance, to statically configure an IPv6 address:
```nix ```nix
networking.localCommands = {
'' networking.localCommands =
ip -6 addr add 2001:610:685:1::1/64 dev eth0 ''
''; ip -6 addr add 2001:610:685:1::1/64 dev eth0
'';
}
``` ```

View file

@ -23,7 +23,9 @@ Then you write and test the package as described in the Nixpkgs manual.
Finally, you add it to [](#opt-environment.systemPackages), e.g. Finally, you add it to [](#opt-environment.systemPackages), e.g.
```nix ```nix
environment.systemPackages = [ pkgs.my-package ]; {
environment.systemPackages = [ pkgs.my-package ];
}
``` ```
and you run `nixos-rebuild`, specifying your own Nixpkgs tree: and you run `nixos-rebuild`, specifying your own Nixpkgs tree:
@ -38,24 +40,28 @@ tree. For instance, here is how you specify a build of the
`configuration.nix`: `configuration.nix`:
```nix ```nix
environment.systemPackages = {
let environment.systemPackages =
my-hello = with pkgs; stdenv.mkDerivation rec { let
name = "hello-2.8"; my-hello = with pkgs; stdenv.mkDerivation rec {
src = fetchurl { name = "hello-2.8";
url = "mirror://gnu/hello/${name}.tar.gz"; src = fetchurl {
hash = "sha256-5rd/gffPfa761Kn1tl3myunD8TuM+66oy1O7XqVGDXM="; url = "mirror://gnu/hello/${name}.tar.gz";
hash = "sha256-5rd/gffPfa761Kn1tl3myunD8TuM+66oy1O7XqVGDXM=";
};
}; };
}; in
in [ my-hello ];
[ my-hello ]; }
``` ```
Of course, you can also move the definition of `my-hello` into a Of course, you can also move the definition of `my-hello` into a
separate Nix expression, e.g. separate Nix expression, e.g.
```nix ```nix
environment.systemPackages = [ (import ./my-hello.nix) ]; {
environment.systemPackages = [ (import ./my-hello.nix) ];
}
``` ```
where `my-hello.nix` contains: where `my-hello.nix` contains:
@ -88,7 +94,9 @@ section](#module-services-flatpak). AppImages will not run "as-is" on NixOS.
First you need to install `appimage-run`: add to `/etc/nixos/configuration.nix` First you need to install `appimage-run`: add to `/etc/nixos/configuration.nix`
```nix ```nix
environment.systemPackages = [ pkgs.appimage-run ]; {
environment.systemPackages = [ pkgs.appimage-run ];
}
``` ```
Then instead of running the AppImage "as-is", run `appimage-run foo.appimage`. Then instead of running the AppImage "as-is", run `appimage-run foo.appimage`.

View file

@ -5,7 +5,7 @@ The NixOS configuration file generally looks like this:
```nix ```nix
{ config, pkgs, ... }: { config, pkgs, ... }:
{ option definitions { /* option definitions */
} }
``` ```
@ -80,7 +80,9 @@ Strings
: Strings are enclosed in double quotes, e.g. : Strings are enclosed in double quotes, e.g.
```nix ```nix
networking.hostName = "dexter"; {
networking.hostName = "dexter";
}
``` ```
Special characters can be escaped by prefixing them with a backslash Special characters can be escaped by prefixing them with a backslash
@ -89,11 +91,13 @@ Strings
Multi-line strings can be enclosed in *double single quotes*, e.g. Multi-line strings can be enclosed in *double single quotes*, e.g.
```nix ```nix
networking.extraHosts = {
'' networking.extraHosts =
127.0.0.2 other-localhost ''
10.0.0.1 server 127.0.0.2 other-localhost
''; 10.0.0.1 server
'';
}
``` ```
The main difference is that it strips from each line a number of The main difference is that it strips from each line a number of
@ -108,8 +112,10 @@ Booleans
: These can be `true` or `false`, e.g. : These can be `true` or `false`, e.g.
```nix ```nix
networking.firewall.enable = true; {
networking.firewall.allowPing = false; networking.firewall.enable = true;
networking.firewall.allowPing = false;
}
``` ```
Integers Integers
@ -117,7 +123,9 @@ Integers
: For example, : For example,
```nix ```nix
boot.kernel.sysctl."net.ipv4.tcp_keepalive_time" = 60; {
boot.kernel.sysctl."net.ipv4.tcp_keepalive_time" = 60;
}
``` ```
(Note that here the attribute name `net.ipv4.tcp_keepalive_time` is (Note that here the attribute name `net.ipv4.tcp_keepalive_time` is
@ -132,11 +140,13 @@ Sets
braces, as in the option definition braces, as in the option definition
```nix ```nix
fileSystems."/boot" = {
{ device = "/dev/sda1"; fileSystems."/boot" =
fsType = "ext4"; { device = "/dev/sda1";
options = [ "rw" "data=ordered" "relatime" ]; fsType = "ext4";
}; options = [ "rw" "data=ordered" "relatime" ];
};
}
``` ```
Lists Lists
@ -145,13 +155,17 @@ Lists
separated by whitespace, like this: separated by whitespace, like this:
```nix ```nix
boot.kernelModules = [ "fuse" "kvm-intel" "coretemp" ]; {
boot.kernelModules = [ "fuse" "kvm-intel" "coretemp" ];
}
``` ```
List elements can be any other type, e.g. sets: List elements can be any other type, e.g. sets:
```nix ```nix
swapDevices = [ { device = "/dev/disk/by-label/swap"; } ]; {
swapDevices = [ { device = "/dev/disk/by-label/swap"; } ];
}
``` ```
Packages Packages
@ -161,12 +175,14 @@ Packages
argument `pkgs`. Typical uses: argument `pkgs`. Typical uses:
```nix ```nix
environment.systemPackages = {
[ pkgs.thunderbird environment.systemPackages =
pkgs.emacs [ pkgs.thunderbird
]; pkgs.emacs
];
services.postgresql.package = pkgs.postgresql_14; services.postgresql.package = pkgs.postgresql_14;
}
``` ```
The latter option definition changes the default PostgreSQL package The latter option definition changes the default PostgreSQL package

View file

@ -16,18 +16,20 @@ Examples include:
You can use them like this: You can use them like this:
```nix ```nix
environment.systemPackages = with pkgs; [ {
sl environment.systemPackages = with pkgs; [
(pass.withExtensions (subpkgs: with subpkgs; [ sl
pass-audit (pass.withExtensions (subpkgs: with subpkgs; [
pass-otp pass-audit
pass-genphrase pass-otp
])) pass-genphrase
(python3.withPackages (subpkgs: with subpkgs; [ ]))
requests (python3.withPackages (subpkgs: with subpkgs; [
])) requests
cowsay ]))
]; cowsay
];
}
``` ```
::: :::
@ -38,7 +40,9 @@ dependency on GTK 2. If you want to build it against GTK 3, you can
specify that as follows: specify that as follows:
```nix ```nix
environment.systemPackages = [ (pkgs.emacs.override { gtk = pkgs.gtk3; }) ]; {
environment.systemPackages = [ (pkgs.emacs.override { gtk = pkgs.gtk3; }) ];
}
``` ```
The function `override` performs the call to the Nix function that The function `override` performs the call to the Nix function that
@ -58,12 +62,14 @@ of the package, such as the source code. For instance, if you want to
override the source code of Emacs, you can say: override the source code of Emacs, you can say:
```nix ```nix
environment.systemPackages = [ {
(pkgs.emacs.overrideAttrs (oldAttrs: { environment.systemPackages = [
name = "emacs-25.0-pre"; (pkgs.emacs.overrideAttrs (oldAttrs: {
src = /path/to/my/emacs/tree; name = "emacs-25.0-pre";
})) src = /path/to/my/emacs/tree;
]; }))
];
}
``` ```
Here, `overrideAttrs` takes the Nix derivation specified by `pkgs.emacs` Here, `overrideAttrs` takes the Nix derivation specified by `pkgs.emacs`
@ -80,9 +86,11 @@ two instances of the package. If you want to have everything depend on
your customised instance, you can apply a *global* override as follows: your customised instance, you can apply a *global* override as follows:
```nix ```nix
nixpkgs.config.packageOverrides = pkgs: {
{ emacs = pkgs.emacs.override { gtk = pkgs.gtk3; }; nixpkgs.config.packageOverrides = pkgs:
}; { emacs = pkgs.emacs.override { gtk = pkgs.gtk3; };
};
}
``` ```
The effect of this definition is essentially equivalent to modifying the The effect of this definition is essentially equivalent to modifying the

View file

@ -7,7 +7,9 @@ following line to `configuration.nix` enables the Mozilla Thunderbird
email application: email application:
```nix ```nix
environment.systemPackages = [ pkgs.thunderbird ]; {
environment.systemPackages = [ pkgs.thunderbird ];
}
``` ```
The effect of this specification is that the Thunderbird package from The effect of this specification is that the Thunderbird package from

View file

@ -6,10 +6,12 @@ Ext4 file system on device `/dev/disk/by-label/data` onto the mount
point `/data`: point `/data`:
```nix ```nix
fileSystems."/data" = {
{ device = "/dev/disk/by-label/data"; fileSystems."/data" =
fsType = "ext4"; { device = "/dev/disk/by-label/data";
}; fsType = "ext4";
};
}
``` ```
This will create an entry in `/etc/fstab`, which will generate a This will create an entry in `/etc/fstab`, which will generate a

View file

@ -5,14 +5,18 @@ and other unexpected packets. The firewall applies to both IPv4 and IPv6
traffic. It is enabled by default. It can be disabled as follows: traffic. It is enabled by default. It can be disabled as follows:
```nix ```nix
networking.firewall.enable = false; {
networking.firewall.enable = false;
}
``` ```
If the firewall is enabled, you can open specific TCP ports to the If the firewall is enabled, you can open specific TCP ports to the
outside world: outside world:
```nix ```nix
networking.firewall.allowedTCPPorts = [ 80 443 ]; {
networking.firewall.allowedTCPPorts = [ 80 443 ];
}
``` ```
Note that TCP port 22 (ssh) is opened automatically if the SSH daemon is Note that TCP port 22 (ssh) is opened automatically if the SSH daemon is
@ -22,10 +26,12 @@ enabled (`services.openssh.enable = true`). UDP ports can be opened through
To open ranges of TCP ports: To open ranges of TCP ports:
```nix ```nix
networking.firewall.allowedTCPPortRanges = [ {
{ from = 4000; to = 4007; } networking.firewall.allowedTCPPortRanges = [
{ from = 8000; to = 8010; } { from = 4000; to = 4007; }
]; { from = 8000; to = 8010; }
];
}
``` ```
Similarly, UDP port ranges can be opened through Similarly, UDP port ranges can be opened through

View file

@ -55,9 +55,11 @@ supported through the rocmPackages.clr.icd package. Adding this package to
enables OpenCL support: enables OpenCL support:
```nix ```nix
hardware.opengl.extraPackages = [ {
rocmPackages.clr.icd hardware.opengl.extraPackages = [
]; rocmPackages.clr.icd
];
}
``` ```
### Intel {#sec-gpu-accel-opencl-intel} ### Intel {#sec-gpu-accel-opencl-intel}
@ -74,9 +76,11 @@ to enable OpenCL support. For example, for Gen8 and later GPUs, the following
configuration can be used: configuration can be used:
```nix ```nix
hardware.opengl.extraPackages = [ {
intel-compute-runtime hardware.opengl.extraPackages = [
]; intel-compute-runtime
];
}
``` ```
## Vulkan {#sec-gpu-accel-vulkan} ## Vulkan {#sec-gpu-accel-vulkan}
@ -141,20 +145,22 @@ makes amdvlk the default driver and hides radv and lavapipe from the device list
A specific driver can be forced as follows: A specific driver can be forced as follows:
```nix ```nix
hardware.opengl.extraPackages = [ {
pkgs.amdvlk hardware.opengl.extraPackages = [
]; pkgs.amdvlk
];
# To enable Vulkan support for 32-bit applications, also add: # To enable Vulkan support for 32-bit applications, also add:
hardware.opengl.extraPackages32 = [ hardware.opengl.extraPackages32 = [
pkgs.driversi686Linux.amdvlk pkgs.driversi686Linux.amdvlk
]; ];
# Force radv # Force radv
environment.variables.AMD_VULKAN_ICD = "RADV"; environment.variables.AMD_VULKAN_ICD = "RADV";
# Or # Or
environment.variables.VK_ICD_FILENAMES = environment.variables.VK_ICD_FILENAMES =
"/run/opengl-driver/share/vulkan/icd.d/radeon_icd.x86_64.json"; "/run/opengl-driver/share/vulkan/icd.d/radeon_icd.x86_64.json";
}
``` ```
## VA-API {#sec-gpu-accel-va-api} ## VA-API {#sec-gpu-accel-va-api}
@ -178,17 +184,21 @@ $ nix-shell -p libva-utils --run vainfo
Modern Intel GPUs use the iHD driver, which can be installed with: Modern Intel GPUs use the iHD driver, which can be installed with:
```nix ```nix
hardware.opengl.extraPackages = [ {
intel-media-driver hardware.opengl.extraPackages = [
]; intel-media-driver
];
}
``` ```
Older Intel GPUs use the i965 driver, which can be installed with: Older Intel GPUs use the i965 driver, which can be installed with:
```nix ```nix
hardware.opengl.extraPackages = [ {
intel-vaapi-driver hardware.opengl.extraPackages = [
]; intel-vaapi-driver
];
}
``` ```
## Common issues {#sec-gpu-accel-common-issues} ## Common issues {#sec-gpu-accel-common-issues}

View file

@ -5,18 +5,22 @@ configure network interfaces. However, you can configure an interface
manually as follows: manually as follows:
```nix ```nix
networking.interfaces.eth0.ipv4.addresses = [ { {
address = "192.168.1.2"; networking.interfaces.eth0.ipv4.addresses = [ {
prefixLength = 24; address = "192.168.1.2";
} ]; prefixLength = 24;
} ];
}
``` ```
Typically you'll also want to set a default gateway and set of name Typically you'll also want to set a default gateway and set of name
servers: servers:
```nix ```nix
networking.defaultGateway = "192.168.1.1"; {
networking.nameservers = [ "8.8.8.8" ]; networking.defaultGateway = "192.168.1.1";
networking.nameservers = [ "8.8.8.8" ];
}
``` ```
::: {.note} ::: {.note}
@ -28,7 +32,9 @@ configuration is performed by `network-setup.service`.
The host name is set using [](#opt-networking.hostName): The host name is set using [](#opt-networking.hostName):
```nix ```nix
networking.hostName = "cartman"; {
networking.hostName = "cartman";
}
``` ```
The default host name is `nixos`. Set it to the empty string (`""`) to The default host name is `nixos`. Set it to the empty string (`""`) to

View file

@ -9,34 +9,42 @@ may be overridden on a per-interface basis by
IPv6 support globally by setting: IPv6 support globally by setting:
```nix ```nix
networking.enableIPv6 = false; {
networking.enableIPv6 = false;
}
``` ```
You can disable IPv6 on a single interface using a normal sysctl (in You can disable IPv6 on a single interface using a normal sysctl (in
this example, we use interface `eth0`): this example, we use interface `eth0`):
```nix ```nix
boot.kernel.sysctl."net.ipv6.conf.eth0.disable_ipv6" = true; {
boot.kernel.sysctl."net.ipv6.conf.eth0.disable_ipv6" = true;
}
``` ```
As with IPv4 networking interfaces are automatically configured via As with IPv4 networking interfaces are automatically configured via
DHCPv6. You can configure an interface manually: DHCPv6. You can configure an interface manually:
```nix ```nix
networking.interfaces.eth0.ipv6.addresses = [ { {
address = "fe00:aa:bb:cc::2"; networking.interfaces.eth0.ipv6.addresses = [ {
prefixLength = 64; address = "fe00:aa:bb:cc::2";
} ]; prefixLength = 64;
} ];
}
``` ```
For configuring a gateway, optionally with explicitly specified For configuring a gateway, optionally with explicitly specified
interface: interface:
```nix ```nix
networking.defaultGateway6 = { {
address = "fe00::1"; networking.defaultGateway6 = {
interface = "enp0s3"; address = "fe00::1";
}; interface = "enp0s3";
};
}
``` ```
See [](#sec-ipv4) for similar examples and additional information. See [](#sec-ipv4) for similar examples and additional information.

View file

@ -7,14 +7,16 @@ There are generally two ways of enabling Kubernetes on NixOS. One way is
to enable and configure cluster components appropriately by hand: to enable and configure cluster components appropriately by hand:
```nix ```nix
services.kubernetes = { {
apiserver.enable = true; services.kubernetes = {
controllerManager.enable = true; apiserver.enable = true;
scheduler.enable = true; controllerManager.enable = true;
addonManager.enable = true; scheduler.enable = true;
proxy.enable = true; addonManager.enable = true;
flannel.enable = true; proxy.enable = true;
}; flannel.enable = true;
};
}
``` ```
Another way is to assign cluster roles ("master" and/or "node") to Another way is to assign cluster roles ("master" and/or "node") to
@ -22,20 +24,26 @@ the host. This enables apiserver, controllerManager, scheduler,
addonManager, kube-proxy and etcd: addonManager, kube-proxy and etcd:
```nix ```nix
services.kubernetes.roles = [ "master" ]; {
services.kubernetes.roles = [ "master" ];
}
``` ```
While this will enable the kubelet and kube-proxy only: While this will enable the kubelet and kube-proxy only:
```nix ```nix
services.kubernetes.roles = [ "node" ]; {
services.kubernetes.roles = [ "node" ];
}
``` ```
Assigning both the master and node roles is usable if you want a single Assigning both the master and node roles is usable if you want a single
node Kubernetes cluster for dev or testing purposes: node Kubernetes cluster for dev or testing purposes:
```nix ```nix
services.kubernetes.roles = [ "master" "node" ]; {
services.kubernetes.roles = [ "master" "node" ];
}
``` ```
Note: Assigning either role will also default both Note: Assigning either role will also default both

View file

@ -5,7 +5,9 @@ option `boot.kernelPackages`. For instance, this selects the Linux 3.10
kernel: kernel:
```nix ```nix
boot.kernelPackages = pkgs.linuxKernel.packages.linux_3_10; {
boot.kernelPackages = pkgs.linuxKernel.packages.linux_3_10;
}
``` ```
Note that this not only replaces the kernel, but also packages that are Note that this not only replaces the kernel, but also packages that are
@ -40,13 +42,15 @@ If you want to change the kernel configuration, you can use the
instance, to enable support for the kernel debugger KGDB: instance, to enable support for the kernel debugger KGDB:
```nix ```nix
nixpkgs.config.packageOverrides = pkgs: pkgs.lib.recursiveUpdate pkgs { {
linuxKernel.kernels.linux_5_10 = pkgs.linuxKernel.kernels.linux_5_10.override { nixpkgs.config.packageOverrides = pkgs: pkgs.lib.recursiveUpdate pkgs {
extraConfig = '' linuxKernel.kernels.linux_5_10 = pkgs.linuxKernel.kernels.linux_5_10.override {
KGDB y extraConfig = ''
''; KGDB y
'';
};
}; };
}; }
``` ```
`extraConfig` takes a list of Linux kernel configuration options, one `extraConfig` takes a list of Linux kernel configuration options, one
@ -59,14 +63,18 @@ by `udev`. You can force a module to be loaded via
[](#opt-boot.kernelModules), e.g. [](#opt-boot.kernelModules), e.g.
```nix ```nix
boot.kernelModules = [ "fuse" "kvm-intel" "coretemp" ]; {
boot.kernelModules = [ "fuse" "kvm-intel" "coretemp" ];
}
``` ```
If the module is required early during the boot (e.g. to mount the root If the module is required early during the boot (e.g. to mount the root
file system), you can use [](#opt-boot.initrd.kernelModules): file system), you can use [](#opt-boot.initrd.kernelModules):
```nix ```nix
boot.initrd.kernelModules = [ "cifs" ]; {
boot.initrd.kernelModules = [ "cifs" ];
}
``` ```
This causes the specified modules and their dependencies to be added to This causes the specified modules and their dependencies to be added to
@ -76,7 +84,9 @@ Kernel runtime parameters can be set through
[](#opt-boot.kernel.sysctl), e.g. [](#opt-boot.kernel.sysctl), e.g.
```nix ```nix
boot.kernel.sysctl."net.ipv4.tcp_keepalive_time" = 120; {
boot.kernel.sysctl."net.ipv4.tcp_keepalive_time" = 120;
}
``` ```
sets the kernel's TCP keepalive time to 120 seconds. To see the sets the kernel's TCP keepalive time to 120 seconds. To see the
@ -89,7 +99,9 @@ Please refer to the Nixpkgs manual for the various ways of [building a custom ke
To use your custom kernel package in your NixOS configuration, set To use your custom kernel package in your NixOS configuration, set
```nix ```nix
boot.kernelPackages = pkgs.linuxPackagesFor yourCustomKernel; {
boot.kernelPackages = pkgs.linuxPackagesFor yourCustomKernel;
}
``` ```
## Rust {#sec-linux-rust} ## Rust {#sec-linux-rust}
@ -99,15 +111,17 @@ default. For kernel versions 6.7 or newer, experimental Rust support
can be enabled. In a NixOS configuration, set: can be enabled. In a NixOS configuration, set:
```nix ```nix
boot.kernelPatches = [ {
{ boot.kernelPatches = [
name = "Rust Support"; {
patch = null; name = "Rust Support";
features = { patch = null;
rust = true; features = {
}; rust = true;
} };
]; }
];
}
``` ```
## Developing kernel modules {#sec-linux-config-developing-modules} ## Developing kernel modules {#sec-linux-config-developing-modules}

View file

@ -29,15 +29,19 @@ system is automatically mounted at boot time as `/`, add the following
to `configuration.nix`: to `configuration.nix`:
```nix ```nix
boot.initrd.luks.devices.crypted.device = "/dev/disk/by-uuid/3f6b0024-3a44-4fde-a43a-767b872abe5d"; {
fileSystems."/".device = "/dev/mapper/crypted"; boot.initrd.luks.devices.crypted.device = "/dev/disk/by-uuid/3f6b0024-3a44-4fde-a43a-767b872abe5d";
fileSystems."/".device = "/dev/mapper/crypted";
}
``` ```
Should grub be used as bootloader, and `/boot` is located on an Should grub be used as bootloader, and `/boot` is located on an
encrypted partition, it is necessary to add the following grub option: encrypted partition, it is necessary to add the following grub option:
```nix ```nix
boot.loader.grub.enableCryptodisk = true; {
boot.loader.grub.enableCryptodisk = true;
}
``` ```
## FIDO2 {#sec-luks-file-systems-fido2} ## FIDO2 {#sec-luks-file-systems-fido2}
@ -68,8 +72,10 @@ To ensure that this file system is decrypted using the FIDO2 compatible
key, add the following to `configuration.nix`: key, add the following to `configuration.nix`:
```nix ```nix
boot.initrd.luks.fido2Support = true; {
boot.initrd.luks.devices."/dev/sda2".fido2.credential = "f1d00200108b9d6e849a8b388da457688e3dd653b4e53770012d8f28e5d3b269865038c346802f36f3da7278b13ad6a3bb6a1452e24ebeeaa24ba40eef559b1b287d2a2f80b7"; boot.initrd.luks.fido2Support = true;
boot.initrd.luks.devices."/dev/sda2".fido2.credential = "f1d00200108b9d6e849a8b388da457688e3dd653b4e53770012d8f28e5d3b269865038c346802f36f3da7278b13ad6a3bb6a1452e24ebeeaa24ba40eef559b1b287d2a2f80b7";
}
``` ```
You can also use the FIDO2 passwordless setup, but for security reasons, You can also use the FIDO2 passwordless setup, but for security reasons,
@ -77,7 +83,9 @@ you might want to enable it only when your device is PIN protected, such
as [Trezor](https://trezor.io/). as [Trezor](https://trezor.io/).
```nix ```nix
boot.initrd.luks.devices."/dev/sda2".fido2.passwordLess = true; {
boot.initrd.luks.devices."/dev/sda2".fido2.passwordLess = true;
}
``` ```
### systemd Stage 1 {#sec-luks-file-systems-fido2-systemd} ### systemd Stage 1 {#sec-luks-file-systems-fido2-systemd}
@ -88,13 +96,15 @@ unlocking the existing LUKS2 volume `root` using any enrolled FIDO2 compatible
tokens. tokens.
```nix ```nix
boot.initrd = { {
luks.devices.root = { boot.initrd = {
crypttabExtraOpts = [ "fido2-device=auto" ]; luks.devices.root = {
device = "/dev/sda2"; crypttabExtraOpts = [ "fido2-device=auto" ];
device = "/dev/sda2";
};
systemd.enable = true;
}; };
systemd.enable = true; }
};
``` ```
All tokens that should be used for unlocking the LUKS2-encrypted volume must All tokens that should be used for unlocking the LUKS2-encrypted volume must

View file

@ -16,7 +16,7 @@ including them from `configuration.nix`, e.g.:
{ imports = [ ./vpn.nix ./kde.nix ]; { imports = [ ./vpn.nix ./kde.nix ];
services.httpd.enable = true; services.httpd.enable = true;
environment.systemPackages = [ pkgs.emacs ]; environment.systemPackages = [ pkgs.emacs ];
... # ...
} }
``` ```
@ -42,7 +42,9 @@ merged last, so for list-type options, it will appear at the end of the
merged list. If you want it to appear first, you can use `mkBefore`: merged list. If you want it to appear first, you can use `mkBefore`:
```nix ```nix
boot.kernelModules = mkBefore [ "kvm-intel" ]; {
boot.kernelModules = mkBefore [ "kvm-intel" ];
}
``` ```
This causes the `kvm-intel` kernel module to be loaded before any other This causes the `kvm-intel` kernel module to be loaded before any other
@ -60,7 +62,9 @@ When that happens, it's possible to force one definition take precedence
over the others: over the others:
```nix ```nix
services.httpd.adminAddr = pkgs.lib.mkForce "bob@example.org"; {
services.httpd.adminAddr = pkgs.lib.mkForce "bob@example.org";
}
``` ```
When using multiple modules, you may need to access configuration values When using multiple modules, you may need to access configuration values

View file

@ -4,7 +4,9 @@ To facilitate network configuration, some desktop environments use
NetworkManager. You can enable NetworkManager by setting: NetworkManager. You can enable NetworkManager by setting:
```nix ```nix
networking.networkmanager.enable = true; {
networking.networkmanager.enable = true;
}
``` ```
some desktop managers (e.g., GNOME) enable NetworkManager automatically some desktop managers (e.g., GNOME) enable NetworkManager automatically
@ -14,7 +16,9 @@ All users that should have permission to change network settings must
belong to the `networkmanager` group: belong to the `networkmanager` group:
```nix ```nix
users.users.alice.extraGroups = [ "networkmanager" ]; {
users.users.alice.extraGroups = [ "networkmanager" ];
}
``` ```
NetworkManager is controlled using either `nmcli` or `nmtui` NetworkManager is controlled using either `nmcli` or `nmtui`
@ -32,9 +36,11 @@ can be used together if desired. To do this you need to instruct
NetworkManager to ignore those interfaces like: NetworkManager to ignore those interfaces like:
```nix ```nix
networking.networkmanager.unmanaged = [ {
"*" "except:type:wwan" "except:type:gsm" networking.networkmanager.unmanaged = [
]; "*" "except:type:wwan" "except:type:gsm"
];
}
``` ```
Refer to the option description for the exact syntax and references to Refer to the option description for the exact syntax and references to

View file

@ -4,21 +4,23 @@ NixOS offers a convenient abstraction to create both read-only as well writable
overlays. overlays.
```nix ```nix
fileSystems = { {
"/writable-overlay" = { fileSystems = {
overlay = { "/writable-overlay" = {
lowerdir = [ writableOverlayLowerdir ]; overlay = {
upperdir = "/.rw-writable-overlay/upper"; lowerdir = [ writableOverlayLowerdir ];
workdir = "/.rw-writable-overlay/work"; upperdir = "/.rw-writable-overlay/upper";
workdir = "/.rw-writable-overlay/work";
};
# Mount the writable overlay in the initrd.
neededForBoot = true;
}; };
# Mount the writable overlay in the initrd. "/readonly-overlay".overlay.lowerdir = [
neededForBoot = true; writableOverlayLowerdir
writableOverlayLowerdir2
];
}; };
"/readonly-overlay".overlay.lowerdir = [ }
writableOverlayLowerdir
writableOverlayLowerdir2
];
};
``` ```
If `upperdir` and `workdir` are not null, they will be created before the If `upperdir` and `workdir` are not null, they will be created before the

View file

@ -8,9 +8,11 @@ is to say, expected usage is to add them to the imports list of your
`/etc/configuration.nix` as such: `/etc/configuration.nix` as such:
```nix ```nix
imports = [ {
<nixpkgs/nixos/modules/profiles/profile-name.nix> imports = [
]; <nixpkgs/nixos/modules/profiles/profile-name.nix>
];
}
``` ```
Even if some of these profiles seem only useful in the context of Even if some of these profiles seem only useful in the context of

View file

@ -25,10 +25,12 @@ we assign the name `wan` to the interface with MAC address
`52:54:00:12:01:01` using a netword link unit: `52:54:00:12:01:01` using a netword link unit:
```nix ```nix
systemd.network.links."10-wan" = { {
matchConfig.PermanentMACAddress = "52:54:00:12:01:01"; systemd.network.links."10-wan" = {
linkConfig.Name = "wan"; matchConfig.PermanentMACAddress = "52:54:00:12:01:01";
}; linkConfig.Name = "wan";
};
}
``` ```
Note that links are directly read by udev, *not networkd*, and will work Note that links are directly read by udev, *not networkd*, and will work
@ -37,10 +39,12 @@ even if networkd is disabled.
Alternatively, we can use a plain old udev rule: Alternatively, we can use a plain old udev rule:
```nix ```nix
boot.initrd.services.udev.rules = '' {
SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", \ boot.initrd.services.udev.rules = ''
ATTR{address}=="52:54:00:12:01:01", KERNEL=="eth*", NAME="wan" SUBSYSTEM=="net", ACTION=="add", DRIVERS=="?*", \
''; ATTR{address}=="52:54:00:12:01:01", KERNEL=="eth*", NAME="wan"
'';
}
``` ```
::: {.warning} ::: {.warning}

View file

@ -3,7 +3,9 @@
Secure shell (SSH) access to your machine can be enabled by setting: Secure shell (SSH) access to your machine can be enabled by setting:
```nix ```nix
services.openssh.enable = true; {
services.openssh.enable = true;
}
``` ```
By default, root logins using a password are disallowed. They can be By default, root logins using a password are disallowed. They can be
@ -14,6 +16,8 @@ You can declaratively specify authorised RSA/DSA public keys for a user
as follows: as follows:
```nix ```nix
users.users.alice.openssh.authorizedKeys.keys = {
[ "ssh-dss AAAAB3NzaC1kc3MAAACBAPIkGWVEt4..." ]; users.users.alice.openssh.authorizedKeys.keys =
[ "ssh-dss AAAAB3NzaC1kc3MAAACBAPIkGWVEt4..." ];
}
``` ```

View file

@ -21,9 +21,11 @@ Apache HTTP, setting [](#opt-services.httpd.adminAddr)
appropriately: appropriately:
```nix ```nix
services.httpd.enable = true; {
services.httpd.adminAddr = ...; services.httpd.enable = true;
networking.firewall.allowedTCPPorts = [ 80 443 ]; services.httpd.adminAddr = "...";
networking.firewall.allowedTCPPorts = [ 80 443 ];
}
``` ```
For a simple Subversion server with basic authentication, configure the For a simple Subversion server with basic authentication, configure the
@ -34,25 +36,28 @@ the `.authz` file describing access permission, and `AuthUserFile` to
the password file. the password file.
```nix ```nix
services.httpd.extraModules = [ {
# note that order is *super* important here services.httpd.extraModules = [
{ name = "dav_svn"; path = "${pkgs.apacheHttpdPackages.subversion}/modules/mod_dav_svn.so"; } # note that order is *super* important here
{ name = "authz_svn"; path = "${pkgs.apacheHttpdPackages.subversion}/modules/mod_authz_svn.so"; } { name = "dav_svn"; path = "${pkgs.apacheHttpdPackages.subversion}/modules/mod_dav_svn.so"; }
]; { name = "authz_svn"; path = "${pkgs.apacheHttpdPackages.subversion}/modules/mod_authz_svn.so"; }
services.httpd.virtualHosts = { ];
"svn" = { services.httpd.virtualHosts = {
hostName = HOSTNAME; "svn" = {
documentRoot = DOCUMENTROOT; hostName = HOSTNAME;
locations."/svn".extraConfig = '' documentRoot = DOCUMENTROOT;
DAV svn locations."/svn".extraConfig = ''
SVNParentPath REPO_PARENT DAV svn
AuthzSVNAccessFile ACCESS_FILE SVNParentPath REPO_PARENT
AuthName "SVN Repositories" AuthzSVNAccessFile ACCESS_FILE
AuthType Basic AuthName "SVN Repositories"
AuthUserFile PASSWORD_FILE AuthType Basic
Require valid-user AuthUserFile PASSWORD_FILE
''; Require valid-user
} '';
};
};
}
``` ```
The key `"svn"` is just a symbolic name identifying the virtual host. The key `"svn"` is just a symbolic name identifying the virtual host.
@ -90,7 +95,7 @@ $ htpasswd -s PASSWORD_FILE USER_NAME
The file describing access permissions `ACCESS_FILE` will look something The file describing access permissions `ACCESS_FILE` will look something
like the following: like the following:
```nix ```
[/] [/]
* = r * = r

View file

@ -6,13 +6,15 @@ management. In the declarative style, users are specified in
account named `alice` shall exist: account named `alice` shall exist:
```nix ```nix
users.users.alice = { {
isNormalUser = true; users.users.alice = {
home = "/home/alice"; isNormalUser = true;
description = "Alice Foobar"; home = "/home/alice";
extraGroups = [ "wheel" "networkmanager" ]; description = "Alice Foobar";
openssh.authorizedKeys.keys = [ "ssh-dss AAAAB3Nza... alice@foobar" ]; extraGroups = [ "wheel" "networkmanager" ];
}; openssh.authorizedKeys.keys = [ "ssh-dss AAAAB3Nza... alice@foobar" ];
};
}
``` ```
Note that `alice` is a member of the `wheel` and `networkmanager` Note that `alice` is a member of the `wheel` and `networkmanager`
@ -38,7 +40,9 @@ A user ID (uid) is assigned automatically. You can also specify a uid
manually by adding manually by adding
```nix ```nix
uid = 1000; {
uid = 1000;
}
``` ```
to the user specification. to the user specification.
@ -47,7 +51,9 @@ Groups can be specified similarly. The following states that a group
named `students` shall exist: named `students` shall exist:
```nix ```nix
users.groups.students.gid = 1000; {
users.groups.students.gid = 1000;
}
``` ```
As with users, the group ID (gid) is optional and will be assigned As with users, the group ID (gid) is optional and will be assigned
@ -100,7 +106,9 @@ Instead of using a custom perl script to create users and groups, you can use
systemd-sysusers: systemd-sysusers:
```nix ```nix
systemd.sysusers.enable = true; {
systemd.sysusers.enable = true;
}
``` ```
The primary benefit of this is to remove a dependency on perl. The primary benefit of this is to remove a dependency on perl.

View file

@ -9,7 +9,9 @@ a Wayland Compositor such as sway without separately enabling a Wayland
server: server:
```nix ```nix
{
programs.sway.enable = true; programs.sway.enable = true;
}
``` ```
This installs the sway compositor along with some essential utilities. This installs the sway compositor along with some essential utilities.
@ -19,7 +21,9 @@ If you are using a wlroots-based compositor, like sway, and want to be
able to share your screen, you might want to activate this option: able to share your screen, you might want to activate this option:
```nix ```nix
xdg.portal.wlr.enable = true; {
xdg.portal.wlr.enable = true;
}
``` ```
and configure Pipewire using and configure Pipewire using

View file

@ -7,25 +7,29 @@ skip the rest of this section on wireless networks.
NixOS will start wpa_supplicant for you if you enable this setting: NixOS will start wpa_supplicant for you if you enable this setting:
```nix ```nix
networking.wireless.enable = true; {
networking.wireless.enable = true;
}
``` ```
NixOS lets you specify networks for wpa_supplicant declaratively: NixOS lets you specify networks for wpa_supplicant declaratively:
```nix ```nix
networking.wireless.networks = { {
echelon = { # SSID with no spaces or special characters networking.wireless.networks = {
psk = "abcdefgh"; echelon = { # SSID with no spaces or special characters
psk = "abcdefgh";
};
"echelon's AP" = { # SSID with spaces and/or special characters
psk = "ijklmnop";
};
echelon = { # Hidden SSID
hidden = true;
psk = "qrstuvwx";
};
free.wifi = {}; # Public wireless network
}; };
"echelon's AP" = { # SSID with spaces and/or special characters }
psk = "ijklmnop";
};
echelon = { # Hidden SSID
hidden = true;
psk = "qrstuvwx";
};
free.wifi = {}; # Public wireless network
};
``` ```
Be aware that keys will be written to the nix store in plaintext! When Be aware that keys will be written to the nix store in plaintext! When
@ -46,11 +50,13 @@ network={
``` ```
```nix ```nix
networking.wireless.networks = { {
echelon = { networking.wireless.networks = {
pskRaw = "dca6d6ed41f4ab5a984c9f55f6f66d4efdc720ebf66959810f4329bb391c5435"; echelon = {
pskRaw = "dca6d6ed41f4ab5a984c9f55f6f66d4efdc720ebf66959810f4329bb391c5435";
};
}; };
}; }
``` ```
or you can use it to directly generate the `wpa_supplicant.conf`: or you can use it to directly generate the `wpa_supplicant.conf`:

View file

@ -4,7 +4,9 @@ The X Window System (X11) provides the basis of NixOS' graphical user
interface. It can be enabled as follows: interface. It can be enabled as follows:
```nix ```nix
services.xserver.enable = true; {
services.xserver.enable = true;
}
``` ```
The X server will automatically detect and use the appropriate video The X server will automatically detect and use the appropriate video
@ -12,7 +14,9 @@ driver from a set of X.org drivers (such as `vesa` and `intel`). You can
also specify a driver manually, e.g. also specify a driver manually, e.g.
```nix ```nix
services.xserver.videoDrivers = [ "r128" ]; {
services.xserver.videoDrivers = [ "r128" ];
}
``` ```
to enable X.org's `xf86-video-r128` driver. to enable X.org's `xf86-video-r128` driver.
@ -22,15 +26,17 @@ Otherwise, you can only log into a plain undecorated `xterm` window.
Thus you should pick one or more of the following lines: Thus you should pick one or more of the following lines:
```nix ```nix
services.xserver.desktopManager.plasma5.enable = true; {
services.xserver.desktopManager.xfce.enable = true; services.xserver.desktopManager.plasma5.enable = true;
services.xserver.desktopManager.gnome.enable = true; services.xserver.desktopManager.xfce.enable = true;
services.xserver.desktopManager.mate.enable = true; services.xserver.desktopManager.gnome.enable = true;
services.xserver.windowManager.xmonad.enable = true; services.xserver.desktopManager.mate.enable = true;
services.xserver.windowManager.twm.enable = true; services.xserver.windowManager.xmonad.enable = true;
services.xserver.windowManager.icewm.enable = true; services.xserver.windowManager.twm.enable = true;
services.xserver.windowManager.i3.enable = true; services.xserver.windowManager.icewm.enable = true;
services.xserver.windowManager.herbstluftwm.enable = true; services.xserver.windowManager.i3.enable = true;
services.xserver.windowManager.herbstluftwm.enable = true;
}
``` ```
NixOS's default *display manager* (the program that provides a graphical NixOS's default *display manager* (the program that provides a graphical
@ -38,22 +44,28 @@ login prompt and manages the X server) is LightDM. You can select an
alternative one by picking one of the following lines: alternative one by picking one of the following lines:
```nix ```nix
services.xserver.displayManager.sddm.enable = true; {
services.xserver.displayManager.gdm.enable = true; services.xserver.displayManager.sddm.enable = true;
services.xserver.displayManager.gdm.enable = true;
}
``` ```
You can set the keyboard layout (and optionally the layout variant): You can set the keyboard layout (and optionally the layout variant):
```nix ```nix
services.xserver.xkb.layout = "de"; {
services.xserver.xkb.variant = "neo"; services.xserver.xkb.layout = "de";
services.xserver.xkb.variant = "neo";
}
``` ```
The X server is started automatically at boot time. If you don't want The X server is started automatically at boot time. If you don't want
this to happen, you can set: this to happen, you can set:
```nix ```nix
services.xserver.autorun = false; {
services.xserver.autorun = false;
}
``` ```
The X server can then be started manually: The X server can then be started manually:
@ -66,7 +78,9 @@ On 64-bit systems, if you want OpenGL for 32-bit programs such as in
Wine, you should also set the following: Wine, you should also set the following:
```nix ```nix
hardware.opengl.driSupport32Bit = true; {
hardware.opengl.driSupport32Bit = true;
}
``` ```
## Auto-login {#sec-x11-auto-login} ## Auto-login {#sec-x11-auto-login}
@ -84,16 +98,20 @@ desktop environment. If you wanted no desktop environment and i3 as your
your window manager, you'd define: your window manager, you'd define:
```nix ```nix
services.xserver.displayManager.defaultSession = "none+i3"; {
services.xserver.displayManager.defaultSession = "none+i3";
}
``` ```
Every display manager in NixOS supports auto-login, here is an example Every display manager in NixOS supports auto-login, here is an example
using lightdm for a user `alice`: using lightdm for a user `alice`:
```nix ```nix
services.xserver.displayManager.lightdm.enable = true; {
services.xserver.displayManager.autoLogin.enable = true; services.xserver.displayManager.lightdm.enable = true;
services.xserver.displayManager.autoLogin.user = "alice"; services.xserver.displayManager.autoLogin.enable = true;
services.xserver.displayManager.autoLogin.user = "alice";
}
``` ```
## Intel Graphics drivers {#sec-x11--graphics-cards-intel} ## Intel Graphics drivers {#sec-x11--graphics-cards-intel}
@ -119,18 +137,22 @@ drivers. Use the option
to set one. The recommended configuration for modern systems is: to set one. The recommended configuration for modern systems is:
```nix ```nix
services.xserver.videoDrivers = [ "modesetting" ]; {
services.xserver.videoDrivers = [ "modesetting" ];
}
``` ```
If you experience screen tearing no matter what, this configuration was If you experience screen tearing no matter what, this configuration was
reported to resolve the issue: reported to resolve the issue:
```nix ```nix
services.xserver.videoDrivers = [ "intel" ]; {
services.xserver.deviceSection = '' services.xserver.videoDrivers = [ "intel" ];
Option "DRI" "2" services.xserver.deviceSection = ''
Option "TearFree" "true" Option "DRI" "2"
''; Option "TearFree" "true"
'';
}
``` ```
Note that this will likely downgrade the performance compared to Note that this will likely downgrade the performance compared to
@ -143,15 +165,19 @@ better 3D performance than the X.org drivers. It is not enabled by
default because it's not free software. You can enable it as follows: default because it's not free software. You can enable it as follows:
```nix ```nix
services.xserver.videoDrivers = [ "nvidia" ]; {
services.xserver.videoDrivers = [ "nvidia" ];
}
``` ```
If you have an older card, you may have to use one of the legacy drivers: If you have an older card, you may have to use one of the legacy drivers:
```nix ```nix
hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.legacy_470; {
hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.legacy_390; hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.legacy_470;
hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.legacy_340; hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.legacy_390;
hardware.nvidia.package = config.boot.kernelPackages.nvidiaPackages.legacy_340;
}
``` ```
You may need to reboot after enabling this driver to prevent a clash You may need to reboot after enabling this driver to prevent a clash
@ -166,7 +192,9 @@ performance. If you still want to use it anyway, you need to explicitly
set: set:
```nix ```nix
services.xserver.videoDrivers = [ "amdgpu-pro" ]; {
services.xserver.videoDrivers = [ "amdgpu-pro" ];
}
``` ```
You will need to reboot after enabling this driver to prevent a clash You will need to reboot after enabling this driver to prevent a clash
@ -178,14 +206,18 @@ Support for Synaptics touchpads (found in many laptops such as the Dell
Latitude series) can be enabled as follows: Latitude series) can be enabled as follows:
```nix ```nix
services.xserver.libinput.enable = true; {
services.xserver.libinput.enable = true;
}
``` ```
The driver has many options (see [](#ch-options)). The driver has many options (see [](#ch-options)).
For instance, the following disables tap-to-click behavior: For instance, the following disables tap-to-click behavior:
```nix ```nix
services.xserver.libinput.touchpad.tapping = false; {
services.xserver.libinput.touchpad.tapping = false;
}
``` ```
Note: the use of `services.xserver.synaptics` is deprecated since NixOS Note: the use of `services.xserver.synaptics` is deprecated since NixOS
@ -198,9 +230,11 @@ GTK themes can be installed either to user profile or system-wide (via
GTK ones, you can use the following configuration: GTK ones, you can use the following configuration:
```nix ```nix
qt.enable = true; {
qt.platformTheme = "gtk2"; qt.enable = true;
qt.style = "gtk2"; qt.platformTheme = "gtk2";
qt.style = "gtk2";
}
``` ```
## Custom XKB layouts {#custom-xkb-layouts} ## Custom XKB layouts {#custom-xkb-layouts}
@ -217,7 +251,7 @@ Create a file called `us-greek` with the following content (under a
directory called `symbols`; it's an XKB peculiarity that will help with directory called `symbols`; it's an XKB peculiarity that will help with
testing): testing):
```nix ```
xkb_symbols "us-greek" xkb_symbols "us-greek"
{ {
include "us(basic)" // includes the base US keys include "us(basic)" // includes the base US keys
@ -234,11 +268,13 @@ xkb_symbols "us-greek"
A minimal layout specification must include the following: A minimal layout specification must include the following:
```nix ```nix
services.xserver.xkb.extraLayouts.us-greek = { {
description = "US layout with alt-gr greek"; services.xserver.xkb.extraLayouts.us-greek = {
languages = [ "eng" ]; description = "US layout with alt-gr greek";
symbolsFile = /yourpath/symbols/us-greek; languages = [ "eng" ];
}; symbolsFile = /yourpath/symbols/us-greek;
};
}
``` ```
::: {.note} ::: {.note}
@ -275,7 +311,7 @@ Use the *xev* utility from `pkgs.xorg.xev` to find the codes of the keys
of interest, then create a `media-key` file to hold the keycodes of interest, then create a `media-key` file to hold the keycodes
definitions definitions
```nix ```
xkb_keycodes "media" xkb_keycodes "media"
{ {
<volUp> = 123; <volUp> = 123;
@ -285,7 +321,7 @@ xkb_keycodes "media"
Now use the newly define keycodes in `media-sym`: Now use the newly define keycodes in `media-sym`:
```nix ```
xkb_symbols "media" xkb_symbols "media"
{ {
key.type = "ONE_LEVEL"; key.type = "ONE_LEVEL";
@ -297,12 +333,14 @@ xkb_symbols "media"
As before, to install the layout do As before, to install the layout do
```nix ```nix
services.xserver.xkb.extraLayouts.media = { {
description = "Multimedia keys remapping"; services.xserver.xkb.extraLayouts.media = {
languages = [ "eng" ]; description = "Multimedia keys remapping";
symbolsFile = /path/to/media-key; languages = [ "eng" ];
keycodesFile = /path/to/media-sym; symbolsFile = /path/to/media-key;
}; keycodesFile = /path/to/media-sym;
};
}
``` ```
::: {.note} ::: {.note}
@ -318,7 +356,9 @@ workaround, you can set the keymap using `setxkbmap` at the start of the
session with: session with:
```nix ```nix
services.xserver.displayManager.sessionCommands = "setxkbmap -keycodes media"; {
services.xserver.displayManager.sessionCommands = "setxkbmap -keycodes media";
}
``` ```
If you are manually starting the X server, you should set the argument If you are manually starting the X server, you should set the argument

View file

@ -3,21 +3,25 @@
To enable the Xfce Desktop Environment, set To enable the Xfce Desktop Environment, set
```nix ```nix
services.xserver.desktopManager.xfce.enable = true; {
services.xserver.displayManager.defaultSession = "xfce"; services.xserver.desktopManager.xfce.enable = true;
services.xserver.displayManager.defaultSession = "xfce";
}
``` ```
Optionally, *picom* can be enabled for nice graphical effects, some Optionally, *picom* can be enabled for nice graphical effects, some
example settings: example settings:
```nix ```nix
services.picom = { {
enable = true; services.picom = {
fade = true; enable = true;
inactiveOpacity = 0.9; fade = true;
shadow = true; inactiveOpacity = 0.9;
fadeDelta = 4; shadow = true;
}; fadeDelta = 4;
};
}
``` ```
Some Xfce programs are not installed automatically. To install them Some Xfce programs are not installed automatically. To install them

View file

@ -9,12 +9,20 @@
, prefix ? ../../.. , prefix ? ../../..
}: }:
with pkgs;
let let
inherit (lib) hasPrefix removePrefix; inherit (pkgs) buildPackages runCommand docbook_xsl_ns;
lib = pkgs.lib; inherit (pkgs.lib)
hasPrefix
removePrefix
flip
foldr
types
mkOption
escapeShellArg
concatMapStringsSep
sourceFilesBySuffices
;
common = import ./common.nix; common = import ./common.nix;
@ -27,7 +35,7 @@ let
# E.g. if some `options` came from modules in ${pkgs.customModules}/nix, # E.g. if some `options` came from modules in ${pkgs.customModules}/nix,
# you'd need to include `extraSources = [ pkgs.customModules ]` # you'd need to include `extraSources = [ pkgs.customModules ]`
prefixesToStrip = map (p: "${toString p}/") ([ prefix ] ++ extraSources); prefixesToStrip = map (p: "${toString p}/") ([ prefix ] ++ extraSources);
stripAnyPrefixes = lib.flip (lib.foldr lib.removePrefix) prefixesToStrip; stripAnyPrefixes = flip (foldr removePrefix) prefixesToStrip;
optionsDoc = buildPackages.nixosOptionsDoc { optionsDoc = buildPackages.nixosOptionsDoc {
inherit options revision baseOptionsJSON warningsAreErrors; inherit options revision baseOptionsJSON warningsAreErrors;
@ -42,8 +50,8 @@ let
testOptionsDoc = let testOptionsDoc = let
eval = nixos-lib.evalTest { eval = nixos-lib.evalTest {
# Avoid evaluating a NixOS config prototype. # Avoid evaluating a NixOS config prototype.
config.node.type = lib.types.deferredModule; config.node.type = types.deferredModule;
options._module.args = lib.mkOption { internal = true; }; options._module.args = mkOption { internal = true; };
}; };
in buildPackages.nixosOptionsDoc { in buildPackages.nixosOptionsDoc {
inherit (eval) options; inherit (eval) options;
@ -76,7 +84,7 @@ let
substituteInPlace ./configuration/configuration.md \ substituteInPlace ./configuration/configuration.md \
--replace \ --replace \
'@MODULE_CHAPTERS@' \ '@MODULE_CHAPTERS@' \
${lib.escapeShellArg (lib.concatMapStringsSep "\n" (p: "${p.value}") config.meta.doc)} ${escapeShellArg (concatMapStringsSep "\n" (p: "${p.value}") config.meta.doc)}
substituteInPlace ./nixos-options.md \ substituteInPlace ./nixos-options.md \
--replace \ --replace \
'@NIXOS_OPTIONS_JSON@' \ '@NIXOS_OPTIONS_JSON@' \
@ -95,7 +103,7 @@ in rec {
# Generate the NixOS manual. # Generate the NixOS manual.
manualHTML = runCommand "nixos-manual-html" manualHTML = runCommand "nixos-manual-html"
{ nativeBuildInputs = [ buildPackages.nixos-render-docs ]; { nativeBuildInputs = [ buildPackages.nixos-render-docs ];
inputs = lib.sourceFilesBySuffices ./. [ ".md" ]; inputs = sourceFilesBySuffices ./. [ ".md" ];
meta.description = "The NixOS manual in HTML format"; meta.description = "The NixOS manual in HTML format";
allowedReferences = ["out"]; allowedReferences = ["out"];
} }
@ -114,8 +122,8 @@ in rec {
nixos-render-docs -j $NIX_BUILD_CORES manual html \ nixos-render-docs -j $NIX_BUILD_CORES manual html \
--manpage-urls ${manpageUrls} \ --manpage-urls ${manpageUrls} \
--revision ${lib.escapeShellArg revision} \ --revision ${escapeShellArg revision} \
--generator "nixos-render-docs ${lib.version}" \ --generator "nixos-render-docs ${pkgs.lib.version}" \
--stylesheet style.css \ --stylesheet style.css \
--stylesheet highlightjs/mono-blue.css \ --stylesheet highlightjs/mono-blue.css \
--script ./highlightjs/highlight.pack.js \ --script ./highlightjs/highlight.pack.js \
@ -147,7 +155,7 @@ in rec {
xml:id="book-nixos-manual"> xml:id="book-nixos-manual">
<info> <info>
<title>NixOS Manual</title> <title>NixOS Manual</title>
<subtitle>Version ${lib.version}</subtitle> <subtitle>Version ${pkgs.lib.version}</subtitle>
</info> </info>
<chapter> <chapter>
<title>Temporarily unavailable</title> <title>Temporarily unavailable</title>
@ -199,7 +207,7 @@ in rec {
# Generate manpages. # Generate manpages.
mkdir -p $out/share/man/man5 mkdir -p $out/share/man/man5
nixos-render-docs -j $NIX_BUILD_CORES options manpage \ nixos-render-docs -j $NIX_BUILD_CORES options manpage \
--revision ${lib.escapeShellArg revision} \ --revision ${escapeShellArg revision} \
${optionsJSON}/${common.outputPath}/options.json \ ${optionsJSON}/${common.outputPath}/options.json \
$out/share/man/man5/configuration.nix.5 $out/share/man/man5/configuration.nix.5
''; '';

View file

@ -17,13 +17,15 @@ activation script will take these dependencies into account and order the
snippets accordingly. As a simple example: snippets accordingly. As a simple example:
```nix ```nix
system.activationScripts.my-activation-script = { {
deps = [ "etc" ]; system.activationScripts.my-activation-script = {
# supportsDryActivation = true; deps = [ "etc" ];
text = '' # supportsDryActivation = true;
echo "Hallo i bims" text = ''
''; echo "Hallo i bims"
}; '';
};
}
``` ```
This example creates an activation script snippet that is run after the `etc` This example creates an activation script snippet that is run after the `etc`

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