Merge commit '17bbfcccd316c29f20e366f838304011f8866805' into wip/yesman

wip/yesman
Katharina Fey 3 years ago
commit 9b013c3998
Signed by: kookie
GPG Key ID: 90734A9E619C8A6C
  1. 21
      infra/libkookie/nixpkgs/.github/CODEOWNERS
  2. 151
      infra/libkookie/nixpkgs/.github/labeler.yml
  3. 29
      infra/libkookie/nixpkgs/.github/workflows/direct-push.yml
  4. 29
      infra/libkookie/nixpkgs/.github/workflows/editorconfig.yml
  5. 19
      infra/libkookie/nixpkgs/.github/workflows/labels.yml
  6. 6
      infra/libkookie/nixpkgs/.github/workflows/manual-nixos.yml
  7. 6
      infra/libkookie/nixpkgs/.github/workflows/manual-nixpkgs.yml
  8. 2
      infra/libkookie/nixpkgs/doc/Makefile
  9. 12
      infra/libkookie/nixpkgs/doc/README.md
  10. 6
      infra/libkookie/nixpkgs/doc/builders/fetchers.chapter.md
  11. 6
      infra/libkookie/nixpkgs/doc/builders/images.xml
  12. 48
      infra/libkookie/nixpkgs/doc/builders/images/appimagetools.section.md
  13. 102
      infra/libkookie/nixpkgs/doc/builders/images/appimagetools.xml
  14. 38
      infra/libkookie/nixpkgs/doc/builders/images/dockertools.section.md
  15. 37
      infra/libkookie/nixpkgs/doc/builders/images/ocitools.section.md
  16. 61
      infra/libkookie/nixpkgs/doc/builders/images/ocitools.xml
  17. 28
      infra/libkookie/nixpkgs/doc/builders/images/snap/example-firefox.nix
  18. 12
      infra/libkookie/nixpkgs/doc/builders/images/snap/example-hello.nix
  19. 71
      infra/libkookie/nixpkgs/doc/builders/images/snaptools.section.md
  20. 59
      infra/libkookie/nixpkgs/doc/builders/images/snaptools.xml
  21. 35
      infra/libkookie/nixpkgs/doc/builders/packages/cataclysm-dda.section.md
  22. 32
      infra/libkookie/nixpkgs/doc/builders/packages/citrix.section.md
  23. 46
      infra/libkookie/nixpkgs/doc/builders/packages/citrix.xml
  24. 13
      infra/libkookie/nixpkgs/doc/builders/packages/dlib.section.md
  25. 24
      infra/libkookie/nixpkgs/doc/builders/packages/dlib.xml
  26. 2
      infra/libkookie/nixpkgs/doc/builders/packages/emacs.section.md
  27. 45
      infra/libkookie/nixpkgs/doc/builders/packages/fuse.section.md
  28. 38
      infra/libkookie/nixpkgs/doc/builders/packages/ibus.section.md
  29. 57
      infra/libkookie/nixpkgs/doc/builders/packages/ibus.xml
  30. 7
      infra/libkookie/nixpkgs/doc/builders/packages/index.xml
  31. 585
      infra/libkookie/nixpkgs/doc/contributing/coding-conventions.chapter.md
  32. 949
      infra/libkookie/nixpkgs/doc/contributing/coding-conventions.xml
  33. 24
      infra/libkookie/nixpkgs/doc/contributing/contributing-to-documentation.chapter.md
  34. 30
      infra/libkookie/nixpkgs/doc/contributing/contributing-to-documentation.xml
  35. 77
      infra/libkookie/nixpkgs/doc/contributing/quick-start.chapter.md
  36. 152
      infra/libkookie/nixpkgs/doc/contributing/quick-start.xml
  37. 204
      infra/libkookie/nixpkgs/doc/contributing/reviewing-contributions.chapter.md
  38. 488
      infra/libkookie/nixpkgs/doc/contributing/reviewing-contributions.xml
  39. 67
      infra/libkookie/nixpkgs/doc/contributing/submitting-changes.chapter.md
  40. 45
      infra/libkookie/nixpkgs/doc/contributing/vulnerability-roundup.chapter.md
  41. 8
      infra/libkookie/nixpkgs/doc/functions/library/attrsets.xml
  42. 113
      infra/libkookie/nixpkgs/doc/languages-frameworks/agda.section.md
  43. 10
      infra/libkookie/nixpkgs/doc/languages-frameworks/android.section.md
  44. 217
      infra/libkookie/nixpkgs/doc/languages-frameworks/beam.section.md
  45. 6
      infra/libkookie/nixpkgs/doc/languages-frameworks/coq.section.md
  46. 8
      infra/libkookie/nixpkgs/doc/languages-frameworks/dotnet.section.md
  47. 18
      infra/libkookie/nixpkgs/doc/languages-frameworks/idris.section.md
  48. 4
      infra/libkookie/nixpkgs/doc/languages-frameworks/lua.section.md
  49. 96
      infra/libkookie/nixpkgs/doc/languages-frameworks/python.section.md
  50. 8
      infra/libkookie/nixpkgs/doc/languages-frameworks/qt.section.md
  51. 2
      infra/libkookie/nixpkgs/doc/languages-frameworks/ruby.section.md
  52. 75
      infra/libkookie/nixpkgs/doc/languages-frameworks/rust.section.md
  53. 46
      infra/libkookie/nixpkgs/doc/languages-frameworks/vim.section.md
  54. 15
      infra/libkookie/nixpkgs/doc/manual.xml
  55. 4
      infra/libkookie/nixpkgs/doc/stdenv/cross-compilation.chapter.md
  56. 194
      infra/libkookie/nixpkgs/doc/stdenv/meta.chapter.md
  57. 349
      infra/libkookie/nixpkgs/doc/stdenv/meta.xml
  58. 128
      infra/libkookie/nixpkgs/doc/stdenv/multiple-output.chapter.md
  59. 262
      infra/libkookie/nixpkgs/doc/stdenv/multiple-output.xml
  60. 1215
      infra/libkookie/nixpkgs/doc/stdenv/stdenv.chapter.md
  61. 2423
      infra/libkookie/nixpkgs/doc/stdenv/stdenv.xml
  62. 2
      infra/libkookie/nixpkgs/doc/using/configuration.xml
  63. 256
      infra/libkookie/nixpkgs/doc/using/overlays.xml
  64. 8
      infra/libkookie/nixpkgs/lib/customisation.nix
  65. 5
      infra/libkookie/nixpkgs/lib/default.nix
  66. 24
      infra/libkookie/nixpkgs/lib/generators.nix
  67. 10
      infra/libkookie/nixpkgs/lib/licenses.nix
  68. 31
      infra/libkookie/nixpkgs/lib/modules.nix
  69. 13
      infra/libkookie/nixpkgs/lib/sources.nix
  70. 6
      infra/libkookie/nixpkgs/lib/strings.nix
  71. 18
      infra/libkookie/nixpkgs/lib/systems/default.nix
  72. 60
      infra/libkookie/nixpkgs/lib/systems/doubles.nix
  73. 24
      infra/libkookie/nixpkgs/lib/systems/examples.nix
  74. 9
      infra/libkookie/nixpkgs/lib/systems/parse.nix
  75. 6
      infra/libkookie/nixpkgs/lib/systems/platforms.nix
  76. 5
      infra/libkookie/nixpkgs/lib/tests/modules.sh
  77. 4
      infra/libkookie/nixpkgs/lib/tests/modules/declare-submoduleWith-modules.nix
  78. 6
      infra/libkookie/nixpkgs/lib/tests/systems.nix
  79. 5
      infra/libkookie/nixpkgs/lib/trivial.nix
  80. 21
      infra/libkookie/nixpkgs/lib/types.nix
  81. 695
      infra/libkookie/nixpkgs/maintainers/maintainer-list.nix
  82. 1
      infra/libkookie/nixpkgs/maintainers/scripts/luarocks-packages.csv
  83. 2
      infra/libkookie/nixpkgs/maintainers/scripts/nix-generate-from-cpan.nix
  84. 537
      infra/libkookie/nixpkgs/maintainers/scripts/pluginupdate.py
  85. 35
      infra/libkookie/nixpkgs/maintainers/team-list.nix
  86. 2
      infra/libkookie/nixpkgs/nixos/doc/manual/Makefile
  87. 6
      infra/libkookie/nixpkgs/nixos/doc/manual/configuration/luks-file-systems.xml
  88. 2
      infra/libkookie/nixpkgs/nixos/doc/manual/configuration/modularity.xml
  89. 59
      infra/libkookie/nixpkgs/nixos/doc/manual/configuration/x-windows.xml
  90. 14
      infra/libkookie/nixpkgs/nixos/doc/manual/development/settings-options.xml
  91. 3
      infra/libkookie/nixpkgs/nixos/doc/manual/development/writing-documentation.xml
  92. 33
      infra/libkookie/nixpkgs/nixos/doc/manual/development/writing-nixos-tests.xml
  93. 2
      infra/libkookie/nixpkgs/nixos/doc/manual/installation/installing.xml
  94. 8
      infra/libkookie/nixpkgs/nixos/doc/manual/release-notes/rl-2009.xml
  95. 295
      infra/libkookie/nixpkgs/nixos/doc/manual/release-notes/rl-2105.xml
  96. 78
      infra/libkookie/nixpkgs/nixos/lib/make-disk-image.nix
  97. 26
      infra/libkookie/nixpkgs/nixos/lib/make-options-doc/default.nix
  98. 4
      infra/libkookie/nixpkgs/nixos/lib/qemu-flags.nix
  99. 82
      infra/libkookie/nixpkgs/nixos/lib/test-driver/test-driver.py
  100. 22
      infra/libkookie/nixpkgs/nixos/lib/testing-python.nix
  101. Some files were not shown because too many files have changed in this diff Show More

@ -11,7 +11,7 @@
/.github/CODEOWNERS @edolstra
# GitHub actions
/.github/workflows @Mic92 @zowoq
/.github/workflows @NixOS/Security @Mic92 @zowoq
/.github/workflows/merge-staging @FRidh
# EditorConfig
@ -79,11 +79,11 @@
/pkgs/development/tools/poetry2nix @adisbladis
# Haskell
/pkgs/development/compilers/ghc @cdepillabout
/pkgs/development/haskell-modules @cdepillabout
/pkgs/development/haskell-modules/default.nix @cdepillabout
/pkgs/development/haskell-modules/generic-builder.nix @cdepillabout
/pkgs/development/haskell-modules/hoogle.nix @cdepillabout
/pkgs/development/compilers/ghc @cdepillabout @sternenseemann
/pkgs/development/haskell-modules @cdepillabout @sternenseemann
/pkgs/development/haskell-modules/default.nix @cdepillabout @sternenseemann
/pkgs/development/haskell-modules/generic-builder.nix @cdepillabout @sternenseemann
/pkgs/development/haskell-modules/hoogle.nix @cdepillabout @sternenseemann
# Perl
/pkgs/development/interpreters/perl @volth @stigtsp
@ -95,8 +95,8 @@
/pkgs/development/r-modules @peti
# Ruby
/pkgs/development/interpreters/ruby @alyssais
/pkgs/development/ruby-modules @alyssais
/pkgs/development/interpreters/ruby @marsam
/pkgs/development/ruby-modules @marsam
# Rust
/pkgs/development/compilers/rust @Mic92 @LnL7 @zowoq
@ -126,9 +126,6 @@
# Jetbrains
/pkgs/applications/editors/jetbrains @edwtjo
# Eclipse
/pkgs/applications/editors/eclipse @rycee
# Licenses
/lib/licenses.nix @alyssais
@ -139,7 +136,7 @@
/pkgs/development/libraries/qt-5 @ttuegel
# PostgreSQL and related stuff
/pkgs/servers/sql/postgresql @thoughtpolice
/pkgs/servers/sql/postgresql @thoughtpolice @marsam
/nixos/modules/services/databases/postgresql.xml @thoughtpolice
/nixos/modules/services/databases/postgresql.nix @thoughtpolice
/nixos/tests/postgresql.nix @thoughtpolice

@ -0,0 +1,151 @@
"6.topic: agda":
- doc/languages-frameworks/agda.section.md
- nixos/tests/agda.nix
- pkgs/build-support/agda/**/*
- pkgs/development/libraries/agda/**/*
- pkgs/top-level/agda-packages.nix
"6.topic: bsd":
- pkgs/os-specific/bsd/**/*
- pkgs/stdenv/freebsd/**/*
"6.topic: cinnamon":
- pkgs/desktops/cinnamon/**/*
"6.topic: emacs":
- nixos/modules/services/editors/emacs.nix
- nixos/modules/services/editors/emacs.xml
- nixos/tests/emacs-daemon.nix
- pkgs/applications/editors/emacs-modes/**/*
- pkgs/applications/editors/emacs/**/*
- pkgs/build-support/emacs/**/*
- pkgs/top-level/emacs-packages.nix
"6.topic: erlang":
- doc/languages-frameworks/beam.section.md
- pkgs/development/beam-modules/**/*
- pkgs/development/interpreters/elixir/**/*
- pkgs/development/interpreters/erlang/**/*
- pkgs/development/tools/build-managers/rebar/**/*
- pkgs/development/tools/build-managers/rebar3/**/*
- pkgs/development/tools/erlang/**/*
- pkgs/top-level/beam-packages.nix
"6.topic: fetch":
- pkgs/build-support/fetch*/**/*
"6.topic: GNOME":
- doc/languages-frameworks/gnome.section.md
- nixos/modules/services/desktops/gnome3/**/*
- nixos/modules/services/x11/desktop-managers/gnome3.nix
- nixos/tests/gnome3-xorg.nix
- nixos/tests/gnome3.nix
- pkgs/desktops/gnome-3/**/*
"6.topic: golang":
- doc/languages-frameworks/go.section.md
- pkgs/development/compilers/go/**/*
- pkgs/development/go-modules/**/*
- pkgs/development/go-packages/**/*
"6.topic: haskell":
- doc/languages-frameworks/haskell.section.md
- pkgs/development/compilers/ghc/**/*
- pkgs/development/haskell-modules/**/*
- pkgs/development/tools/haskell/**/*
- pkgs/top-level/haskell-packages.nix
"6.topic: kernel":
- pkgs/build-support/kernel/**/*
- pkgs/os-specific/linux/kernel/**/*
"6.topic: lua":
- pkgs/development/interpreters/lua-5/**/*
- pkgs/development/interpreters/luajit/**/*
- pkgs/development/lua-modules/**/*
- pkgs/top-level/lua-packages.nix
"6.topic: nixos":
- nixos/**/*
"6.topic: ocaml":
- doc/languages-frameworks/ocaml.section.md
- pkgs/development/compilers/ocaml/**/*
- pkgs/development/compilers/reason/**/*
- pkgs/development/ocaml-modules/**/*
- pkgs/development/tools/ocaml/**/*
- pkgs/top-level/ocaml-packages.nix
"6.topic: pantheon":
- nixos/modules/services/desktops/pantheon/**/*
- nixos/modules/services/x11/desktop-managers/pantheon.nix
- nixos/modules/services/x11/display-managers/lightdm-greeters/pantheon.nix
- nixos/tests/pantheon.nix
- pkgs/desktops/pantheon/**/*
"6.topic: policy discussion":
- .github/**/*
"6.topic: printing":
- nixos/modules/services/printing/cupsd.nix
- pkgs/misc/cups/**/*
"6.topic: python":
- doc/languages-frameworks/python.section.md
- pkgs/development/interpreters/python/**/*
- pkgs/development/python-modules/**/*
- pkgs/top-level/python-packages.nix
"6.topic: qt/kde":
- doc/languages-frameworks/qt.section.md
- nixos/modules/services/x11/desktop-managers/plasma5.nix
- nixos/tests/plasma5.nix
- pkgs/applications/kde/**/*
- pkgs/desktops/plasma-5/**/*
- pkgs/development/libraries/kde-frameworks/**/*
- pkgs/development/libraries/qt-5/**/*
"6.topic: ruby":
- doc/languages-frameworks/ruby.section.md
- pkgs/development/interpreters/ruby/**/*
- pkgs/development/ruby-modules/**/*
"6.topic: rust":
- doc/languages-frameworks/rust.section.md
- pkgs/build-support/rust/**/*
- pkgs/development/compilers/rust/**/*
"6.topic: stdenv":
- pkgs/stdenv/**/*
"6.topic: steam":
- pkgs/games/steam/**/*
"6.topic: systemd":
- pkgs/os-specific/linux/systemd/**/*
- nixos/modules/system/boot/systemd*/**/*
"6.topic: TeX":
- doc/languages-frameworks/texlive.section.md
- pkgs/tools/typesetting/tex/**/*
"6.topic: vim":
- doc/languages-frameworks/vim.section.md
- pkgs/applications/editors/vim/**/*
- pkgs/misc/vim-plugins/**/*
"6.topic: xfce":
- nixos/doc/manual/configuration/xfce.xml
- nixos/modules/services/x11/desktop-managers/xfce.nix
- nixos/tests/xfce.nix
- pkgs/desktops/xfce/**/*
"8.has: changelog":
- nixos/doc/manual/release-notes/**/*
"8.has: documentation":
- doc/**/*
- nixos/doc/**/*
"8.has: module (update)":
- nixos/modules/**/*

@ -0,0 +1,29 @@
name: "Direct Push Warning"
on:
push:
branches:
- master
- release-**
jobs:
build:
runs-on: ubuntu-latest
if: github.repository_owner == 'NixOS'
env:
GITHUB_SHA: ${{ github.sha }}
GITHUB_REPOSITORY: ${{ github.repository }}
steps:
- name: Check if commit is a merge commit
id: ismerge
run: |
ISMERGE=$(curl -H 'Accept: application/vnd.github.groot-preview+json' -H "authorization: Bearer ${{ secrets.GITHUB_TOKEN }}" https://api.github.com/repos/${{ env.GITHUB_REPOSITORY }}/commits/${{ env.GITHUB_SHA }}/pulls | jq -r '.[] | select(.merge_commit_sha == "${{ env.GITHUB_SHA }}") | any')
echo "::set-output name=ismerge::$ISMERGE"
- name: Warn if the commit was a direct push
if: steps.ismerge.outputs.ismerge != 'true'
uses: peter-evans/commit-comment@v1
with:
body: |
@${{ github.actor }}, you pushed a commit directly to master/release branch
instead of going through a Pull Request.
That's highly discouraged beyond the few exceptions listed
on https://github.com/NixOS/nixpkgs/issues/118661

@ -1,7 +1,10 @@
name: "Checking EditorConfig"
permissions: read-all
on:
pull_request:
# avoids approving first time contributors
pull_request_target:
branches-ignore:
- 'release-**'
@ -21,17 +24,23 @@ jobs:
>> $GITHUB_ENV
echo 'EOF' >> $GITHUB_ENV
- uses: actions/checkout@v2
with:
# pull_request_target checks out the base branch by default
ref: refs/pull/${{ github.event.pull_request.number }}/merge
if: env.PR_DIFF
- name: Fetch editorconfig-checker
- uses: cachix/install-nix-action@v13
if: env.PR_DIFF
with:
# nixpkgs commit is pinned so that it doesn't break
nix_path: nixpkgs=https://github.com/NixOS/nixpkgs/archive/f93ecc4f6bc60414d8b73dbdf615ceb6a2c604df.tar.gz
- name: install editorconfig-checker
run: nix-env -iA editorconfig-checker -f '<nixpkgs>'
if: env.PR_DIFF
env:
ECC_VERSION: "2.3.1"
ECC_URL: "https://github.com/editorconfig-checker/editorconfig-checker/releases/download"
run: |
curl -sSf -O -L -C - "$ECC_URL/$ECC_VERSION/ec-linux-amd64.tar.gz" && \
tar xzf ec-linux-amd64.tar.gz && \
mv ./bin/ec-linux-amd64 ./bin/editorconfig-checker
- name: Checking EditorConfig
if: env.PR_DIFF
run: |
echo "$PR_DIFF" | xargs ./bin/editorconfig-checker -disable-indent-size
echo "$PR_DIFF" | xargs editorconfig-checker -disable-indent-size
- if: ${{ failure() }}
run: |
echo "::error :: Hey! It looks like your changes don't follow our editorconfig settings. Read https://editorconfig.org/#download to configure your editor so you never see this error again."

@ -0,0 +1,19 @@
name: "Label PR"
on:
pull_request_target:
types: [edited, opened, synchronize, reopened]
permissions:
contents: read
pull-requests: write
jobs:
labels:
runs-on: ubuntu-latest
if: github.repository_owner == 'NixOS'
steps:
- uses: actions/labeler@v3
with:
repo-token: ${{ secrets.GITHUB_TOKEN }}
sync-labels: true

@ -1,5 +1,7 @@
name: "Build NixOS manual"
permissions: read-all
on:
pull_request_target:
branches:
@ -15,11 +17,11 @@ jobs:
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@v12
- uses: cachix/install-nix-action@v13
with:
# explicitly enable sandbox
extra_nix_config: sandbox = true
- uses: cachix/cachix-action@v8
- uses: cachix/cachix-action@v9
with:
# This cache is for the nixos/nixpkgs manual builds and should not be trusted or used elsewhere.
name: nixpkgs-ci

@ -1,5 +1,7 @@
name: "Build Nixpkgs manual"
permissions: read-all
on:
pull_request_target:
branches:
@ -15,11 +17,11 @@ jobs:
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@v12
- uses: cachix/install-nix-action@v13
with:
# explicitly enable sandbox
extra_nix_config: sandbox = true
- uses: cachix/cachix-action@v8
- uses: cachix/cachix-action@v9
with:
# This cache is for the nixos/nixpkgs manual builds and should not be trusted or used elsewhere.
name: nixpkgs-ci

@ -1,4 +1,4 @@
MD_TARGETS=$(addsuffix .xml, $(basename $(shell find . -type f -regex '.*\.md$$')))
MD_TARGETS=$(addsuffix .xml, $(basename $(shell find . -type f -regex '.*\.md$$' -not -name README.md)))
.PHONY: all
all: validate format out/html/index.html out/epub/manual.epub

@ -0,0 +1,12 @@
# Nixpkgs/doc
This directory houses the sources files for the Nixpkgs manual.
You can find the [rendered documentation for Nixpkgs `unstable` on nixos.org](https://nixos.org/manual/nixpkgs/unstable/).
[Docs for Nixpkgs stable](https://nixos.org/manual/nixpkgs/stable/) are also available.
If you want to contribute to the documentation, [here's how to do it](https://nixos.org/manual/nixpkgs/unstable/#chap-contributing).
If you're only getting started with Nix, go to [nixos.org/learn](https://nixos.org/learn).

@ -18,7 +18,7 @@ stdenv.mkDerivation {
The main difference between `fetchurl` and `fetchzip` is in how they store the contents. `fetchurl` will store the unaltered contents of the URL within the Nix store. `fetchzip` on the other hand will decompress the archive for you, making files and directories directly accessible in the future. `fetchzip` can only be used with archives. Despite the name, `fetchzip` is not limited to .zip files and can also be used with any tarball.
`fetchpatch` works very similarly to `fetchurl` with the same arguments expected. It expects patch files as a source and and performs normalization on them before computing the checksum. For example it will remove comments or other unstable parts that are sometimes added by version control systems and can change over time.
`fetchpatch` works very similarly to `fetchurl` with the same arguments expected. It expects patch files as a source and performs normalization on them before computing the checksum. For example it will remove comments or other unstable parts that are sometimes added by version control systems and can change over time.
Other fetcher functions allow you to add source code directly from a VCS such as subversion or git. These are mostly straightforward nambes based on the name of the command used with the VCS system. Because they give you a working repository, they act most like `fetchzip`.
@ -72,3 +72,7 @@ This is used with Savannah repositories. The arguments expected are very similar
## `fetchFromRepoOrCz`
This is used with repo.or.cz repositories. The arguments expected are very similar to fetchFromGitHub above.
## `fetchFromSourcehut`
This is used with sourcehut repositories. The arguments expected are very similar to fetchFromGitHub above. Don't forget the tilde (~) in front of the user name!

@ -5,8 +5,8 @@
<para>
This chapter describes tools for creating various types of images.
</para>
<xi:include href="images/appimagetools.xml" />
<xi:include href="images/appimagetools.section.xml" />
<xi:include href="images/dockertools.section.xml" />
<xi:include href="images/ocitools.xml" />
<xi:include href="images/snaptools.xml" />
<xi:include href="images/ocitools.section.xml" />
<xi:include href="images/snaptools.section.xml" />
</chapter>

@ -0,0 +1,48 @@
# pkgs.appimageTools {#sec-pkgs-appimageTools}
`pkgs.appimageTools` is a set of functions for extracting and wrapping [AppImage](https://appimage.org/) files. They are meant to be used if traditional packaging from source is infeasible, or it would take too long. To quickly run an AppImage file, `pkgs.appimage-run` can be used as well.
::: warning
The `appimageTools` API is unstable and may be subject to backwards-incompatible changes in the future.
:::
## AppImage formats {#ssec-pkgs-appimageTools-formats}
There are different formats for AppImages, see [the specification](https://github.com/AppImage/AppImageSpec/blob/74ad9ca2f94bf864a4a0dac1f369dd4f00bd1c28/draft.md#image-format) for details.
- Type 1 images are ISO 9660 files that are also ELF executables.
- Type 2 images are ELF executables with an appended filesystem.
They can be told apart with `file -k`:
```ShellSession
$ file -k type1.AppImage
type1.AppImage: ELF 64-bit LSB executable, x86-64, version 1 (SYSV) ISO 9660 CD-ROM filesystem data 'AppImage' (Lepton 3.x), scale 0-0,
spot sensor temperature 0.000000, unit celsius, color scheme 0, calibration: offset 0.000000, slope 0.000000, dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.18, BuildID[sha1]=d629f6099d2344ad82818172add1d38c5e11bc6d, stripped\012- data
$ file -k type2.AppImage
type2.AppImage: ELF 64-bit LSB executable, x86-64, version 1 (SYSV) (Lepton 3.x), scale 232-60668, spot sensor temperature -4.187500, color scheme 15, show scale bar, calibration: offset -0.000000, slope 0.000000 (Lepton 2.x), scale 4111-45000, spot sensor temperature 412442.250000, color scheme 3, minimum point enabled, calibration: offset -75402534979642766821519867692934234112.000000, slope 5815371847733706829839455140374904832.000000, dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.18, BuildID[sha1]=79dcc4e55a61c293c5e19edbd8d65b202842579f, stripped\012- data
```
Note how the type 1 AppImage is described as an `ISO 9660 CD-ROM filesystem`, and the type 2 AppImage is not.
## Wrapping {#ssec-pkgs-appimageTools-wrapping}
Depending on the type of AppImage you're wrapping, you'll have to use `wrapType1` or `wrapType2`.
```nix
appimageTools.wrapType2 { # or wrapType1
name = "patchwork";
src = fetchurl {
url = "https://github.com/ssbc/patchwork/releases/download/v3.11.4/Patchwork-3.11.4-linux-x86_64.AppImage";
sha256 = "1blsprpkvm0ws9b96gb36f0rbf8f5jgmw4x6dsb1kswr4ysf591s";
};
extraPkgs = pkgs: with pkgs; [ ];
}
```
- `name` specifies the name of the resulting image.
- `src` specifies the AppImage file to extract.
- `extraPkgs` allows you to pass a function to include additional packages inside the FHS environment your AppImage is going to run in. There are a few ways to learn which dependencies an application needs:
- Looking through the extracted AppImage files, reading its scripts and running `patchelf` and `ldd` on its executables. This can also be done in `appimage-run`, by setting `APPIMAGE_DEBUG_EXEC=bash`.
- Running `strace -vfefile` on the wrapped executable, looking for libraries that can't be found.

@ -1,102 +0,0 @@
<section xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xi="http://www.w3.org/2001/XInclude"
xml:id="sec-pkgs-appimageTools">
<title>pkgs.appimageTools</title>
<para>
<varname>pkgs.appimageTools</varname> is a set of functions for extracting and wrapping <link xlink:href="https://appimage.org/">AppImage</link> files. They are meant to be used if traditional packaging from source is infeasible, or it would take too long. To quickly run an AppImage file, <literal>pkgs.appimage-run</literal> can be used as well.
</para>
<warning>
<para>
The <varname>appimageTools</varname> API is unstable and may be subject to backwards-incompatible changes in the future.
</para>
</warning>
<section xml:id="ssec-pkgs-appimageTools-formats">
<title>AppImage formats</title>
<para>
There are different formats for AppImages, see <link xlink:href="https://github.com/AppImage/AppImageSpec/blob/74ad9ca2f94bf864a4a0dac1f369dd4f00bd1c28/draft.md#image-format">the specification</link> for details.
</para>
<itemizedlist>
<listitem>
<para>
Type 1 images are ISO 9660 files that are also ELF executables.
</para>
</listitem>
<listitem>
<para>
Type 2 images are ELF executables with an appended filesystem.
</para>
</listitem>
</itemizedlist>
<para>
They can be told apart with <command>file -k</command>:
</para>
<screen>
<prompt>$ </prompt>file -k type1.AppImage
type1.AppImage: ELF 64-bit LSB executable, x86-64, version 1 (SYSV) ISO 9660 CD-ROM filesystem data 'AppImage' (Lepton 3.x), scale 0-0,
spot sensor temperature 0.000000, unit celsius, color scheme 0, calibration: offset 0.000000, slope 0.000000, dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.18, BuildID[sha1]=d629f6099d2344ad82818172add1d38c5e11bc6d, stripped\012- data
<prompt>$ </prompt>file -k type2.AppImage
type2.AppImage: ELF 64-bit LSB executable, x86-64, version 1 (SYSV) (Lepton 3.x), scale 232-60668, spot sensor temperature -4.187500, color scheme 15, show scale bar, calibration: offset -0.000000, slope 0.000000 (Lepton 2.x), scale 4111-45000, spot sensor temperature 412442.250000, color scheme 3, minimum point enabled, calibration: offset -75402534979642766821519867692934234112.000000, slope 5815371847733706829839455140374904832.000000, dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.18, BuildID[sha1]=79dcc4e55a61c293c5e19edbd8d65b202842579f, stripped\012- data
</screen>
<para>
Note how the type 1 AppImage is described as an <literal>ISO 9660 CD-ROM filesystem</literal>, and the type 2 AppImage is not.
</para>
</section>
<section xml:id="ssec-pkgs-appimageTools-wrapping">
<title>Wrapping</title>
<para>
Depending on the type of AppImage you're wrapping, you'll have to use <varname>wrapType1</varname> or <varname>wrapType2</varname>.
</para>
<programlisting>
appimageTools.wrapType2 { # or wrapType1
name = "patchwork"; <co xml:id='ex-appimageTools-wrapping-1' />
src = fetchurl { <co xml:id='ex-appimageTools-wrapping-2' />
url = "https://github.com/ssbc/patchwork/releases/download/v3.11.4/Patchwork-3.11.4-linux-x86_64.AppImage";
sha256 = "1blsprpkvm0ws9b96gb36f0rbf8f5jgmw4x6dsb1kswr4ysf591s";
};
extraPkgs = pkgs: with pkgs; [ ]; <co xml:id='ex-appimageTools-wrapping-3' />
}</programlisting>
<calloutlist>
<callout arearefs='ex-appimageTools-wrapping-1'>
<para>
<varname>name</varname> specifies the name of the resulting image.
</para>
</callout>
<callout arearefs='ex-appimageTools-wrapping-2'>
<para>
<varname>src</varname> specifies the AppImage file to extract.
</para>
</callout>
<callout arearefs='ex-appimageTools-wrapping-3'>
<para>
<varname>extraPkgs</varname> allows you to pass a function to include additional packages inside the FHS environment your AppImage is going to run in. There are a few ways to learn which dependencies an application needs:
<itemizedlist>
<listitem>
<para>
Looking through the extracted AppImage files, reading its scripts and running <command>patchelf</command> and <command>ldd</command> on its executables. This can also be done in <command>appimage-run</command>, by setting <command>APPIMAGE_DEBUG_EXEC=bash</command>.
</para>
</listitem>
<listitem>
<para>
Running <command>strace -vfefile</command> on the wrapped executable, looking for libraries that can't be found.
</para>
</listitem>
</itemizedlist>
</para>
</callout>
</calloutlist>
</section>
</section>

@ -38,15 +38,15 @@ The above example will build a Docker image `redis/latest` from the given base i
- `name` specifies the name of the resulting image. This is the only required argument for `buildImage`.
- `tag` specifies the tag of the resulting image. By default it\'s `null`, which indicates that the nix output hash will be used as tag.
- `tag` specifies the tag of the resulting image. By default it's `null`, which indicates that the nix output hash will be used as tag.
- `fromImage` is the repository tarball containing the base image. It must be a valid Docker image, such as exported by `docker save`. By default it\'s `null`, which can be seen as equivalent to `FROM scratch` of a `Dockerfile`.
- `fromImage` is the repository tarball containing the base image. It must be a valid Docker image, such as exported by `docker save`. By default it's `null`, which can be seen as equivalent to `FROM scratch` of a `Dockerfile`.
- `fromImageName` can be used to further specify the base image within the repository, in case it contains multiple images. By default it\'s `null`, in which case `buildImage` will peek the first image available in the repository.
- `fromImageName` can be used to further specify the base image within the repository, in case it contains multiple images. By default it's `null`, in which case `buildImage` will peek the first image available in the repository.
- `fromImageTag` can be used to further specify the tag of the base image within the repository, in case an image contains multiple tags. By default it\'s `null`, in which case `buildImage` will peek the first tag available for the base image.
- `fromImageTag` can be used to further specify the tag of the base image within the repository, in case an image contains multiple tags. By default it's `null`, in which case `buildImage` will peek the first tag available for the base image.
- `contents` is a derivation that will be copied in the new layer of the resulting image. This can be similarly seen as `ADD contents/ /` in a `Dockerfile`. By default it\'s `null`.
- `contents` is a derivation that will be copied in the new layer of the resulting image. This can be similarly seen as `ADD contents/ /` in a `Dockerfile`. By default it's `null`.
- `runAsRoot` is a bash script that will run as root in an environment that overlays the existing layers of the base image with the new resulting layer, including the previously copied `contents` derivation. This can be similarly seen as `RUN ...` in a `Dockerfile`.
@ -109,7 +109,13 @@ Create a Docker image with many of the store paths being on their own layer to i
: Tag of the generated image.
*Default:* the output path\'s hash
*Default:* the output path's hash
`fromImage` _optional_
: The repository tarball containing the base image. It must be a valid Docker image, such as one exported by `docker save`.
*Default:* `null`, which can be seen as equivalent to `FROM scratch` of a `Dockerfile`.
`contents` _optional_
@ -139,7 +145,11 @@ Create a Docker image with many of the store paths being on their own layer to i
`extraCommands` _optional_
: Shell commands to run while building the final layer, without access to most of the layer contents. Changes to this layer are \"on top\" of all the other layers, so can create additional directories and files.
: Shell commands to run while building the final layer, without access to most of the layer contents. Changes to this layer are "on top" of all the other layers, so can create additional directories and files.
`fakeRootCommands` _optional_
: Shell commands to run while creating the archive for the final layer in a fakeroot environment. Unlike `extraCommands`, you can run `chown` to change the owners of the files in the archive, changing fakeroot's state instead of the real filesystem. The latter would require privileges that the build user does not have. Static binaries do not interact with the fakeroot environment. By default all files in the archive will be owned by root.
### Behavior of `contents` in the final image {#dockerTools-buildLayeredImage-arg-contents}
@ -183,9 +193,9 @@ Modern Docker installations support up to 128 layers, however older versions sup
If the produced image will not be extended by other Docker builds, it is safe to set `maxLayers` to `128`. However it will be impossible to extend the image further.
The first (`maxLayers-2`) most \"popular\" paths will have their own individual layers, then layer \#`maxLayers-1` will contain all the remaining \"unpopular\" paths, and finally layer \#`maxLayers` will contain the Image configuration.
The first (`maxLayers-2`) most "popular" paths will have their own individual layers, then layer \#`maxLayers-1` will contain all the remaining "unpopular" paths, and finally layer \#`maxLayers` will contain the Image configuration.
Docker\'s Layers are not inherently ordered, they are content-addressable and are not explicitly layered until they are composed in to an Image.
Docker's Layers are not inherently ordered, they are content-addressable and are not explicitly layered until they are composed in to an Image.
## streamLayeredImage {#ssec-pkgs-dockerTools-streamLayeredImage}
@ -226,15 +236,15 @@ pullImage {
- `imageDigest` specifies the digest of the image to be downloaded. This argument is required.
- `finalImageName`, if specified, this is the name of the image to be created. Note it is never used to fetch the image since we prefer to rely on the immutable digest ID. By default it\'s equal to `imageName`.
- `finalImageName`, if specified, this is the name of the image to be created. Note it is never used to fetch the image since we prefer to rely on the immutable digest ID. By default it's equal to `imageName`.
- `finalImageTag`, if specified, this is the tag of the image to be created. Note it is never used to fetch the image since we prefer to rely on the immutable digest ID. By default it\'s `latest`.
- `finalImageTag`, if specified, this is the tag of the image to be created. Note it is never used to fetch the image since we prefer to rely on the immutable digest ID. By default it's `latest`.
- `sha256` is the checksum of the whole fetched image. This argument is required.
- `os`, if specified, is the operating system of the fetched image. By default it\'s `linux`.
- `os`, if specified, is the operating system of the fetched image. By default it's `linux`.
- `arch`, if specified, is the cpu architecture of the fetched image. By default it\'s `x86_64`.
- `arch`, if specified, is the cpu architecture of the fetched image. By default it's `x86_64`.
`nix-prefetch-docker` command can be used to get required image parameters:
@ -278,7 +288,7 @@ The `name` argument is the name of the derivation output, which defaults to `fro
## shadowSetup {#ssec-pkgs-dockerTools-shadowSetup}
This constant string is a helper for setting up the base files for managing users and groups, only if such files don\'t exist already. It is suitable for being used in a [`buildImage` `runAsRoot`](#ex-dockerTools-buildImage-runAsRoot) script for cases like in the example below:
This constant string is a helper for setting up the base files for managing users and groups, only if such files don't exist already. It is suitable for being used in a [`buildImage` `runAsRoot`](#ex-dockerTools-buildImage-runAsRoot) script for cases like in the example below:
```nix
buildImage {

@ -0,0 +1,37 @@
# pkgs.ociTools {#sec-pkgs-ociTools}
`pkgs.ociTools` is a set of functions for creating containers according to the [OCI container specification v1.0.0](https://github.com/opencontainers/runtime-spec). Beyond that it makes no assumptions about the container runner you choose to use to run the created container.
## buildContainer {#ssec-pkgs-ociTools-buildContainer}
This function creates a simple OCI container that runs a single command inside of it. An OCI container consists of a `config.json` and a rootfs directory.The nix store of the container will contain all referenced dependencies of the given command.
The parameters of `buildContainer` with an example value are described below:
```nix
buildContainer {
args = [
(with pkgs;
writeScript "run.sh" ''
#!${bash}/bin/bash
exec ${bash}/bin/bash
'').outPath
];
mounts = {
"/data" = {
type = "none";
source = "/var/lib/mydata";
options = [ "bind" ];
};
};
readonly = false;
}
```
- `args` specifies a set of arguments to run inside the container. This is the only required argument for `buildContainer`. All referenced packages inside the derivation will be made available inside the container
- `mounts` specifies additional mount points chosen by the user. By default only a minimal set of necessary filesystems are mounted into the container (e.g procfs, cgroupfs)
- `readonly` makes the container\'s rootfs read-only if it is set to true. The default value is false `false`.

@ -1,61 +0,0 @@
<section xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xi="http://www.w3.org/2001/XInclude"
xml:id="sec-pkgs-ociTools">
<title>pkgs.ociTools</title>
<para>
<varname>pkgs.ociTools</varname> is a set of functions for creating containers according to the <link xlink:href="https://github.com/opencontainers/runtime-spec">OCI container specification v1.0.0</link>. Beyond that it makes no assumptions about the container runner you choose to use to run the created container.
</para>
<section xml:id="ssec-pkgs-ociTools-buildContainer">
<title>buildContainer</title>
<para>
This function creates a simple OCI container that runs a single command inside of it. An OCI container consists of a <varname>config.json</varname> and a rootfs directory.The nix store of the container will contain all referenced dependencies of the given command.
</para>
<para>
The parameters of <varname>buildContainer</varname> with an example value are described below:
</para>
<example xml:id='ex-ociTools-buildContainer'>
<title>Build Container</title>
<programlisting>
buildContainer {
args = [ (with pkgs; writeScript "run.sh" ''
#!${bash}/bin/bash
exec ${bash}/bin/bash
'').outPath ]; <co xml:id='ex-ociTools-buildContainer-1' />
mounts = {
"/data" = {
type = "none";
source = "/var/lib/mydata";
options = [ "bind" ];
};
};<co xml:id='ex-ociTools-buildContainer-2' />
readonly = false; <co xml:id='ex-ociTools-buildContainer-3' />
}
</programlisting>
<calloutlist>
<callout arearefs='ex-ociTools-buildContainer-1'>
<para>
<varname>args</varname> specifies a set of arguments to run inside the container. This is the only required argument for <varname>buildContainer</varname>. All referenced packages inside the derivation will be made available inside the container
</para>
</callout>
<callout arearefs='ex-ociTools-buildContainer-2'>
<para>
<varname>mounts</varname> specifies additional mount points chosen by the user. By default only a minimal set of necessary filesystems are mounted into the container (e.g procfs, cgroupfs)
</para>
</callout>
<callout arearefs='ex-ociTools-buildContainer-3'>
<para>
<varname>readonly</varname> makes the container's rootfs read-only if it is set to true. The default value is false <literal>false</literal>.
</para>
</callout>
</calloutlist>
</example>
</section>
</section>

@ -1,28 +0,0 @@
let
inherit (import <nixpkgs> { }) snapTools firefox;
in snapTools.makeSnap {
meta = {
name = "nix-example-firefox";
summary = firefox.meta.description;
architectures = [ "amd64" ];
apps.nix-example-firefox = {
command = "${firefox}/bin/firefox";
plugs = [
"pulseaudio"
"camera"
"browser-support"
"avahi-observe"
"cups-control"
"desktop"
"desktop-legacy"
"gsettings"
"home"
"network"
"mount-observe"
"removable-media"
"x11"
];
};
confinement = "strict";
};
}

@ -1,12 +0,0 @@
let
inherit (import <nixpkgs> { }) snapTools hello;
in snapTools.makeSnap {
meta = {
name = "hello";
summary = hello.meta.description;
description = hello.meta.longDescription;
architectures = [ "amd64" ];
confinement = "strict";
apps.hello.command = "${hello}/bin/hello";
};
}

@ -0,0 +1,71 @@
# pkgs.snapTools {#sec-pkgs-snapTools}
`pkgs.snapTools` is a set of functions for creating Snapcraft images. Snap and Snapcraft is not used to perform these operations.
## The makeSnap Function {#ssec-pkgs-snapTools-makeSnap-signature}
`makeSnap` takes a single named argument, `meta`. This argument mirrors [the upstream `snap.yaml` format](https://docs.snapcraft.io/snap-format) exactly.
The `base` should not be specified, as `makeSnap` will force set it.
Currently, `makeSnap` does not support creating GUI stubs.
## Build a Hello World Snap {#ssec-pkgs-snapTools-build-a-snap-hello}
The following expression packages GNU Hello as a Snapcraft snap.
```{#ex-snapTools-buildSnap-hello .nix}
let
inherit (import <nixpkgs> { }) snapTools hello;
in snapTools.makeSnap {
meta = {
name = "hello";
summary = hello.meta.description;
description = hello.meta.longDescription;
architectures = [ "amd64" ];
confinement = "strict";
apps.hello.command = "${hello}/bin/hello";
};
}
```
`nix-build` this expression and install it with `snap install ./result --dangerous`. `hello` will now be the Snapcraft version of the package.
## Build a Graphical Snap {#ssec-pkgs-snapTools-build-a-snap-firefox}
Graphical programs require many more integrations with the host. This example uses Firefox as an example, because it is one of the most complicated programs we could package.
```{#ex-snapTools-buildSnap-firefox .nix}
let
inherit (import <nixpkgs> { }) snapTools firefox;
in snapTools.makeSnap {
meta = {
name = "nix-example-firefox";
summary = firefox.meta.description;
architectures = [ "amd64" ];
apps.nix-example-firefox = {
command = "${firefox}/bin/firefox";
plugs = [
"pulseaudio"
"camera"
"browser-support"
"avahi-observe"
"cups-control"
"desktop"
"desktop-legacy"
"gsettings"
"home"
"network"
"mount-observe"
"removable-media"
"x11"
];
};
confinement = "strict";
};
}
```
`nix-build` this expression and install it with `snap install ./result --dangerous`. `nix-example-firefox` will now be the Snapcraft version of the Firefox package.
The specific meaning behind plugs can be looked up in the [Snapcraft interface documentation](https://docs.snapcraft.io/supported-interfaces).

@ -1,59 +0,0 @@
<section xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xi="http://www.w3.org/2001/XInclude"
xml:id="sec-pkgs-snapTools">
<title>pkgs.snapTools</title>
<para>
<varname>pkgs.snapTools</varname> is a set of functions for creating Snapcraft images. Snap and Snapcraft is not used to perform these operations.
</para>
<section xml:id="ssec-pkgs-snapTools-makeSnap-signature">
<title>The makeSnap Function</title>
<para>
<function>makeSnap</function> takes a single named argument, <parameter>meta</parameter>. This argument mirrors <link xlink:href="https://docs.snapcraft.io/snap-format">the upstream <filename>snap.yaml</filename> format</link> exactly.
</para>
<para>
The <parameter>base</parameter> should not be be specified, as <function>makeSnap</function> will force set it.
</para>
<para>
Currently, <function>makeSnap</function> does not support creating GUI stubs.
</para>
</section>
<section xml:id="ssec-pkgs-snapTools-build-a-snap-hello">
<title>Build a Hello World Snap</title>
<example xml:id="ex-snapTools-buildSnap-hello">
<title>Making a Hello World Snap</title>
<para>
The following expression packages GNU Hello as a Snapcraft snap.
</para>
<programlisting><xi:include href="./snap/example-hello.nix" parse="text" /></programlisting>
<para>
<command>nix-build</command> this expression and install it with <command>snap install ./result --dangerous</command>. <command>hello</command> will now be the Snapcraft version of the package.
</para>
</example>
</section>
<section xml:id="ssec-pkgs-snapTools-build-a-snap-firefox">
<title>Build a Hello World Snap</title>
<example xml:id="ex-snapTools-buildSnap-firefox">
<title>Making a Graphical Snap</title>
<para>
Graphical programs require many more integrations with the host. This example uses Firefox as an example, because it is one of the most complicated programs we could package.
</para>
<programlisting><xi:include href="./snap/example-firefox.nix" parse="text" /></programlisting>
<para>
<command>nix-build</command> this expression and install it with <command>snap install ./result --dangerous</command>. <command>nix-example-firefox</command> will now be the Snapcraft version of the Firefox package.
</para>
<para>
The specific meaning behind plugs can be looked up in the <link xlink:href="https://docs.snapcraft.io/supported-interfaces">Snapcraft interface documentation</link>.
</para>
</example>
</section>
</section>

@ -34,6 +34,41 @@ cataclysm-dda.override {
}
```
## Important note for overriding packages
After applying `overrideAttrs`, you need to fix `passthru.pkgs` and
`passthru.withMods` attributes either manually or by using `attachPkgs`:
```nix
let
# You enabled parallel building.
myCDDA = cataclysm-dda-git.overrideAttrs (_: {
enableParallelBuilding = true;
});
# Unfortunately, this refers to the package before overriding and
# parallel building is still disabled.
badExample = myCDDA.withMods (_: []);
inherit (cataclysmDDA) attachPkgs pkgs wrapCDDA;
# You can fix it by hand
goodExample1 = myCDDA.overrideAttrs (old: {
passthru = old.passthru // {
pkgs = pkgs.override { build = goodExample1; };
withMods = wrapCDDA goodExample1;
};
});
# or by using a helper function `attachPkgs`.
goodExample2 = attachPkgs pkgs myCDDA;
in
# badExample # parallel building disabled
# goodExample1.withMods (_: []) # parallel building enabled
goodExample2.withMods (_: []) # parallel building enabled
```
## Customizing with mods
To install Cataclysm DDA with mods of your choice, you can use `withMods`

@ -0,0 +1,32 @@
# Citrix Workspace {#sec-citrix}
The [Citrix Workspace App](https://www.citrix.com/products/workspace-app/) is a remote desktop viewer which provides access to [XenDesktop](https://www.citrix.com/products/xenapp-xendesktop/) installations.
## Basic usage {#sec-citrix-base}
The tarball archive needs to be downloaded manually as the license agreements of the vendor for [Citrix Workspace](https://www.citrix.de/downloads/workspace-app/linux/workspace-app-for-linux-latest.html) needs to be accepted first. Then run `nix-prefetch-url file://$PWD/linuxx64-$version.tar.gz`. With the archive available in the store the package can be built and installed with Nix.
## Citrix Selfservice {#sec-citrix-selfservice}
The [selfservice](https://support.citrix.com/article/CTX200337) is an application managing Citrix desktops and applications. Please note that this feature only works with at least citrix_workspace_20_06_0 and later versions.
In order to set this up, you first have to [download the `.cr` file from the Netscaler Gateway](https://its.uiowa.edu/support/article/102186). After that you can configure the `selfservice` like this:
```ShellSession
$ storebrowse -C ~/Downloads/receiverconfig.cr
$ selfservice
```
## Custom certificates {#sec-citrix-custom-certs}
The `Citrix Workspace App` in `nixpkgs` trusts several certificates [from the Mozilla database](https://curl.haxx.se/docs/caextract.html) by default. However several companies using Citrix might require their own corporate certificate. On distros with imperative packaging these certs can be stored easily in [`$ICAROOT`](https://developer-docs.citrix.com/projects/receiver-for-linux-command-reference/en/13.7/), however this directory is a store path in `nixpkgs`. In order to work around this issue the package provides a simple mechanism to add custom certificates without rebuilding the entire package using `symlinkJoin`:
```nix
with import <nixpkgs> { config.allowUnfree = true; };
let
extraCerts = [
./custom-cert-1.pem
./custom-cert-2.pem # ...
];
in citrix_workspace.override { inherit extraCerts; }
```

@ -1,46 +0,0 @@
<section xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xml:id="sec-citrix">
<title>Citrix Workspace</title>
<para>
The <link xlink:href="https://www.citrix.com/products/workspace-app/">Citrix Workspace App</link> is a remote desktop viewer which provides access to <link xlink:href="https://www.citrix.com/products/xenapp-xendesktop/">XenDesktop</link> installations.
</para>
<section xml:id="sec-citrix-base">
<title>Basic usage</title>
<para>
The tarball archive needs to be downloaded manually as the license agreements of the vendor for <link xlink:href="https://www.citrix.de/downloads/workspace-app/linux/workspace-app-for-linux-latest.html">Citrix Workspace</link> needs to be accepted first. Then run <command>nix-prefetch-url file://$PWD/linuxx64-$version.tar.gz</command>. With the archive available in the store the package can be built and installed with Nix.
</para>
</section>
<section xml:id="sec-citrix-selfservice">
<title>Citrix Selfservice</title>
<para>
The <link xlink:href="https://support.citrix.com/article/CTX200337">selfservice</link> is an application managing Citrix desktops and applications. Please note that this feature only works with at least <package>citrix_workspace_20_06_0</package> and later versions.
</para>
<para>
In order to set this up, you first have to <link xlink:href="https://its.uiowa.edu/support/article/102186">download the <literal>.cr</literal> file from the Netscaler Gateway</link>. After that you can configure the <command>selfservice</command> like this:
<screen>
<prompt>$ </prompt>storebrowse -C ~/Downloads/receiverconfig.cr
<prompt>$ </prompt>selfservice
</screen>
</para>
</section>
<section xml:id="sec-citrix-custom-certs">
<title>Custom certificates</title>
<para>
The <literal>Citrix Workspace App</literal> in <literal>nixpkgs</literal> trusts several certificates <link xlink:href="https://curl.haxx.se/docs/caextract.html">from the Mozilla database</link> by default. However several companies using Citrix might require their own corporate certificate. On distros with imperative packaging these certs can be stored easily in <link xlink:href="https://developer-docs.citrix.com/projects/receiver-for-linux-command-reference/en/13.7/"><literal>$ICAROOT</literal></link>, however this directory is a store path in <literal>nixpkgs</literal>. In order to work around this issue the package provides a simple mechanism to add custom certificates without rebuilding the entire package using <literal>symlinkJoin</literal>:
<programlisting>
<![CDATA[with import <nixpkgs> { config.allowUnfree = true; };
let extraCerts = [ ./custom-cert-1.pem ./custom-cert-2.pem /* ... */ ]; in
citrix_workspace.override {
inherit extraCerts;
}]]>
</programlisting>
</para>
</section>
</section>

@ -0,0 +1,13 @@
# DLib {#dlib}
[DLib](http://dlib.net/) is a modern, C++-based toolkit which provides several machine learning algorithms.
## Compiling without AVX support {#compiling-without-avx-support}
Especially older CPUs don\'t support [AVX](https://en.wikipedia.org/wiki/Advanced_Vector_Extensions) (Advanced Vector Extensions) instructions that are used by DLib to optimize their algorithms.
On the affected hardware errors like `Illegal instruction` will occur. In those cases AVX support needs to be disabled:
```nix
self: super: { dlib = super.dlib.override { avxSupport = false; }; }
```

@ -1,24 +0,0 @@
<section xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xml:id="dlib">
<title>DLib</title>
<para>
<link xlink:href="http://dlib.net/">DLib</link> is a modern, C++-based toolkit which provides several machine learning algorithms.
</para>
<section xml:id="compiling-without-avx-support">
<title>Compiling without AVX support</title>
<para>
Especially older CPUs don't support <link xlink:href="https://en.wikipedia.org/wiki/Advanced_Vector_Extensions">AVX</link> (<abbrev>Advanced Vector Extensions</abbrev>) instructions that are used by DLib to optimize their algorithms.
</para>
<para>
On the affected hardware errors like <literal>Illegal instruction</literal> will occur. In those cases AVX support needs to be disabled:
<programlisting>self: super: {
dlib = super.dlib.override { avxSupport = false; };
}</programlisting>
</para>
</section>
</section>

@ -36,7 +36,7 @@ You can install it like any other packages via `nix-env -iA myEmacs`. However, t
;; load some packages
(use-package company
:bind ("&lt;C-tab&gt;" . company-complete)
:bind ("<C-tab>" . company-complete)
:diminish company-mode
:commands (company-mode global-company-mode)
:defer 1

@ -0,0 +1,45 @@
# FUSE {#sec-fuse}
Some packages rely on
[FUSE](https://www.kernel.org/doc/html/latest/filesystems/fuse.html) to provide
support for additional filesystems not supported by the kernel.
In general, FUSE software are primarily developed for Linux but many of them can
also run on macOS. Nixpkgs supports FUSE packages on macOS, but it requires
[macFUSE](https://osxfuse.github.io) to be installed outside of Nix. macFUSE
currently isn't packaged in Nixpkgs mainly because it includes a kernel
extension, which isn't supported by Nix outside of NixOS.
If a package fails to run on macOS with an error message similar to the
following, it's a likely sign that you need to have macFUSE installed.
dyld: Library not loaded: /usr/local/lib/libfuse.2.dylib
Referenced from: /nix/store/w8bi72bssv0bnxhwfw3xr1mvn7myf37x-sshfs-fuse-2.10/bin/sshfs
Reason: image not found
[1] 92299 abort /nix/store/w8bi72bssv0bnxhwfw3xr1mvn7myf37x-sshfs-fuse-2.10/bin/sshfs
Package maintainers may often encounter the following error when building FUSE
packages on macOS:
checking for fuse.h... no
configure: error: No fuse.h found.
This happens on autoconf based projects that uses `AC_CHECK_HEADERS` or
`AC_CHECK_LIBS` to detect libfuse, and will occur even when the `fuse` package
is included in `buildInputs`. It happens because libfuse headers throw an error
on macOS if the `FUSE_USE_VERSION` macro is undefined. Many proejcts do define
`FUSE_USE_VERSION`, but only inside C source files. This results in the above
error at configure time because the configure script would attempt to compile
sample FUSE programs without defining `FUSE_USE_VERSION`.
There are two possible solutions for this problem in Nixpkgs:
1. Pass `FUSE_USE_VERSION` to the configure script by adding
`CFLAGS=-DFUSE_USE_VERSION=25` in `configureFlags`. The actual value would
have to match the definition used in the upstream source code.
2. Remove `AC_CHECK_HEADERS` / `AC_CHECK_LIBS` for libfuse.
However, a better solution might be to fix the build script upstream to use
`PKG_CHECK_MODULES` instead. This approach wouldn't suffer from the problem that
`AC_CHECK_HEADERS`/`AC_CHECK_LIBS` has at the price of introducing a dependency
on pkg-config.

@ -0,0 +1,38 @@
# ibus-engines.typing-booster {#sec-ibus-typing-booster}
This package is an ibus-based completion method to speed up typing.
## Activating the engine {#sec-ibus-typing-booster-activate}
IBus needs to be configured accordingly to activate `typing-booster`. The configuration depends on the desktop manager in use. For detailed instructions, please refer to the [upstream docs](https://mike-fabian.github.io/ibus-typing-booster/documentation.html).
On NixOS you need to explicitly enable `ibus` with given engines before customizing your desktop to use `typing-booster`. This can be achieved using the `ibus` module:
```nix
{ pkgs, ... }: {
i18n.inputMethod = {
enabled = "ibus";
ibus.engines = with pkgs.ibus-engines; [ typing-booster ];
};
}
```
## Using custom hunspell dictionaries {#sec-ibus-typing-booster-customize-hunspell}
The IBus engine is based on `hunspell` to support completion in many languages. By default the dictionaries `de-de`, `en-us`, `fr-moderne` `es-es`, `it-it`, `sv-se` and `sv-fi` are in use. To add another dictionary, the package can be overridden like this:
```nix
ibus-engines.typing-booster.override { langs = [ "de-at" "en-gb" ]; }
```
_Note: each language passed to `langs` must be an attribute name in `pkgs.hunspellDicts`._
## Built-in emoji picker {#sec-ibus-typing-booster-emoji-picker}
The `ibus-engines.typing-booster` package contains a program named `emoji-picker`. To display all emojis correctly, a special font such as `noto-fonts-emoji` is needed:
On NixOS it can be installed using the following expression:
```nix
{ pkgs, ... }: { fonts.fonts = with pkgs; [ noto-fonts-emoji ]; }
```

@ -1,57 +0,0 @@
<section xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xml:id="sec-ibus-typing-booster">
<title>ibus-engines.typing-booster</title>
<para>
This package is an ibus-based completion method to speed up typing.
</para>
<section xml:id="sec-ibus-typing-booster-activate">
<title>Activating the engine</title>
<para>
IBus needs to be configured accordingly to activate <literal>typing-booster</literal>. The configuration depends on the desktop manager in use. For detailed instructions, please refer to the <link xlink:href="https://mike-fabian.github.io/ibus-typing-booster/documentation.html">upstream docs</link>.
</para>
<para>
On NixOS you need to explicitly enable <literal>ibus</literal> with given engines before customizing your desktop to use <literal>typing-booster</literal>. This can be achieved using the <literal>ibus</literal> module:
<programlisting>{ pkgs, ... }: {
i18n.inputMethod = {
enabled = "ibus";
ibus.engines = with pkgs.ibus-engines; [ typing-booster ];
};
}</programlisting>
</para>
</section>
<section xml:id="sec-ibus-typing-booster-customize-hunspell">
<title>Using custom hunspell dictionaries</title>
<para>
The IBus engine is based on <literal>hunspell</literal> to support completion in many languages. By default the dictionaries <literal>de-de</literal>, <literal>en-us</literal>, <literal>fr-moderne</literal> <literal>es-es</literal>, <literal>it-it</literal>, <literal>sv-se</literal> and <literal>sv-fi</literal> are in use. To add another dictionary, the package can be overridden like this:
<programlisting>ibus-engines.typing-booster.override {
langs = [ "de-at" "en-gb" ];
}</programlisting>
</para>
<para>
<emphasis>Note: each language passed to <literal>langs</literal> must be an attribute name in <literal>pkgs.hunspellDicts</literal>.</emphasis>
</para>
</section>
<section xml:id="sec-ibus-typing-booster-emoji-picker">
<title>Built-in emoji picker</title>
<para>
The <literal>ibus-engines.typing-booster</literal> package contains a program named <literal>emoji-picker</literal>. To display all emojis correctly, a special font such as <literal>noto-fonts-emoji</literal> is needed:
</para>
<para>
On NixOS it can be installed using the following expression:
<programlisting>{ pkgs, ... }: {
fonts.fonts = with pkgs; [ noto-fonts-emoji ];
}</programlisting>
</para>
</section>
</section>

@ -5,14 +5,15 @@
<para>
This chapter contains information about how to use and maintain the Nix expressions for a number of specific packages, such as the Linux kernel or X.org.
</para>
<xi:include href="citrix.xml" />
<xi:include href="dlib.xml" />
<xi:include href="citrix.section.xml" />
<xi:include href="dlib.section.xml" />
<xi:include href="eclipse.section.xml" />
<xi:include href="elm.section.xml" />
<xi:include href="emacs.section.xml" />
<xi:include href="firefox.section.xml" />
<xi:include href="fish.section.xml" />
<xi:include href="ibus.xml" />
<xi:include href="fuse.section.xml" />
<xi:include href="ibus.section.xml" />
<xi:include href="kakoune.section.xml" />
<xi:include href="linux.section.xml" />
<xi:include href="locales.section.xml" />

@ -0,0 +1,585 @@
# Coding conventions {#chap-conventions}
## Syntax {#sec-syntax}
- Use 2 spaces of indentation per indentation level in Nix expressions, 4 spaces in shell scripts.
- Do not use tab characters, i.e. configure your editor to use soft tabs. For instance, use `(setq-default indent-tabs-mode nil)` in Emacs. Everybody has different tab settings so it’s asking for trouble.
- Use `lowerCamelCase` for variable names, not `UpperCamelCase`. Note, this rule does not apply to package attribute names, which instead follow the rules in <xref linkend="sec-package-naming"/>.
- Function calls with attribute set arguments are written as
```nix
foo {
arg = ...;
}
```
not
```nix
foo
{
arg = ...;
}
```
Also fine is
```nix
foo { arg = ...; }
```
if it's a short call.
- In attribute sets or lists that span multiple lines, the attribute names or list elements should be aligned:
```nix
# A long list.
list = [
elem1
elem2
elem3
];
# A long attribute set.
attrs = {
attr1 = short_expr;
attr2 =
if true then big_expr else big_expr;
};
# Combined
listOfAttrs = [
{
attr1 = 3;
attr2 = "fff";
}
{
attr1 = 5;
attr2 = "ggg";
}
];
```
- Short lists or attribute sets can be written on one line:
```nix
# A short list.
list = [ elem1 elem2 elem3 ];
# A short set.
attrs = { x = 1280; y = 1024; };
```
- Breaking in the middle of a function argument can give hard-to-read code, like
```nix
someFunction { x = 1280;
y = 1024; } otherArg
yetAnotherArg
```
(especially if the argument is very large, spanning multiple lines).
Better:
```nix
someFunction
{ x = 1280; y = 1024; }
otherArg
yetAnotherArg
```
or
```nix
let res = { x = 1280; y = 1024; };
in someFunction res otherArg yetAnotherArg
```
- The bodies of functions, asserts, and withs are not indented to prevent a lot of superfluous indentation levels, i.e.
```nix
{ arg1, arg2 }:
assert system == "i686-linux";
stdenv.mkDerivation { ...
```
not
```nix
{ arg1, arg2 }:
assert system == "i686-linux";
stdenv.mkDerivation { ...
```
- Function formal arguments are written as:
```nix
{ arg1, arg2, arg3 }:
```
but if they don't fit on one line they're written as:
```nix
{ arg1, arg2, arg3
, arg4, ...
, # Some comment...
argN
}:
```
- Functions should list their expected arguments as precisely as possible. That is, write
```nix
{ stdenv, fetchurl, perl }: ...
```
instead of
```nix
args: with args; ...
```
or
```nix
{ 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:
```nix
{ stdenv, doCoverageAnalysis ? false, ... } @ args:
stdenv.mkDerivation (args // {
... if doCoverageAnalysis then "bla" else "" ...
})
```
instead of
```nix
args:
args.stdenv.mkDerivation (args // {
... if args ? doCoverageAnalysis && args.doCoverageAnalysis then "bla" else "" ...
})
```
- Arguments should be listed in the order they are used, with the exception of `lib`, which always goes first.
- The top-level `lib` must be used in the master and 21.05 branch over its alias `stdenv.lib` as it now causes evaluation errors when aliases are disabled which is the case for ofborg.
`lib` is unrelated to `stdenv`, and so `stdenv.lib` should only be used as a convenience alias when developing locally to avoid having to modify the function inputs just to test something out.
## Package naming {#sec-package-naming}
The key words _must_, _must not_, _required_, _shall_, _shall not_, _should_, _should not_, _recommended_, _may_, and _optional_ in this section are to be interpreted as described in [RFC 2119](https://tools.ietf.org/html/rfc2119). Only _emphasized_ words are to be interpreted in this way.
In Nixpkgs, there are generally three different names associated with a package:
- The `name` attribute of the derivation (excluding the version part). This is what most users see, in particular when using `nix-env`.
- The variable name used for the instantiated package in `all-packages.nix`, and when passing it as a dependency to other functions. Typically this is called the _package attribute name_. This is what Nix expression authors see. It can also be used when installing using `nix-env -iA`.
- The filename for (the directory containing) the Nix expression.
Most of the time, these are the same. For instance, the package `e2fsprogs` has a `name` attribute `"e2fsprogs-version"`, is bound to the variable name `e2fsprogs` in `all-packages.nix`, and the Nix expression is in `pkgs/os-specific/linux/e2fsprogs/default.nix`.
There are a few naming guidelines:
- The `name` attribute _should_ be identical to the upstream package name.
- The `name` attribute _must not_ contain uppercase letters — e.g., `"mplayer-1.0rc2"` instead of `"MPlayer-1.0rc2"`.
- The version part of the `name` attribute _must_ start with a digit (following a dash) — e.g., `"hello-0.3.1rc2"`.
- If a package is not a release but a commit from a repository, then the version part of the name _must_ be the date of that (fetched) commit. The date _must_ be in `"YYYY-MM-DD"` format. Also append `"unstable"` to the name - e.g., `"pkgname-unstable-2014-09-23"`.
- Dashes in the package name _should_ be preserved in new variable names, rather than converted to underscores or camel cased — e.g., `http-parser` instead of `http_parser` or `httpParser`. The hyphenated style is preferred in all three package names.
- If there are multiple versions of a package, this _should_ be reflected in the variable names in `all-packages.nix`, e.g. `json-c-0-9` and `json-c-0-11`. If there is an obvious “default” version, make an attribute like `json-c = json-c-0-9;`. See also <xref linkend="sec-versioning" />
## File naming and organisation {#sec-organisation}
Names of files and directories should be in lowercase, with dashes between words — not in camel case. For instance, it should be `all-packages.nix`, not `allPackages.nix` or `AllPackages.nix`.
### Hierarchy {#sec-hierarchy}
Each package should be stored in its own directory somewhere in the `pkgs/` tree, i.e. in `pkgs/category/subcategory/.../pkgname`. Below are some rules for picking the right category for a package. Many packages fall under several categories; what matters is the _primary_ purpose of a package. For example, the `libxml2` package builds both a library and some tools; but it’s a library foremost, so it goes under `pkgs/development/libraries`.
When in doubt, consider refactoring the `pkgs/` tree, e.g. creating new categories or splitting up an existing category.
**If it’s used to support _software development_:**
- **If it’s a _library_ used by other packages:**
- `development/libraries` (e.g. `libxml2`)
- **If it’s a _compiler_:**
- `development/compilers` (e.g. `gcc`)
- **If it’s an _interpreter_:**
- `development/interpreters` (e.g. `guile`)
- **If it’s a (set of) development _tool(s)_:**
- **If it’s a _parser generator_ (including lexers):**
- `development/tools/parsing` (e.g. `bison`, `flex`)
- **If it’s a _build manager_:**
- `development/tools/build-managers` (e.g. `gnumake`)
- **Else:**
- `development/tools/misc` (e.g. `binutils`)
- **Else:**
- `development/misc`
**If it’s a (set of) _tool(s)_:**
(A tool is a relatively small program, especially one intended to be used non-interactively.)
- **If it’s for _networking_:**
- `tools/networking` (e.g. `wget`)
- **If it’s for _text processing_:**
- `tools/text` (e.g. `diffutils`)
- **If it’s a _system utility_, i.e., something related or essential to the operation of a system:**
- `tools/system` (e.g. `cron`)
- **If it’s an _archiver_ (which may include a compression function):**
- `tools/archivers` (e.g. `zip`, `tar`)
- **If it’s a _compression_ program:**
- `tools/compression` (e.g. `gzip`, `bzip2`)
- **If it’s a _security_-related program:**
- `tools/security` (e.g. `nmap`, `gnupg`)
- **Else:**
- `tools/misc`
**If it’s a _shell_:**
- `shells` (e.g. `bash`)
**If it’s a _server_:**
- **If it’s a web server:**
- `servers/http` (e.g. `apache-httpd`)
- **If it’s an implementation of the X Windowing System:**
- `servers/x11` (e.g. `xorg` — this includes the client libraries and programs)
- **Else:**
- `servers/misc`
**If it’s a _desktop environment_:**
- `desktops` (e.g. `kde`, `gnome`, `enlightenment`)
**If it’s a _window manager_:**
- `applications/window-managers` (e.g. `awesome`, `stumpwm`)
**If it’s an _application_:**
A (typically large) program with a distinct user interface, primarily used interactively.
- **If it’s a _version management system_:**
- `applications/version-management` (e.g. `subversion`)
- **If it’s a _terminal emulator_:**
- `applications/terminal-emulators` (e.g. `alacritty` or `rxvt` or `termite`)
- **If it’s for _video playback / editing_:**
- `applications/video` (e.g. `vlc`)
- **If it’s for _graphics viewing / editing_:**
- `applications/graphics` (e.g. `gimp`)
- **If it’s for _networking_:**
- **If it’s a _mailreader_:**
- `applications/networking/mailreaders` (e.g. `thunderbird`)
- **If it’s a _newsreader_:**
- `applications/networking/newsreaders` (e.g. `pan`)
- **If it’s a _web browser_:**
- `applications/networking/browsers` (e.g. `firefox`)
- **Else:**
- `applications/networking/misc`
- **Else:**
- `applications/misc`
**If it’s _data_ (i.e., does not have a straight-forward executable semantics):**
- **If it’s a _font_:**
- `data/fonts`
- **If it’s an _icon theme_:**
- `data/icons`
- **If it’s related to _SGML/XML processing_:**
- **If it’s an _XML DTD_:**
- `data/sgml+xml/schemas/xml-dtd` (e.g. `docbook`)
- **If it’s an _XSLT stylesheet_:**
(Okay, these are executable...)
- `data/sgml+xml/stylesheets/xslt` (e.g. `docbook-xsl`)
- **If it’s a _theme_ for a _desktop environment_, a _window manager_ or a _display manager_:**
- `data/themes`
**If it’s a _game_:**
- `games`
**Else:**
- `misc`
### Versioning {#sec-versioning}
Because every version of a package in Nixpkgs creates a potential maintenance burden, old versions of a package should not be kept unless there is a good reason to do so. For instance, Nixpkgs contains several versions of GCC because other packages don’t build with the latest version of GCC. Other examples are having both the latest stable and latest pre-release version of a package, or to keep several major releases of an application that differ significantly in functionality.
If there is only one version of a package, its Nix expression should be named `e2fsprogs/default.nix`. If there are multiple versions, this should be reflected in the filename, e.g. `e2fsprogs/1.41.8.nix` and `e2fsprogs/1.41.9.nix`. The version in the filename should leave out unnecessary detail. For instance, if we keep the latest Firefox 2.0.x and 3.5.x versions in Nixpkgs, they should be named `firefox/2.0.nix` and `firefox/3.5.nix`, respectively (which, at a given point, might contain versions `2.0.0.20` and `3.5.4`). If a version requires many auxiliary files, you can use a subdirectory for each version, e.g. `firefox/2.0/default.nix` and `firefox/3.5/default.nix`.
All versions of a package _must_ be included in `all-packages.nix` to make sure that they evaluate correctly.
## Fetching Sources {#sec-sources}
There are multiple ways to fetch a package source in nixpkgs. The general guideline is that you should package reproducible sources with a high degree of availability. Right now there is only one fetcher which has mirroring support and that is `fetchurl`. Note that you should also prefer protocols which have a corresponding proxy environment variable.
You can find many source fetch helpers in `pkgs/build-support/fetch*`.
In the file `pkgs/top-level/all-packages.nix` you can find fetch helpers, these have names on the form `fetchFrom*`. The intention of these are to provide snapshot fetches but using the same api as some of the version controlled fetchers from `pkgs/build-support/`. As an example going from bad to good:
- Bad: Uses `git://` which won't be proxied.
```nix
src = fetchgit {
url = "git://github.com/NixOS/nix.git";
rev = "1f795f9f44607cc5bec70d1300150bfefcef2aae";
sha256 = "1cw5fszffl5pkpa6s6wjnkiv6lm5k618s32sp60kvmvpy7a2v9kg";
}
```
- Better: This is ok, but an archive fetch will still be faster.
```nix
src = fetchgit {
url = "https://github.com/NixOS/nix.git";
rev = "1f795f9f44607cc5bec70d1300150bfefcef2aae";
sha256 = "1cw5fszffl5pkpa6s6wjnkiv6lm5k618s32sp60kvmvpy7a2v9kg";
}
```
- Best: Fetches a snapshot archive and you get the rev you want.
```nix
src = fetchFromGitHub {
owner = "NixOS";
repo = "nix";
rev = "1f795f9f44607cc5bec70d1300150bfefcef2aae";
sha256 = "1i2yxndxb6yc9l6c99pypbd92lfq5aac4klq7y2v93c9qvx2cgpc";
}
```
Find the value to put as `sha256` by running `nix run -f '<nixpkgs>' nix-prefetch-github -c nix-prefetch-github --rev 1f795f9f44607cc5bec70d1300150bfefcef2aae NixOS nix` or `nix-prefetch-url --unpack https://github.com/NixOS/nix/archive/1f795f9f44607cc5bec70d1300150bfefcef2aae.tar.gz`.
## Obtaining source hash {#sec-source-hashes}
Preferred source hash type is sha256. There are several ways to get it.
1. Prefetch URL (with `nix-prefetch-XXX URL`, where `XXX` is one of `url`, `git`, `hg`, `cvs`, `bzr`, `svn`). Hash is printed to stdout.
2. Prefetch by package source (with `nix-prefetch-url '<nixpkgs>' -A PACKAGE.src`, where `PACKAGE` is package attribute name). Hash is printed to stdout.
This works well when you've upgraded existing package version and want to find out new hash, but is useless if package can't be accessed by attribute or package has multiple sources (`.srcs`, architecture-dependent sources, etc).
3. Upstream provided hash: use it when upstream provides `sha256` or `sha512` (when upstream provides `md5`, don't use it, compute `sha256` instead).
A little nuance is that `nix-prefetch-*` tools produce hash encoded with `base32`, but upstream usually provides hexadecimal (`base16`) encoding. Fetchers understand both formats. Nixpkgs does not standardize on any one format.
You can convert between formats with nix-hash, for example:
```ShellSession
$ nix-hash --type sha256 --to-base32 HASH
```
4. Extracting hash from local source tarball can be done with `sha256sum`. Use `nix-prefetch-url file:///path/to/tarball` if you want base32 hash.
5. Fake hash: set fake hash in package expression, perform build and extract correct hash from error Nix prints.
For package updates it is enough to change one symbol to make hash fake. For new packages, you can use `lib.fakeSha256`, `lib.fakeSha512` or any other fake hash.
This is last resort method when reconstructing source URL is non-trivial and `nix-prefetch-url -A` isn't applicable (for example, [one of `kodi` dependencies](https://github.com/NixOS/nixpkgs/blob/d2ab091dd308b99e4912b805a5eb088dd536adb9/pkgs/applications/video/kodi/default.nix#L73")). The easiest way then would be replace hash with a fake one and rebuild. Nix build will fail and error message will contain desired hash.
::: warning
This method has security problems. Check below for details.
:::
### Obtaining hashes securely {#sec-source-hashes-security}
Let's say Man-in-the-Middle (MITM) sits close to your network. Then instead of fetching source you can fetch malware, and instead of source hash you get hash of malware. Here are security considerations for this scenario:
- `http://` URLs are not secure to prefetch hash from;
- hashes from upstream (in method 3) should be obtained via secure protocol;
- `https://` URLs are secure in methods 1, 2, 3;
- `https://` URLs are not secure in method 5. When obtaining hashes with fake hash method, TLS checks are disabled. So refetch source hash from several different networks to exclude MITM scenario. Alternatively, use fake hash method to make Nix error, but instead of extracting hash from error, extract `https://` URL and prefetch it with method 1.
## Patches {#sec-patches}
Patches available online should be retrieved using `fetchpatch`.
```nix
patches = [
(fetchpatch {
name = "fix-check-for-using-shared-freetype-lib.patch";
url = "http://git.ghostscript.com/?p=ghostpdl.git;a=patch;h=8f5d285";
sha256 = "1f0k043rng7f0rfl9hhb89qzvvksqmkrikmm38p61yfx51l325xr";
})
];
```
Otherwise, you can add a `.patch` file to the `nixpkgs` repository. In the interest of keeping our maintenance burden to a minimum, only patches that are unique to `nixpkgs` should be added in this way.
```nix
patches = [ ./0001-changes.patch ];
```
If you do need to do create this sort of patch file, one way to do so is with git:
1. Move to the root directory of the source code you're patching.
```ShellSession
$ cd the/program/source
```
2. If a git repository is not already present, create one and stage all of the source files.
```ShellSession
$ git init
$ git add .
```
3. Edit some files to make whatever changes need to be included in the patch.
4. Use git to create a diff, and pipe the output to a patch file:
```ShellSession
$ git diff > nixpkgs/pkgs/the/package/0001-changes.patch
```
## Package tests {#sec-package-tests}
Tests are important to ensure quality and make reviews and automatic updates easy.
Nix package tests are a lightweight alternative to [NixOS module tests](https://nixos.org/manual/nixos/stable/#sec-nixos-tests). They can be used to create simple integration tests for packages while the module tests are used to test services or programs with a graphical user interface on a NixOS VM. Unittests that are included in the source code of a package should be executed in the `checkPhase`.
### Writing package tests {#ssec-package-tests-writing}
This is an example using the `phoronix-test-suite` package with the current best practices.
Add the tests in `passthru.tests` to the package definition like this:
```nix
{ stdenv, lib, fetchurl, callPackage }:
stdenv.mkDerivation {
passthru.tests = {
simple-execution = callPackage ./tests.nix { };
};
meta = { … };
}
```
Create `tests.nix` in the package directory:
```nix
{ runCommand, phoronix-test-suite }:
let
inherit (phoronix-test-suite) pname version;
in
runCommand "${pname}-tests" { meta.timeout = 3; }
''
# automatic initial setup to prevent interactive questions
${phoronix-test-suite}/bin/phoronix-test-suite enterprise-setup >/dev/null
# get version of installed program and compare with package version
if [[ `${phoronix-test-suite}/bin/phoronix-test-suite version` != *"${version}"* ]]; then
echo "Error: program version does not match package version"
exit 1
fi
# run dummy command
${phoronix-test-suite}/bin/phoronix-test-suite dummy_module.dummy-command >/dev/null
# needed for Nix to register the command as successful
touch $out
''
```
### Running package tests {#ssec-package-tests-running}
You can run these tests with:
```ShellSession
$ cd path/to/nixpkgs
$ nix-build -A phoronix-test-suite.tests
```
### Examples of package tests {#ssec-package-tests-examples}
Here are examples of package tests:
- [Jasmin compile test](https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/compilers/jasmin/test-assemble-hello-world/default.nix)
- [Lobster compile test](https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/compilers/lobster/test-can-run-hello-world.nix)
- [Spacy annotation test](https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/python-modules/spacy/annotation-test/default.nix)
- [Libtorch test](https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/libraries/science/math/libtorch/test/default.nix)
- [Multiple tests for nanopb](https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/libraries/nanopb/default.nix)

@ -1,949 +0,0 @@
<chapter xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xml:id="chap-conventions">
<title>Coding conventions</title>
<section xml:id="sec-syntax">
<title>Syntax</title>
<itemizedlist>
<listitem>
<para>
Use 2 spaces of indentation per indentation level in Nix expressions, 4 spaces in shell scripts.
</para>
</listitem>
<listitem>
<para>
Do not use tab characters, i.e. configure your editor to use soft tabs. For instance, use <literal>(setq-default indent-tabs-mode nil)</literal> in Emacs. Everybody has different tab settings so it’s asking for trouble.
</para>
</listitem>
<listitem>
<para>
Use <literal>lowerCamelCase</literal> for variable names, not <literal>UpperCamelCase</literal>. Note, this rule does not apply to package attribute names, which instead follow the rules in <xref linkend="sec-package-naming"/>.
</para>
</listitem>
<listitem>
<para>
Function calls with attribute set arguments are written as
<programlisting>
foo {
arg = ...;
}
</programlisting>
not
<programlisting>
foo
{
arg = ...;
}
</programlisting>
Also fine is
<programlisting>
foo { arg = ...; }
</programlisting>
if it's a short call.
</para>
</listitem>
<listitem>
<para>
In attribute sets or lists that span multiple lines, the attribute names or list elements should be aligned:
<programlisting>
# A long list.
list = [
elem1
elem2
elem3
];
# A long attribute set.
attrs = {
attr1 = short_expr;
attr2 =
if true then big_expr else big_expr;
};
# Combined
listOfAttrs = [
{
attr1 = 3;
attr2 = "fff";
}
{
attr1 = 5;
attr2 = "ggg";
}
];
</programlisting>
</para>
</listitem>
<listitem>
<para>
Short lists or attribute sets can be written on one line:
<programlisting>
# A short list.
list = [ elem1 elem2 elem3 ];
# A short set.
attrs = { x = 1280; y = 1024; };
</programlisting>
</para>
</listitem>
<listitem>
<para>
Breaking in the middle of a function argument can give hard-to-read code, like
<programlisting>
someFunction { x = 1280;
y = 1024; } otherArg
yetAnotherArg
</programlisting>
(especially if the argument is very large, spanning multiple lines).
</para>
<para>
Better:
<programlisting>
someFunction
{ x = 1280; y = 1024; }
otherArg
yetAnotherArg
</programlisting>
or
<programlisting>
let res = { x = 1280; y = 1024; };
in someFunction res otherArg yetAnotherArg
</programlisting>
</para>
</listitem>
<listitem>
<para>
The bodies of functions, asserts, and withs are not indented to prevent a lot of superfluous indentation levels, i.e.
<programlisting>
{ arg1, arg2 }:
assert system == "i686-linux";
stdenv.mkDerivation { ...
</programlisting>
not
<programlisting>
{ arg1, arg2 }:
assert system == "i686-linux";
stdenv.mkDerivation { ...
</programlisting>
</para>
</listitem>
<listitem>
<para>
Function formal arguments are written as:
<programlisting>
{ arg1, arg2, arg3 }:
</programlisting>
but if they don't fit on one line they're written as:
<programlisting>
{ arg1, arg2, arg3
, arg4, ...
, # Some comment...
argN
}:
</programlisting>
</para>
</listitem>
<listitem>
<para>
Functions should list their expected arguments as precisely as possible. That is, write
<programlisting>
{ stdenv, fetchurl, perl }: <replaceable>...</replaceable>
</programlisting>
instead of
<programlisting>
args: with args; <replaceable>...</replaceable>
</programlisting>
or
<programlisting>
{ stdenv, fetchurl, perl, ... }: <replaceable>...</replaceable>
</programlisting>
</para>
<para>
For functions that are truly generic in the number of arguments (such as wrappers around <varname>mkDerivation</varname>) that have some required arguments, you should write them using an <literal>@</literal>-pattern:
<programlisting>
{ stdenv, doCoverageAnalysis ? false, ... } @ args:
stdenv.mkDerivation (args // {
<replaceable>...</replaceable> if doCoverageAnalysis then "bla" else "" <replaceable>...</replaceable>
})
</programlisting>
instead of
<programlisting>
args:
args.stdenv.mkDerivation (args // {
<replaceable>...</replaceable> if args ? doCoverageAnalysis &amp;&amp; args.doCoverageAnalysis then "bla" else "" <replaceable>...</replaceable>
})
</programlisting>
</para>
</listitem>
<listitem>
<para>
Arguments should be listed in the order they are used, with the
exception of <varname>lib</varname>, which always goes first.
</para>
</listitem>
<listitem>
<para>
Prefer using the top-level <varname>lib</varname> over its alias
<literal>stdenv.lib</literal>. <varname>lib</varname> is unrelated to
<varname>stdenv</varname>, and so <literal>stdenv.lib</literal> should only
be used as a convenience alias when developing to avoid having to modify
the function inputs just to test something out.
</para>
</listitem>
</itemizedlist>
</section>
<section xml:id="sec-package-naming">
<title>Package naming</title>
<para>
The key words <emphasis>must</emphasis>, <emphasis>must not</emphasis>, <emphasis>required</emphasis>, <emphasis>shall</emphasis>, <emphasis>shall not</emphasis>, <emphasis>should</emphasis>, <emphasis>should not</emphasis>, <emphasis>recommended</emphasis>, <emphasis>may</emphasis>, and <emphasis>optional</emphasis> in this section are to be interpreted as described in <link xlink:href="https://tools.ietf.org/html/rfc2119">RFC 2119</link>. Only <emphasis>emphasized</emphasis> words are to be interpreted in this way.
</para>
<para>
In Nixpkgs, there are generally three different names associated with a package:
<itemizedlist>
<listitem>
<para>
The <varname>name</varname> attribute of the derivation (excluding the version part). This is what most users see, in particular when using <command>nix-env</command>.
</para>
</listitem>
<listitem>
<para>
The variable name used for the instantiated package in <filename>all-packages.nix</filename>, and when passing it as a dependency to other functions. Typically this is called the <emphasis>package attribute name</emphasis>. This is what Nix expression authors see. It can also be used when installing using <command>nix-env -iA</command>.
</para>
</listitem>
<listitem>
<para>
The filename for (the directory containing) the Nix expression.
</para>
</listitem>
</itemizedlist>
Most of the time, these are the same. For instance, the package <literal>e2fsprogs</literal> has a <varname>name</varname> attribute <literal>"e2fsprogs-<replaceable>version</replaceable>"</literal>, is bound to the variable name <varname>e2fsprogs</varname> in <filename>all-packages.nix</filename>, and the Nix expression is in <filename>pkgs/os-specific/linux/e2fsprogs/default.nix</filename>.
</para>
<para>
There are a few naming guidelines:
<itemizedlist>
<listitem>
<para>
The <literal>name</literal> attribute <emphasis>should</emphasis> be identical to the upstream package name.
</para>
</listitem>
<listitem>
<para>
The <literal>name</literal> attribute <emphasis>must not</emphasis> contain uppercase letters — e.g., <literal>"mplayer-1.0rc2"</literal> instead of <literal>"MPlayer-1.0rc2"</literal>.
</para>
</listitem>
<listitem>
<para>
The version part of the <literal>name</literal> attribute <emphasis>must</emphasis> start with a digit (following a dash) — e.g., <literal>"hello-0.3.1rc2"</literal>.
</para>
</listitem>
<listitem>
<para>
If a package is not a release but a commit from a repository, then the version part of the name <emphasis>must</emphasis> be the date of that (fetched) commit. The date <emphasis>must</emphasis> be in <literal>"YYYY-MM-DD"</literal> format. Also append <literal>"unstable"</literal> to the name - e.g., <literal>"pkgname-unstable-2014-09-23"</literal>.
</para>
</listitem>
<listitem>
<para>
Dashes in the package name <emphasis>should</emphasis> be preserved in new variable names, rather than converted to underscores or camel cased — e.g., <varname>http-parser</varname> instead of <varname>http_parser</varname> or <varname>httpParser</varname>. The hyphenated style is preferred in all three package names.
</para>
</listitem>
<listitem>
<para>
If there are multiple versions of a package, this <emphasis>should</emphasis> be reflected in the variable names in <filename>all-packages.nix</filename>, e.g. <varname>json-c-0-9</varname> and <varname>json-c-0-11</varname>. If there is an obvious “default” version, make an attribute like <literal>json-c = json-c-0-9;</literal>. See also <xref linkend="sec-versioning" />
</para>
</listitem>
</itemizedlist>
</para>
</section>
<section xml:id="sec-organisation">
<title>File naming and organisation</title>
<para>
Names of files and directories should be in lowercase, with dashes between words — not in camel case. For instance, it should be <filename>all-packages.nix</filename>, not <filename>allPackages.nix</filename> or <filename>AllPackages.nix</filename>.
</para>
<section xml:id="sec-hierarchy">
<title>Hierarchy</title>
<para>
Each package should be stored in its own directory somewhere in the <filename>pkgs/</filename> tree, i.e. in <filename>pkgs/<replaceable>category</replaceable>/<replaceable>subcategory</replaceable>/<replaceable>...</replaceable>/<replaceable>pkgname</replaceable></filename>. Below are some rules for picking the right category for a package. Many packages fall under several categories; what matters is the <emphasis>primary</emphasis> purpose of a package. For example, the <literal>libxml2</literal> package builds both a library and some tools; but it’s a library foremost, so it goes under <filename>pkgs/development/libraries</filename>.
</para>
<para>
When in doubt, consider refactoring the <filename>pkgs/</filename> tree, e.g. creating new categories or splitting up an existing category.
</para>
<variablelist>
<varlistentry>
<term>
If it’s used to support <emphasis>software development</emphasis>:
</term>
<listitem>
<variablelist>
<varlistentry>
<term>
If it’s a <emphasis>library</emphasis> used by other packages:
</term>
<listitem>
<para>
<filename>development/libraries</filename> (e.g. <filename>libxml2</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>compiler</emphasis>:
</term>
<listitem>
<para>
<filename>development/compilers</filename> (e.g. <filename>gcc</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s an <emphasis>interpreter</emphasis>:
</term>
<listitem>
<para>
<filename>development/interpreters</filename> (e.g. <filename>guile</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a (set of) development <emphasis>tool(s)</emphasis>:
</term>
<listitem>
<variablelist>
<varlistentry>
<term>
If it’s a <emphasis>parser generator</emphasis> (including lexers):
</term>
<listitem>
<para>
<filename>development/tools/parsing</filename> (e.g. <filename>bison</filename>, <filename>flex</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>build manager</emphasis>:
</term>
<listitem>
<para>
<filename>development/tools/build-managers</filename> (e.g. <filename>gnumake</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
Else:
</term>
<listitem>
<para>
<filename>development/tools/misc</filename> (e.g. <filename>binutils</filename>)
</para>
</listitem>
</varlistentry>
</variablelist>
</listitem>
</varlistentry>
<varlistentry>
<term>
Else:
</term>
<listitem>
<para>
<filename>development/misc</filename>
</para>
</listitem>
</varlistentry>
</variablelist>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a (set of) <emphasis>tool(s)</emphasis>:
</term>
<listitem>
<para>
(A tool is a relatively small program, especially one intended to be used non-interactively.)
</para>
<variablelist>
<varlistentry>
<term>
If it’s for <emphasis>networking</emphasis>:
</term>
<listitem>
<para>
<filename>tools/networking</filename> (e.g. <filename>wget</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s for <emphasis>text processing</emphasis>:
</term>
<listitem>
<para>
<filename>tools/text</filename> (e.g. <filename>diffutils</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>system utility</emphasis>, i.e., something related or essential to the operation of a system:
</term>
<listitem>
<para>
<filename>tools/system</filename> (e.g. <filename>cron</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s an <emphasis>archiver</emphasis> (which may include a compression function):
</term>
<listitem>
<para>
<filename>tools/archivers</filename> (e.g. <filename>zip</filename>, <filename>tar</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>compression</emphasis> program:
</term>
<listitem>
<para>
<filename>tools/compression</filename> (e.g. <filename>gzip</filename>, <filename>bzip2</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>security</emphasis>-related program:
</term>
<listitem>
<para>
<filename>tools/security</filename> (e.g. <filename>nmap</filename>, <filename>gnupg</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
Else:
</term>
<listitem>
<para>
<filename>tools/misc</filename>
</para>
</listitem>
</varlistentry>
</variablelist>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>shell</emphasis>:
</term>
<listitem>
<para>
<filename>shells</filename> (e.g. <filename>bash</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>server</emphasis>:
</term>
<listitem>
<variablelist>
<varlistentry>
<term>
If it’s a web server:
</term>
<listitem>
<para>
<filename>servers/http</filename> (e.g. <filename>apache-httpd</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s an implementation of the X Windowing System:
</term>
<listitem>
<para>
<filename>servers/x11</filename> (e.g. <filename>xorg</filename> — this includes the client libraries and programs)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
Else:
</term>
<listitem>
<para>
<filename>servers/misc</filename>
</para>
</listitem>
</varlistentry>
</variablelist>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>desktop environment</emphasis>:
</term>
<listitem>
<para>
<filename>desktops</filename> (e.g. <filename>kde</filename>, <filename>gnome</filename>, <filename>enlightenment</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>window manager</emphasis>:
</term>
<listitem>
<para>
<filename>applications/window-managers</filename> (e.g. <filename>awesome</filename>, <filename>stumpwm</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s an <emphasis>application</emphasis>:
</term>
<listitem>
<para>
A (typically large) program with a distinct user interface, primarily used interactively.
</para>
<variablelist>
<varlistentry>
<term>
If it’s a <emphasis>version management system</emphasis>:
</term>
<listitem>
<para>
<filename>applications/version-management</filename> (e.g. <filename>subversion</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>terminal emulator</emphasis>:
</term>
<listitem>
<para>
<filename>applications/terminal-emulators</filename> (e.g. <filename>alacritty</filename> or <filename>rxvt</filename> or <filename>termite</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s for <emphasis>video playback / editing</emphasis>:
</term>
<listitem>
<para>
<filename>applications/video</filename> (e.g. <filename>vlc</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s for <emphasis>graphics viewing / editing</emphasis>:
</term>
<listitem>
<para>
<filename>applications/graphics</filename> (e.g. <filename>gimp</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s for <emphasis>networking</emphasis>:
</term>
<listitem>
<variablelist>
<varlistentry>
<term>
If it’s a <emphasis>mailreader</emphasis>:
</term>
<listitem>
<para>
<filename>applications/networking/mailreaders</filename> (e.g. <filename>thunderbird</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>newsreader</emphasis>:
</term>
<listitem>
<para>
<filename>applications/networking/newsreaders</filename> (e.g. <filename>pan</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>web browser</emphasis>:
</term>
<listitem>
<para>
<filename>applications/networking/browsers</filename> (e.g. <filename>firefox</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
Else:
</term>
<listitem>
<para>
<filename>applications/networking/misc</filename>
</para>
</listitem>
</varlistentry>
</variablelist>
</listitem>
</varlistentry>
<varlistentry>
<term>
Else:
</term>
<listitem>
<para>
<filename>applications/misc</filename>
</para>
</listitem>
</varlistentry>
</variablelist>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s <emphasis>data</emphasis> (i.e., does not have a straight-forward executable semantics):
</term>
<listitem>
<variablelist>
<varlistentry>
<term>
If it’s a <emphasis>font</emphasis>:
</term>
<listitem>
<para>
<filename>data/fonts</filename>
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s an <emphasis>icon theme</emphasis>:
</term>
<listitem>
<para>
<filename>data/icons</filename>
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s related to <emphasis>SGML/XML processing</emphasis>:
</term>
<listitem>
<variablelist>
<varlistentry>
<term>
If it’s an <emphasis>XML DTD</emphasis>:
</term>
<listitem>
<para>
<filename>data/sgml+xml/schemas/xml-dtd</filename> (e.g. <filename>docbook</filename>)
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s an <emphasis>XSLT stylesheet</emphasis>:
</term>
<listitem>
<para>
(Okay, these are executable...)
</para>
<para>
<filename>data/sgml+xml/stylesheets/xslt</filename> (e.g. <filename>docbook-xsl</filename>)
</para>
</listitem>
</varlistentry>
</variablelist>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>theme</emphasis> for a <emphasis>desktop environment</emphasis>,
a <emphasis>window manager</emphasis> or a <emphasis>display manager</emphasis>:
</term>
<listitem>
<para>
<filename>data/themes</filename>
</para>
</listitem>
</varlistentry>
</variablelist>
</listitem>
</varlistentry>
<varlistentry>
<term>
If it’s a <emphasis>game</emphasis>:
</term>
<listitem>
<para>
<filename>games</filename>
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
Else:
</term>
<listitem>
<para>
<filename>misc</filename>
</para>
</listitem>
</varlistentry>
</variablelist>
</section>
<section xml:id="sec-versioning">
<title>Versioning</title>
<para>
Because every version of a package in Nixpkgs creates a potential maintenance burden, old versions of a package should not be kept unless there is a good reason to do so. For instance, Nixpkgs contains several versions of GCC because other packages don’t build with the latest version of GCC. Other examples are having both the latest stable and latest pre-release version of a package, or to keep several major releases of an application that differ significantly in functionality.
</para>
<para>
If there is only one version of a package, its Nix expression should be named <filename>e2fsprogs/default.nix</filename>. If there are multiple versions, this should be reflected in the filename, e.g. <filename>e2fsprogs/1.41.8.nix</filename> and <filename>e2fsprogs/1.41.9.nix</filename>. The version in the filename should leave out unnecessary detail. For instance, if we keep the latest Firefox 2.0.x and 3.5.x versions in Nixpkgs, they should be named <filename>firefox/2.0.nix</filename> and <filename>firefox/3.5.nix</filename>, respectively (which, at a given point, might contain versions <literal>2.0.0.20</literal> and <literal>3.5.4</literal>). If a version requires many auxiliary files, you can use a subdirectory for each version, e.g. <filename>firefox/2.0/default.nix</filename> and <filename>firefox/3.5/default.nix</filename>.
</para>
<para>
All versions of a package <emphasis>must</emphasis> be included in <filename>all-packages.nix</filename> to make sure that they evaluate correctly.
</para>
</section>
</section>
<section xml:id="sec-sources">
<title>Fetching Sources</title>
<para>
There are multiple ways to fetch a package source in nixpkgs. The general guideline is that you should package reproducible sources with a high degree of availability. Right now there is only one fetcher which has mirroring support and that is <literal>fetchurl</literal>. Note that you should also prefer protocols which have a corresponding proxy environment variable.
</para>
<para>
You can find many source fetch helpers in <literal>pkgs/build-support/fetch*</literal>.
</para>
<para>
In the file <literal>pkgs/top-level/all-packages.nix</literal> you can find fetch helpers, these have names on the form <literal>fetchFrom*</literal>. The intention of these are to provide snapshot fetches but using the same api as some of the version controlled fetchers from <literal>pkgs/build-support/</literal>. As an example going from bad to good:
<itemizedlist>
<listitem>
<para>
Bad: Uses <literal>git://</literal> which won't be proxied.
<programlisting>
src = fetchgit {
url = "git://github.com/NixOS/nix.git";
rev = "1f795f9f44607cc5bec70d1300150bfefcef2aae";
sha256 = "1cw5fszffl5pkpa6s6wjnkiv6lm5k618s32sp60kvmvpy7a2v9kg";
}
</programlisting>
</para>
</listitem>
<listitem>
<para>
Better: This is ok, but an archive fetch will still be faster.
<programlisting>
src = fetchgit {
url = "https://github.com/NixOS/nix.git";
rev = "1f795f9f44607cc5bec70d1300150bfefcef2aae";
sha256 = "1cw5fszffl5pkpa6s6wjnkiv6lm5k618s32sp60kvmvpy7a2v9kg";
}
</programlisting>
</para>
</listitem>
<listitem>
<para>
Best: Fetches a snapshot archive and you get the rev you want.
<programlisting>
src = fetchFromGitHub {
owner = "NixOS";
repo = "nix";
rev = "1f795f9f44607cc5bec70d1300150bfefcef2aae";
sha256 = "1i2yxndxb6yc9l6c99pypbd92lfq5aac4klq7y2v93c9qvx2cgpc";
}
</programlisting>
Find the value to put as <literal>sha256</literal> by running <literal>nix run -f '&lt;nixpkgs&gt;' nix-prefetch-github -c nix-prefetch-github --rev 1f795f9f44607cc5bec70d1300150bfefcef2aae NixOS nix</literal> or <literal>nix-prefetch-url --unpack https://github.com/NixOS/nix/archive/1f795f9f44607cc5bec70d1300150bfefcef2aae.tar.gz</literal>.
</para>
</listitem>
</itemizedlist>
</para>
</section>
<section xml:id="sec-source-hashes">
<title>Obtaining source hash</title>
<para>
Preferred source hash type is sha256. There are several ways to get it.
</para>
<orderedlist>
<listitem>
<para>
Prefetch URL (with <literal>nix-prefetch-<replaceable>XXX</replaceable> <replaceable>URL</replaceable></literal>, where <replaceable>XXX</replaceable> is one of <literal>url</literal>, <literal>git</literal>, <literal>hg</literal>, <literal>cvs</literal>, <literal>bzr</literal>, <literal>svn</literal>). Hash is printed to stdout.
</para>
</listitem>
<listitem>
<para>
Prefetch by package source (with <literal>nix-prefetch-url '&lt;nixpkgs&gt;' -A <replaceable>PACKAGE</replaceable>.src</literal>, where <replaceable>PACKAGE</replaceable> is package attribute name). Hash is printed to stdout.
</para>
<para>
This works well when you've upgraded existing package version and want to find out new hash, but is useless if package can't be accessed by attribute or package has multiple sources (<literal>.srcs</literal>, architecture-dependent sources, etc).
</para>
</listitem>
<listitem>
<para>
Upstream provided hash: use it when upstream provides <literal>sha256</literal> or <literal>sha512</literal> (when upstream provides <literal>md5</literal>, don't use it, compute <literal>sha256</literal> instead).
</para>
<para>
A little nuance is that <literal>nix-prefetch-*</literal> tools produce hash encoded with <literal>base32</literal>, but upstream usually provides hexadecimal (<literal>base16</literal>) encoding. Fetchers understand both formats. Nixpkgs does not standardize on any one format.
</para>
<para>
You can convert between formats with nix-hash, for example:
<screen>
<prompt>$ </prompt>nix-hash --type sha256 --to-base32 <replaceable>HASH</replaceable>
</screen>
</para>
</listitem>
<listitem>
<para>
Extracting hash from local source tarball can be done with <literal>sha256sum</literal>. Use <literal>nix-prefetch-url file:///path/to/tarball </literal> if you want base32 hash.
</para>
</listitem>
<listitem>
<para>
Fake hash: set fake hash in package expression, perform build and extract correct hash from error Nix prints.
</para>
<para>
For package updates it is enough to change one symbol to make hash fake. For new packages, you can use <literal>lib.fakeSha256</literal>, <literal>lib.fakeSha512</literal> or any other fake hash.
</para>
<para>
This is last resort method when reconstructing source URL is non-trivial and <literal>nix-prefetch-url -A</literal> isn't applicable (for example, <link xlink:href="https://github.com/NixOS/nixpkgs/blob/d2ab091dd308b99e4912b805a5eb088dd536adb9/pkgs/applications/video/kodi/default.nix#L73"> one of <literal>kodi</literal> dependencies</link>). The easiest way then would be replace hash with a fake one and rebuild. Nix build will fail and error message will contain desired hash.
</para>
<warning>
<para>
This method has security problems. Check below for details.
</para>
</warning>
</listitem>
</orderedlist>
<section xml:id="sec-source-hashes-security">
<title>Obtaining hashes securely</title>
<para>
Let's say Man-in-the-Middle (MITM) sits close to your network. Then instead of fetching source you can fetch malware, and instead of source hash you get hash of malware. Here are security considerations for this scenario:
</para>
<itemizedlist>
<listitem>
<para>
<literal>http://</literal> URLs are not secure to prefetch hash from;
</para>
</listitem>
<listitem>
<para>
hashes from upstream (in method 3) should be obtained via secure protocol;
</para>
</listitem>
<listitem>
<para>
<literal>https://</literal> URLs are secure in methods 1, 2, 3;
</para>
</listitem>
<listitem>
<para>
<literal>https://</literal> URLs are not secure in method 5. When obtaining hashes with fake hash method, TLS checks are disabled. So refetch source hash from several different networks to exclude MITM scenario. Alternatively, use fake hash method to make Nix error, but instead of extracting hash from error, extract <literal>https://</literal> URL and prefetch it with method 1.
</para>
</listitem>
</itemizedlist>
</section>
</section>
<section xml:id="sec-patches">
<title>Patches</title>
<para>
Patches available online should be retrieved using <literal>fetchpatch</literal>.
</para>
<para>
<programlisting>
patches = [
(fetchpatch {
name = "fix-check-for-using-shared-freetype-lib.patch";
url = "http://git.ghostscript.com/?p=ghostpdl.git;a=patch;h=8f5d285";
sha256 = "1f0k043rng7f0rfl9hhb89qzvvksqmkrikmm38p61yfx51l325xr";
})
];
</programlisting>
</para>
<para>
Otherwise, you can add a <literal>.patch</literal> file to the <literal>nixpkgs</literal> repository. In the interest of keeping our maintenance burden to a minimum, only patches that are unique to <literal>nixpkgs</literal> should be added in this way.
</para>
<para>
<programlisting>
patches = [ ./0001-changes.patch ];
</programlisting>
</para>
<para>
If you do need to do create this sort of patch file, one way to do so is with git:
<orderedlist>
<listitem>
<para>
Move to the root directory of the source code you're patching.
<screen>
<prompt>$ </prompt>cd the/program/source</screen>
</para>
</listitem>
<listitem>
<para>
If a git repository is not already present, create one and stage all of the source files.
<screen>
<prompt>$ </prompt>git init
<prompt>$ </prompt>git add .</screen>
</para>
</listitem>
<listitem>
<para>
Edit some files to make whatever changes need to be included in the patch.
</para>
</listitem>
<listitem>
<para>
Use git to create a diff, and pipe the output to a patch file:
<screen>
<prompt>$ </prompt>git diff > nixpkgs/pkgs/the/package/0001-changes.patch</screen>
</para>
</listitem>
</orderedlist>
</para>
</section>
</chapter>

@ -0,0 +1,24 @@
# Contributing to this documentation {#chap-contributing}
The DocBook sources of the Nixpkgs manual are in the [doc](https://github.com/NixOS/nixpkgs/tree/master/doc) subdirectory of the Nixpkgs repository.
You can quickly check your edits with `make`:
```ShellSession
$ cd /path/to/nixpkgs/doc
$ nix-shell
[nix-shell]$ make $makeFlags
```
If you experience problems, run `make debug` to help understand the docbook errors.
After making modifications to the manual, it's important to build it before committing. You can do that as follows:
```ShellSession
$ cd /path/to/nixpkgs/doc
$ nix-shell
[nix-shell]$ make clean
[nix-shell]$ nix-build .
```
If the build succeeds, the manual will be in `./result/share/doc/nixpkgs/manual.html`.

@ -1,30 +0,0 @@
<chapter xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xml:id="chap-contributing">
<title>Contributing to this documentation</title>
<para>
The DocBook sources of the Nixpkgs manual are in the <filename
xlink:href="https://github.com/NixOS/nixpkgs/tree/master/doc">doc</filename> subdirectory of the Nixpkgs repository.
</para>
<para>
You can quickly check your edits with <command>make</command>:
</para>
<screen>
<prompt>$ </prompt>cd /path/to/nixpkgs/doc
<prompt>$ </prompt>nix-shell
<prompt>[nix-shell]$ </prompt>make $makeFlags
</screen>
<para>
If you experience problems, run <command>make debug</command> to help understand the docbook errors.
</para>
<para>
After making modifications to the manual, it's important to build it before committing. You can do that as follows:
<screen>
<prompt>$ </prompt>cd /path/to/nixpkgs/doc
<prompt>$ </prompt>nix-shell
<prompt>[nix-shell]$ </prompt>make clean
<prompt>[nix-shell]$ </prompt>nix-build .
</screen>
If the build succeeds, the manual will be in <filename>./result/share/doc/nixpkgs/manual.html</filename>.
</para>
</chapter>

@ -0,0 +1,77 @@
# Quick Start to Adding a Package {#chap-quick-start}
To add a package to Nixpkgs:
1. Checkout the Nixpkgs source tree:
```ShellSession
$ git clone https://github.com/NixOS/nixpkgs
$ cd nixpkgs
```
2. Find a good place in the Nixpkgs tree to add the Nix expression for your package. For instance, a library package typically goes into `pkgs/development/libraries/pkgname`, while a web browser goes into `pkgs/applications/networking/browsers/pkgname`. See <xref linkend="sec-organisation" /> for some hints on the tree organisation. Create a directory for your package, e.g.
```ShellSession
$ mkdir pkgs/development/libraries/libfoo
```
3. In the package directory, create a Nix expression — a piece of code that describes how to build the package. In this case, it should be a _function_ that is called with the package dependencies as arguments, and returns a build of the package in the Nix store. The expression should usually be called `default.nix`.
```ShellSession
$ emacs pkgs/development/libraries/libfoo/default.nix
$ git add pkgs/development/libraries/libfoo/default.nix
```
You can have a look at the existing Nix expressions under `pkgs/` to see how it’s done. Here are some good ones:
- GNU Hello: [`pkgs/applications/misc/hello/default.nix`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/misc/hello/default.nix). Trivial package, which specifies some `meta` attributes which is good practice.
- GNU cpio: [`pkgs/tools/archivers/cpio/default.nix`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/tools/archivers/cpio/default.nix). Also a simple package. The generic builder in `stdenv` does everything for you. It has no dependencies beyond `stdenv`.
- GNU Multiple Precision arithmetic library (GMP): [`pkgs/development/libraries/gmp/5.1.x.nix`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/libraries/gmp/5.1.x.nix). Also done by the generic builder, but has a dependency on `m4`.
- Pan, a GTK-based newsreader: [`pkgs/applications/networking/newsreaders/pan/default.nix`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/networking/newsreaders/pan/default.nix). Has an optional dependency on `gtkspell`, which is only built if `spellCheck` is `true`.
- Apache HTTPD: [`pkgs/servers/http/apache-httpd/2.4.nix`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/servers/http/apache-httpd/2.4.nix). A bunch of optional features, variable substitutions in the configure flags, a post-install hook, and miscellaneous hackery.
- Thunderbird: [`pkgs/applications/networking/mailreaders/thunderbird/default.nix`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/networking/mailreaders/thunderbird/default.nix). Lots of dependencies.
- JDiskReport, a Java utility: [`pkgs/tools/misc/jdiskreport/default.nix`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/tools/misc/jdiskreport/default.nix). Nixpkgs doesn’t have a decent `stdenv` for Java yet so this is pretty ad-hoc.
- XML::Simple, a Perl module: [`pkgs/top-level/perl-packages.nix`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/top-level/perl-packages.nix) (search for the `XMLSimple` attribute). Most Perl modules are so simple to build that they are defined directly in `perl-packages.nix`; no need to make a separate file for them.
- Adobe Reader: [`pkgs/applications/misc/adobe-reader/default.nix`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/misc/adobe-reader/default.nix). Shows how binary-only packages can be supported. In particular the [builder](https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/misc/adobe-reader/builder.sh) uses `patchelf` to set the RUNPATH and ELF interpreter of the executables so that the right libraries are found at runtime.
Some notes:
- All [`meta`](#chap-meta) attributes are optional, but it’s still a good idea to provide at least the `description`, `homepage` and [`license`](#sec-meta-license).
- You can use `nix-prefetch-url url` to get the SHA-256 hash of source distributions. There are similar commands as `nix-prefetch-git` and `nix-prefetch-hg` available in `nix-prefetch-scripts` package.
- A list of schemes for `mirror://` URLs can be found in [`pkgs/build-support/fetchurl/mirrors.nix`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/build-support/fetchurl/mirrors.nix).
The exact syntax and semantics of the Nix expression language, including the built-in function, are described in the Nix manual in the [chapter on writing Nix expressions](https://hydra.nixos.org/job/nix/trunk/tarball/latest/download-by-type/doc/manual/#chap-writing-nix-expressions).
4. Add a call to the function defined in the previous step to [`pkgs/top-level/all-packages.nix`](https://github.com/NixOS/nixpkgs/blob/master/pkgs/top-level/all-packages.nix) with some descriptive name for the variable, e.g. `libfoo`.
```ShellSession
$ emacs pkgs/top-level/all-packages.nix
```
The attributes in that file are sorted by category (like “Development / Libraries”) that more-or-less correspond to the directory structure of Nixpkgs, and then by attribute name.
5. To test whether the package builds, run the following command from the root of the nixpkgs source tree:
```ShellSession
$ nix-build -A libfoo
```
where `libfoo` should be the variable name defined in the previous step. You may want to add the flag `-K` to keep the temporary build directory in case something fails. If the build succeeds, a symlink `./result` to the package in the Nix store is created.
6. If you want to install the package into your profile (optional), do
```ShellSession
$ nix-env -f . -iA libfoo
```
7. Optionally commit the new package and open a pull request [to nixpkgs](https://github.com/NixOS/nixpkgs/pulls), or use [the Patches category](https://discourse.nixos.org/t/about-the-patches-category/477) on Discourse for sending a patch without a GitHub account.

@ -1,152 +0,0 @@
<chapter xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xml:id="chap-quick-start">
<title>Quick Start to Adding a Package</title>
<para>
To add a package to Nixpkgs:
<orderedlist>
<listitem>
<para>
Checkout the Nixpkgs source tree:
<screen>
<prompt>$ </prompt>git clone https://github.com/NixOS/nixpkgs
<prompt>$ </prompt>cd nixpkgs</screen>
</para>
</listitem>
<listitem>
<para>
Find a good place in the Nixpkgs tree to add the Nix expression for your package. For instance, a library package typically goes into <filename>pkgs/development/libraries/<replaceable>pkgname</replaceable></filename>, while a web browser goes into <filename>pkgs/applications/networking/browsers/<replaceable>pkgname</replaceable></filename>. See <xref linkend="sec-organisation" /> for some hints on the tree organisation. Create a directory for your package, e.g.
<screen>
<prompt>$ </prompt>mkdir pkgs/development/libraries/libfoo</screen>
</para>
</listitem>
<listitem>
<para>
In the package directory, create a Nix expression — a piece of code that describes how to build the package. In this case, it should be a <emphasis>function</emphasis> that is called with the package dependencies as arguments, and returns a build of the package in the Nix store. The expression should usually be called <filename>default.nix</filename>.
<screen>
<prompt>$ </prompt>emacs pkgs/development/libraries/libfoo/default.nix
<prompt>$ </prompt>git add pkgs/development/libraries/libfoo/default.nix</screen>
</para>
<para>
You can have a look at the existing Nix expressions under <filename>pkgs/</filename> to see how it’s done. Here are some good ones:
<itemizedlist>
<listitem>
<para>
GNU Hello: <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/misc/hello/default.nix"><filename>pkgs/applications/misc/hello/default.nix</filename></link>. Trivial package, which specifies some <varname>meta</varname> attributes which is good practice.
</para>
</listitem>
<listitem>
<para>
GNU cpio: <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/pkgs/tools/archivers/cpio/default.nix"><filename>pkgs/tools/archivers/cpio/default.nix</filename></link>. Also a simple package. The generic builder in <varname>stdenv</varname> does everything for you. It has no dependencies beyond <varname>stdenv</varname>.
</para>
</listitem>
<listitem>
<para>
GNU Multiple Precision arithmetic library (GMP): <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/pkgs/development/libraries/gmp/5.1.x.nix"><filename>pkgs/development/libraries/gmp/5.1.x.nix</filename></link>. Also done by the generic builder, but has a dependency on <varname>m4</varname>.
</para>
</listitem>
<listitem>
<para>
Pan, a GTK-based newsreader: <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/networking/newsreaders/pan/default.nix"><filename>pkgs/applications/networking/newsreaders/pan/default.nix</filename></link>. Has an optional dependency on <varname>gtkspell</varname>, which is only built if <varname>spellCheck</varname> is <literal>true</literal>.
</para>
</listitem>
<listitem>
<para>
Apache HTTPD: <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/pkgs/servers/http/apache-httpd/2.4.nix"><filename>pkgs/servers/http/apache-httpd/2.4.nix</filename></link>. A bunch of optional features, variable substitutions in the configure flags, a post-install hook, and miscellaneous hackery.
</para>
</listitem>
<listitem>
<para>
Thunderbird: <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/networking/mailreaders/thunderbird/default.nix"><filename>pkgs/applications/networking/mailreaders/thunderbird/default.nix</filename></link>. Lots of dependencies.
</para>
</listitem>
<listitem>
<para>
JDiskReport, a Java utility: <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/pkgs/tools/misc/jdiskreport/default.nix"><filename>pkgs/tools/misc/jdiskreport/default.nix</filename></link>. Nixpkgs doesn’t have a decent <varname>stdenv</varname> for Java yet so this is pretty ad-hoc.
</para>
</listitem>
<listitem>
<para>
XML::Simple, a Perl module: <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/pkgs/top-level/perl-packages.nix"><filename>pkgs/top-level/perl-packages.nix</filename></link> (search for the <varname>XMLSimple</varname> attribute). Most Perl modules are so simple to build that they are defined directly in <filename>perl-packages.nix</filename>; no need to make a separate file for them.
</para>
</listitem>
<listitem>
<para>
Adobe Reader: <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/misc/adobe-reader/default.nix"><filename>pkgs/applications/misc/adobe-reader/default.nix</filename></link>. Shows how binary-only packages can be supported. In particular the <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/pkgs/applications/misc/adobe-reader/builder.sh">builder</link> uses <command>patchelf</command> to set the RUNPATH and ELF interpreter of the executables so that the right libraries are found at runtime.
</para>
</listitem>
</itemizedlist>
</para>
<para>
Some notes:
<itemizedlist>
<listitem>
<para>
All <varname linkend="chap-meta">meta</varname> attributes are optional, but it’s still a good idea to provide at least the <varname>description</varname>, <varname>homepage</varname> and <varname
linkend="sec-meta-license">license</varname>.
</para>
</listitem>
<listitem>
<para>
You can use <command>nix-prefetch-url</command> <replaceable>url</replaceable> to get the SHA-256 hash of source distributions. There are similar commands as <command>nix-prefetch-git</command> and <command>nix-prefetch-hg</command> available in <literal>nix-prefetch-scripts</literal> package.
</para>
</listitem>
<listitem>
<para>
A list of schemes for <literal>mirror://</literal> URLs can be found in <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/pkgs/build-support/fetchurl/mirrors.nix"><filename>pkgs/build-support/fetchurl/mirrors.nix</filename></link>.
</para>
</listitem>
</itemizedlist>
</para>
<para>
The exact syntax and semantics of the Nix expression language, including the built-in function, are described in the Nix manual in the <link
xlink:href="https://hydra.nixos.org/job/nix/trunk/tarball/latest/download-by-type/doc/manual/#chap-writing-nix-expressions">chapter on writing Nix expressions</link>.
</para>
</listitem>
<listitem>
<para>
Add a call to the function defined in the previous step to <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/pkgs/top-level/all-packages.nix"><filename>pkgs/top-level/all-packages.nix</filename></link> with some descriptive name for the variable, e.g. <varname>libfoo</varname>.
<screen>
<prompt>$ </prompt>emacs pkgs/top-level/all-packages.nix</screen>
</para>
<para>
The attributes in that file are sorted by category (like “Development / Libraries”) that more-or-less correspond to the directory structure of Nixpkgs, and then by attribute name.
</para>
</listitem>
<listitem>
<para>
To test whether the package builds, run the following command from the root of the nixpkgs source tree:
<screen>
<prompt>$ </prompt>nix-build -A libfoo</screen>
where <varname>libfoo</varname> should be the variable name defined in the previous step. You may want to add the flag <option>-K</option> to keep the temporary build directory in case something fails. If the build succeeds, a symlink <filename>./result</filename> to the package in the Nix store is created.
</para>
</listitem>
<listitem>
<para>
If you want to install the package into your profile (optional), do
<screen>
<prompt>$ </prompt>nix-env -f . -iA libfoo</screen>
</para>
</listitem>
<listitem>
<para>
Optionally commit the new package and open a pull request <link
xlink:href="https://github.com/NixOS/nixpkgs/pulls">to nixpkgs</link>, or use <link
xlink:href="https://discourse.nixos.org/t/about-the-patches-category/477"> the Patches category</link> on Discourse for sending a patch without a GitHub account.
</para>
</listitem>
</orderedlist>
</para>
</chapter>

@ -0,0 +1,204 @@
# Reviewing contributions {#chap-reviewing-contributions}
::: warning
The following section is a draft, and the policy for reviewing is still being discussed in issues such as [#11166](https://github.com/NixOS/nixpkgs/issues/11166) and [#20836](https://github.com/NixOS/nixpkgs/issues/20836).
:::
The Nixpkgs project receives a fairly high number of contributions via GitHub pull requests. Reviewing and approving these is an important task and a way to contribute to the project.
The high change rate of Nixpkgs makes any pull request that remains open for too long subject to conflicts that will require extra work from the submitter or the merger. Reviewing pull requests in a timely manner and being responsive to the comments is the key to avoid this issue. GitHub provides sort filters that can be used to see the [most recently](https://github.com/NixOS/nixpkgs/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc) and the [least recently](https://github.com/NixOS/nixpkgs/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-asc) updated pull requests. We highly encourage looking at [this list of ready to merge, unreviewed pull requests](https://github.com/NixOS/nixpkgs/pulls?q=is%3Apr+is%3Aopen+review%3Anone+status%3Asuccess+-label%3A%222.status%3A+work-in-progress%22+no%3Aproject+no%3Aassignee+no%3Amilestone).
When reviewing a pull request, please always be nice and polite. Controversial changes can lead to controversial opinions, but it is important to respect every community member and their work.
GitHub provides reactions as a simple and quick way to provide feedback to pull requests or any comments. The thumb-down reaction should be used with care and if possible accompanied with some explanation so the submitter has directions to improve their contribution.
pull request reviews should include a list of what has been reviewed in a comment, so other reviewers and mergers can know the state of the review.
All the review template samples provided in this section are generic and meant as examples. Their usage is optional and the reviewer is free to adapt them to their liking.
## Package updates {#reviewing-contributions-package-updates}
A package update is the most trivial and common type of pull request. These pull requests mainly consist of updating the version part of the package name and the source hash.
It can happen that non-trivial updates include patches or more complex changes.
Reviewing process:
- Ensure that the package versioning fits the guidelines.
- Ensure that the commit text fits the guidelines.
- Ensure that the package maintainers are notified.
- [CODEOWNERS](https://help.github.com/articles/about-codeowners) will make GitHub notify users based on the submitted changes, but it can happen that it misses some of the package maintainers.
- Ensure that the meta field information is correct.
- License can change with version updates, so it should be checked to match the upstream license.
- If the package has no maintainer, a maintainer must be set. This can be the update submitter or a community member that accepts to take maintainership of the package.
- Ensure that the code contains no typos.
- Building the package locally.
- pull requests are often targeted to the master or staging branch, and building the pull request locally when it is submitted can trigger many source builds.
- It is possible to rebase the changes on nixos-unstable or nixpkgs-unstable for easier review by running the following commands from a nixpkgs clone.
```ShellSession
$ git fetch origin nixos-unstable
$ git fetch origin pull/PRNUMBER/head
$ git rebase --onto nixos-unstable BASEBRANCH FETCH_HEAD
```
- The first command fetches the nixos-unstable branch.
- The second command fetches the pull request changes, `PRNUMBER` is the number at the end of the pull request title and `BASEBRANCH` the base branch of the pull request.
- The third command rebases the pull request changes to the nixos-unstable branch.
- The [nixpkgs-review](https://github.com/Mic92/nixpkgs-review) tool can be used to review a pull request content in a single command. `PRNUMBER` should be replaced by the number at the end of the pull request title. You can also provide the full github pull request url.
```ShellSession
$ nix-shell -p nixpkgs-review --run "nixpkgs-review pr PRNUMBER"
```
- Running every binary.
Sample template for a package update review is provided below.
```markdown
##### Reviewed points
- [ ] package name fits guidelines
- [ ] package version fits guidelines
- [ ] package build on ARCHITECTURE
- [ ] executables tested on ARCHITECTURE
- [ ] all depending packages build
##### Possible improvements
##### Comments
```
## New packages {#reviewing-contributions-new-packages}
New packages are a common type of pull requests. These pull requests consists in adding a new nix-expression for a package.
Review process:
- Ensure that the package versioning fits the guidelines.
- Ensure that the commit name fits the guidelines.
- Ensure that the meta fields contain correct information.
- License must match the upstream license.
- Platforms should be set (or the package will not get binary substitutes).
- Maintainers must be set. This can be the package submitter or a community member that accepts taking up maintainership of the package.
- Report detected typos.
- Ensure the package source:
- Uses mirror URLs when available.
- Uses the most appropriate functions (e.g. packages from GitHub should use `fetchFromGitHub`).
- Building the package locally.
- Running every binary.
Sample template for a new package review is provided below.
```markdown
##### Reviewed points
- [ ] package path fits guidelines
- [ ] package name fits guidelines
- [ ] package version fits guidelines
- [ ] package build on ARCHITECTURE
- [ ] executables tested on ARCHITECTURE
- [ ] `meta.description` is set and fits guidelines
- [ ] `meta.license` fits upstream license
- [ ] `meta.platforms` is set
- [ ] `meta.maintainers` is set
- [ ] build time only dependencies are declared in `nativeBuildInputs`
- [ ] source is fetched using the appropriate function
- [ ] phases are respected
- [ ] patches that are remotely available are fetched with `fetchpatch`
##### Possible improvements
##### Comments
```
## Module updates {#reviewing-contributions-module-updates}
Module updates are submissions changing modules in some ways. These often contains changes to the options or introduce new options.
Reviewing process:
- Ensure that the module maintainers are notified.
- [CODEOWNERS](https://help.github.com/articles/about-codeowners/) will make GitHub notify users based on the submitted changes, but it can happen that it misses some of the package maintainers.
- Ensure that the module tests, if any, are succeeding.
- Ensure that the introduced options are correct.
- Type should be appropriate (string related types differs in their merging capabilities, `optionSet` and `string` types are deprecated).
- Description, default and example should be provided.
- Ensure that option changes are backward compatible.
- `mkRenamedOptionModule` and `mkAliasOptionModule` functions provide way to make option changes backward compatible.
- Ensure that removed options are declared with `mkRemovedOptionModule`
- Ensure that changes that are not backward compatible are mentioned in release notes.
- Ensure that documentations affected by the change is updated.
Sample template for a module update review is provided below.
```markdown
##### Reviewed points
- [ ] changes are backward compatible
- [ ] removed options are declared with `mkRemovedOptionModule`
- [ ] changes that are not backward compatible are documented in release notes
- [ ] module tests succeed on ARCHITECTURE
- [ ] options types are appropriate
- [ ] options description is set
- [ ] options example is provided
- [ ] documentation affected by the changes is updated
##### Possible improvements
##### Comments
```
## New modules {#reviewing-contributions-new-modules}
New modules submissions introduce a new module to NixOS.
Reviewing process:
- Ensure that the module tests, if any, are succeeding.
- Ensure that the introduced options are correct.
- Type should be appropriate (string related types differs in their merging capabilities, `optionSet` and `string` types are deprecated).
- Description, default and example should be provided.
- Ensure that module `meta` field is present
- Maintainers should be declared in `meta.maintainers`.
- Module documentation should be declared with `meta.doc`.
- Ensure that the module respect other modules functionality.
- For example, enabling a module should not open firewall ports by default.
Sample template for a new module review is provided below.
```markdown
##### Reviewed points
- [ ] module path fits the guidelines
- [ ] module tests succeed on ARCHITECTURE
- [ ] options have appropriate types
- [ ] options have default
- [ ] options have example
- [ ] options have descriptions
- [ ] No unneeded package is added to environment.systemPackages
- [ ] meta.maintainers is set
- [ ] module documentation is declared in meta.doc
##### Possible improvements
##### Comments
```
## Other submissions {#reviewing-contributions-other-submissions}
Other type of submissions requires different reviewing steps.
If you consider having enough knowledge and experience in a topic and would like to be a long-term reviewer for related submissions, please contact the current reviewers for that topic. They will give you information about the reviewing process. The main reviewers for a topic can be hard to find as there is no list, but checking past pull requests to see who reviewed or git-blaming the code to see who committed to that topic can give some hints.
Container system, boot system and library changes are some examples of the pull requests fitting this category.
## Merging pull requests {#reviewing-contributions--merging-pull-requests}
It is possible for community members that have enough knowledge and experience on a special topic to contribute by merging pull requests.
<!--
The following paragraphs about how to deal with unactive contributors is just a proposition and should be modified to what the community agrees to be the right policy.
Please note that contributors with commit rights unactive for more than three months will have their commit rights revoked.
-->
Please see the discussion in [GitHub nixpkgs issue #50105](https://github.com/NixOS/nixpkgs/issues/50105) for information on how to proceed to be granted this level of access.
In a case a contributor definitively leaves the Nix community, they should create an issue or post on [Discourse](https://discourse.nixos.org) with references of packages and modules they maintain so the maintainership can be taken over by other contributors.

@ -1,488 +0,0 @@
<chapter xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xmlns:xi="http://www.w3.org/2001/XInclude"
version="5.0"
xml:id="chap-reviewing-contributions">
<title>Reviewing contributions</title>
<warning>
<para>
The following section is a draft, and the policy for reviewing is still being discussed in issues such as <link
xlink:href="https://github.com/NixOS/nixpkgs/issues/11166">#11166 </link> and <link
xlink:href="https://github.com/NixOS/nixpkgs/issues/20836">#20836 </link>.
</para>
</warning>
<para>
The Nixpkgs project receives a fairly high number of contributions via GitHub pull requests. Reviewing and approving these is an important task and a way to contribute to the project.
</para>
<para>
The high change rate of Nixpkgs makes any pull request that remains open for too long subject to conflicts that will require extra work from the submitter or the merger. Reviewing pull requests in a timely manner and being responsive to the comments is the key to avoid this issue. GitHub provides sort filters that can be used to see the <link
xlink:href="https://github.com/NixOS/nixpkgs/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-desc">most recently</link> and the <link
xlink:href="https://github.com/NixOS/nixpkgs/pulls?q=is%3Apr+is%3Aopen+sort%3Aupdated-asc">least recently</link> updated pull requests. We highly encourage looking at <link xlink:href="https://github.com/NixOS/nixpkgs/pulls?q=is%3Apr+is%3Aopen+review%3Anone+status%3Asuccess+-label%3A%222.status%3A+work-in-progress%22+no%3Aproject+no%3Aassignee+no%3Amilestone"> this list of ready to merge, unreviewed pull requests</link>.
</para>
<para>
When reviewing a pull request, please always be nice and polite. Controversial changes can lead to controversial opinions, but it is important to respect every community member and their work.
</para>
<para>
GitHub provides reactions as a simple and quick way to provide feedback to pull requests or any comments. The thumb-down reaction should be used with care and if possible accompanied with some explanation so the submitter has directions to improve their contribution.
</para>
<para>
pull request reviews should include a list of what has been reviewed in a comment, so other reviewers and mergers can know the state of the review.
</para>
<para>
All the review template samples provided in this section are generic and meant as examples. Their usage is optional and the reviewer is free to adapt them to their liking.
</para>
<section xml:id="reviewing-contributions-package-updates">
<title>Package updates</title>
<para>
A package update is the most trivial and common type of pull request. These pull requests mainly consist of updating the version part of the package name and the source hash.
</para>
<para>
It can happen that non-trivial updates include patches or more complex changes.
</para>
<para>
Reviewing process:
</para>
<itemizedlist>
<listitem>
<para>
Ensure that the package versioning fits the guidelines.
</para>
</listitem>
<listitem>
<para>
Ensure that the commit text fits the guidelines.
</para>
</listitem>
<listitem>
<para>
Ensure that the package maintainers are notified.
</para>
<itemizedlist>
<listitem>
<para>
<link xlink:href="https://help.github.com/articles/about-codeowners/">CODEOWNERS</link> will make GitHub notify users based on the submitted changes, but it can happen that it misses some of the package maintainers.
</para>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<para>
Ensure that the meta field information is correct.
</para>
<itemizedlist>
<listitem>
<para>
License can change with version updates, so it should be checked to match the upstream license.
</para>
</listitem>
<listitem>
<para>
If the package has no maintainer, a maintainer must be set. This can be the update submitter or a community member that accepts to take maintainership of the package.
</para>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<para>
Ensure that the code contains no typos.
</para>
</listitem>
<listitem>
<para>
Building the package locally.
</para>
<itemizedlist>
<listitem>
<para>
pull requests are often targeted to the master or staging branch, and building the pull request locally when it is submitted can trigger many source builds.
</para>
<para>
It is possible to rebase the changes on nixos-unstable or nixpkgs-unstable for easier review by running the following commands from a nixpkgs clone.
<screen>
<prompt>$ </prompt>git fetch origin nixos-unstable <co xml:id='reviewing-rebase-2' />
<prompt>$ </prompt>git fetch origin pull/PRNUMBER/head <co xml:id='reviewing-rebase-3' />
<prompt>$ </prompt>git rebase --onto nixos-unstable BASEBRANCH FETCH_HEAD <co
xml:id='reviewing-rebase-4' />
</screen>
<calloutlist>
<callout arearefs='reviewing-rebase-2'>
<para>
Fetching the nixos-unstable branch.
</para>
</callout>
<callout arearefs='reviewing-rebase-3'>
<para>
Fetching the pull request changes, <varname>PRNUMBER</varname> is the number at the end of the pull request title and <varname>BASEBRANCH</varname> the base branch of the pull request.
</para>
</callout>
<callout arearefs='reviewing-rebase-4'>
<para>
Rebasing the pull request changes to the nixos-unstable branch.
</para>
</callout>
</calloutlist>
</para>
</listitem>
<listitem>
<para>
The <link xlink:href="https://github.com/Mic92/nixpkgs-review">nixpkgs-review</link> tool can be used to review a pull request content in a single command. <varname>PRNUMBER</varname> should be replaced by the number at the end of the pull request title. You can also provide the full github pull request url.
</para>
<screen>
<prompt>$ </prompt>nix-shell -p nixpkgs-review --run "nixpkgs-review pr PRNUMBER"
</screen>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<para>
Running every binary.
</para>
</listitem>
</itemizedlist>
<example xml:id="reviewing-contributions-sample-package-update">
<title>Sample template for a package update review</title>
<screen>
##### Reviewed points
- [ ] package name fits guidelines
- [ ] package version fits guidelines
- [ ] package build on ARCHITECTURE
- [ ] executables tested on ARCHITECTURE
- [ ] all depending packages build
##### Possible improvements
##### Comments
</screen>
</example>
</section>
<section xml:id="reviewing-contributions-new-packages">
<title>New packages</title>
<para>
New packages are a common type of pull requests. These pull requests consists in adding a new nix-expression for a package.
</para>
<para>
Reviewing process:
</para>
<itemizedlist>
<listitem>
<para>
Ensure that the package versioning is fitting the guidelines.
</para>
</listitem>
<listitem>
<para>
Ensure that the commit name is fitting the guidelines.
</para>
</listitem>
<listitem>
<para>
Ensure that the meta field contains correct information.
</para>
<itemizedlist>
<listitem>
<para>
License must be checked to be fitting upstream license.
</para>
</listitem>
<listitem>
<para>
Platforms should be set or the package will not get binary substitutes.
</para>
</listitem>
<listitem>
<para>
A maintainer must be set. This can be the package submitter or a community member that accepts to take maintainership of the package.
</para>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<para>
Ensure that the code contains no typos.
</para>
</listitem>
<listitem>
<para>
Ensure the package source.
</para>
<itemizedlist>
<listitem>
<para>
Mirrors urls should be used when available.
</para>
</listitem>
<listitem>
<para>
The most appropriate function should be used (e.g. packages from GitHub should use <literal>fetchFromGitHub</literal>).
</para>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<para>
Building the package locally.
</para>
</listitem>
<listitem>
<para>
Running every binary.
</para>
</listitem>
</itemizedlist>
<example xml:id="reviewing-contributions-sample-new-package">
<title>Sample template for a new package review</title>
<screen>
##### Reviewed points
- [ ] package path fits guidelines
- [ ] package name fits guidelines
- [ ] package version fits guidelines
- [ ] package build on ARCHITECTURE
- [ ] executables tested on ARCHITECTURE
- [ ] `meta.description` is set and fits guidelines
- [ ] `meta.license` fits upstream license
- [ ] `meta.platforms` is set
- [ ] `meta.maintainers` is set
- [ ] build time only dependencies are declared in `nativeBuildInputs`
- [ ] source is fetched using the appropriate function
- [ ] phases are respected
- [ ] patches that are remotely available are fetched with `fetchpatch`
##### Possible improvements
##### Comments
</screen>
</example>
</section>
<section xml:id="reviewing-contributions-module-updates">
<title>Module updates</title>
<para>
Module updates are submissions changing modules in some ways. These often contains changes to the options or introduce new options.
</para>
<para>
Reviewing process
</para>
<itemizedlist>
<listitem>
<para>
Ensure that the module maintainers are notified.
</para>
<itemizedlist>
<listitem>
<para>
<link xlink:href="https://help.github.com/articles/about-codeowners/">CODEOWNERS</link> will make GitHub notify users based on the submitted changes, but it can happen that it misses some of the package maintainers.
</para>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<para>
Ensure that the module tests, if any, are succeeding.
</para>
</listitem>
<listitem>
<para>
Ensure that the introduced options are correct.
</para>
<itemizedlist>
<listitem>
<para>
Type should be appropriate (string related types differs in their merging capabilities, <literal>optionSet</literal> and <literal>string</literal> types are deprecated).
</para>
</listitem>
<listitem>
<para>
Description, default and example should be provided.
</para>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<para>
Ensure that option changes are backward compatible.
</para>
<itemizedlist>
<listitem>
<para>
<literal>mkRenamedOptionModule</literal> and <literal>mkAliasOptionModule</literal> functions provide way to make option changes backward compatible.
</para>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<para>
Ensure that removed options are declared with <literal>mkRemovedOptionModule</literal>
</para>
</listitem>
<listitem>
<para>
Ensure that changes that are not backward compatible are mentioned in release notes.
</para>
</listitem>
<listitem>
<para>
Ensure that documentations affected by the change is updated.
</para>
</listitem>
</itemizedlist>
<example xml:id="reviewing-contributions-sample-module-update">
<title>Sample template for a module update review</title>
<screen>
##### Reviewed points
- [ ] changes are backward compatible
- [ ] removed options are declared with `mkRemovedOptionModule`
- [ ] changes that are not backward compatible are documented in release notes
- [ ] module tests succeed on ARCHITECTURE
- [ ] options types are appropriate
- [ ] options description is set
- [ ] options example is provided
- [ ] documentation affected by the changes is updated
##### Possible improvements
##### Comments
</screen>
</example>
</section>
<section xml:id="reviewing-contributions-new-modules">
<title>New modules</title>
<para>
New modules submissions introduce a new module to NixOS.
</para>
<itemizedlist>
<listitem>
<para>
Ensure that the module tests, if any, are succeeding.
</para>
</listitem>
<listitem>
<para>
Ensure that the introduced options are correct.
</para>
<itemizedlist>
<listitem>
<para>
Type should be appropriate (string related types differs in their merging capabilities, <literal>optionSet</literal> and <literal>string</literal> types are deprecated).
</para>
</listitem>
<listitem>
<para>
Description, default and example should be provided.
</para>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<para>
Ensure that module <literal>meta</literal> field is present
</para>
<itemizedlist>
<listitem>
<para>
Maintainers should be declared in <literal>meta.maintainers</literal>.
</para>
</listitem>
<listitem>
<para>
Module documentation should be declared with <literal>meta.doc</literal>.
</para>
</listitem>
</itemizedlist>
</listitem>
<listitem>
<para>
Ensure that the module respect other modules functionality.
</para>
<itemizedlist>
<listitem>
<para>
For example, enabling a module should not open firewall ports by default.
</para>
</listitem>
</itemizedlist>
</listitem>
</itemizedlist>
<example xml:id="reviewing-contributions-sample-new-module">
<title>Sample template for a new module review</title>
<screen>
##### Reviewed points
- [ ] module path fits the guidelines
- [ ] module tests succeed on ARCHITECTURE
- [ ] options have appropriate types
- [ ] options have default
- [ ] options have example
- [ ] options have descriptions
- [ ] No unneeded package is added to environment.systemPackages
- [ ] meta.maintainers is set
- [ ] module documentation is declared in meta.doc
##### Possible improvements
##### Comments
</screen>
</example>
</section>
<section xml:id="reviewing-contributions-other-submissions">
<title>Other submissions</title>
<para>
Other type of submissions requires different reviewing steps.
</para>
<para>
If you consider having enough knowledge and experience in a topic and would like to be a long-term reviewer for related submissions, please contact the current reviewers for that topic. They will give you information about the reviewing process. The main reviewers for a topic can be hard to find as there is no list, but checking past pull requests to see who reviewed or git-blaming the code to see who committed to that topic can give some hints.
</para>
<para>
Container system, boot system and library changes are some examples of the pull requests fitting this category.
</para>
</section>
<section xml:id="reviewing-contributions--merging-pull-requests">
<title>Merging pull requests</title>
<para>
It is possible for community members that have enough knowledge and experience on a special topic to contribute by merging pull requests.
</para>
<!--
The following paragraphs about how to deal with unactive contributors is just a
proposition and should be modified to what the community agrees to be the right
policy.
<para>Please note that contributors with commit rights unactive for more than
three months will have their commit rights revoked.</para>
-->
<para>
Please see the discussion in <link xlink:href="https://github.com/NixOS/nixpkgs/issues/50105">GitHub nixpkgs issue #50105</link> for information on how to proceed to be granted this level of access.
</para>
<para>
In a case a contributor definitively leaves the Nix community, they should create an issue or post on <link
xlink:href="https://discourse.nixos.org">Discourse</link> with references of packages and modules they maintain so the maintainership can be taken over by other contributors.
</para>
</section>
</chapter>

@ -68,20 +68,67 @@
Security fixes are submitted in the same way as other changes and thus the same guidelines apply.
If the security fix comes in the form of a patch and a CVE is available, then the name of the patch should be the CVE identifier, so e.g. `CVE-2019-13636.patch` in the case of a patch that is included in the Nixpkgs tree. If a patch is fetched the name needs to be set as well, e.g.:
```nix
(fetchpatch {
name = "CVE-2019-11068.patch";
url = "https://gitlab.gnome.org/GNOME/libxslt/commit/e03553605b45c88f0b4b2980adfbbb8f6fca2fd6.patch";
sha256 = "0pkpb4837km15zgg6h57bncp66d5lwrlvkr73h0lanywq7zrwhj8";
})
```
- If a new version fixing the vulnerability has been released, update the package;
- If the security fix comes in the form of a patch and a CVE is available, then add the patch to the Nixpkgs tree, and apply it to the package.
The name of the patch should be the CVE identifier, so e.g. `CVE-2019-13636.patch`; If a patch is fetched the name needs to be set as well, e.g.:
```nix
(fetchpatch {
name = "CVE-2019-11068.patch";
url = "https://gitlab.gnome.org/GNOME/libxslt/commit/e03553605b45c88f0b4b2980adfbbb8f6fca2fd6.patch";
sha256 = "0pkpb4837km15zgg6h57bncp66d5lwrlvkr73h0lanywq7zrwhj8";
})
```
If a security fix applies to both master and a stable release then, similar to regular changes, they are preferably delivered via master first and cherry-picked to the release branch.
Critical security fixes may by-pass the staging branches and be delivered directly to release branches such as `master` and `release-*`.
## Deprecating/removing packages {#submitting-changes-deprecating-packages}
There is currently no policy when to remove a package.
Before removing a package, one should try to find a new maintainer or fix smaller issues first.
### Steps to remove a package from Nixpkgs
We use jbidwatcher as an example for a discontinued project here.
1. Have Nixpkgs checked out locally and up to date.
1. Create a new branch for your change, e.g. `git checkout -b jbidwatcher`
1. Remove the actual package including its directory, e.g. `rm -rf pkgs/applications/misc/jbidwatcher`
1. Remove the package from the list of all packages (`pkgs/top-level/all-packages.nix`).
1. Add an alias for the package name in `pkgs/top-level/aliases.nix` (There is also `pkgs/misc/vim-plugins/aliases.nix`. Package sets typically do not have aliases, so we can't add them there.)
For example in this case:
```
jbidwatcher = throw "jbidwatcher was discontinued in march 2021"; # added 2021-03-15
```
The throw message should explain in short why the package was removed for users that still have it installed.
1. Test if the changes introduced any issues by running `nix-env -qaP -f . --show-trace`. It should show the list of packages without errors.
1. Commit the changes. Explain again why the package was removed. If it was declared discontinued upstream, add a link to the source.
```ShellSession
$ git add pkgs/applications/misc/jbidwatcher/default.nix pkgs/top-level/all-packages.nix pkgs/top-level/aliases.nix
$ git commit
```
Example commit message:
```
jbidwatcher: remove
project was discontinued in march 2021. the program does not work anymore because ebay changed the login.
https://web.archive.org/web/20210315205723/http://www.jbidwatcher.com/
```
1. Push changes to your GitHub fork with `git push`
1. Create a pull request against Nixpkgs. Mention the package maintainer.
This is how the pull request looks like in this case: [https://github.com/NixOS/nixpkgs/pull/116470](https://github.com/NixOS/nixpkgs/pull/116470)
## Pull Request Template {#submitting-changes-pull-request-template}
The pull request template helps determine what steps have been made for a contribution so far, and will help guide maintainers on the status of a change. The motivation section of the PR should include any extra details the title does not address and link any existing issues related to the pull request.
@ -114,7 +161,7 @@ Many Nix packages are designed to run on multiple platforms. As such, it’s imp
### Tested via one or more NixOS test(s) if existing and applicable for the change (look inside nixos/tests) {#submitting-changes-nixos-tests}
Packages with automated tests are much more likely to be merged in a timely fashion because it doesn’t require as much manual testing by the maintainer to verify the functionality of the package. If there are existing tests for the package, they should be run to verify your changes do not break the tests. Tests only apply to packages with NixOS modules defined and can only be run on Linux. For more details on writing and running tests, see the [section in the NixOS manual](https://nixos.org/nixos/manual/index.html#sec-nixos-tests).
Packages with automated tests are much more likely to be merged in a timely fashion because it doesn’t require as much manual testing by the maintainer to verify the functionality of the package. If there are existing tests for the package, they should be run to verify your changes do not break the tests. Tests can only be run on Linux. For more details on writing and running tests, see the [section in the NixOS manual](https://nixos.org/nixos/manual/index.html#sec-nixos-tests).
### Tested compilation of all pkgs that depend on this change using `nixpkgs-review` {#submitting-changes-tested-compilation}

@ -0,0 +1,45 @@
# Vulnerability Roundup {#chap-vulnerability-roundup}
## Issues {#vulnerability-roundup-issues}
Vulnerable packages in Nixpkgs are managed using issues.
Currently opened ones can be found using the following:
[github.com/NixOS/nixpkgs/issues?q=is:issue+is:open+"Vulnerability+roundup"](https://github.com/NixOS/nixpkgs/issues?q=is%3Aissue+is%3Aopen+%22Vulnerability+roundup%22)
Each issue correspond to a vulnerable version of a package; As a consequence:
- One issue can contain several CVEs;
- One CVE can be shared across several issues;
- A single package can be concerned by several issues.
A "Vulnerability roundup" issue usually respects the following format:
```txt
<link to relevant package search on search.nix.gsc.io>, <link to relevant files in Nixpkgs on GitHub>
<list of related CVEs, their CVSS score, and the impacted NixOS version>
<list of the scanned Nixpkgs versions>
<list of relevant contributors>
```
Note that there can be an extra comment containing links to previously reported (and still open) issues for the same package.
## Triaging and Fixing {#vulnerability-roundup-triaging-and-fixing}
**Note**: An issue can be a "false positive" (i.e. automatically opened, but without the package it refers to being actually vulnerable).
If you find such a "false positive", comment on the issue an explanation of why it falls into this category, linking as much information as the necessary to help maintainers double check.
If you are investigating a "true positive":
- Find the earliest patched version or a code patch in the CVE details;
- Is the issue already patched (version up-to-date or patch applied manually) in Nixpkgs's `master` branch?
- **No**:
- [Submit a security fix](#submitting-changes-submitting-security-fixes);
- Once the fix is merged into `master`, [submit the change to the vulnerable release branch(es)](https://nixos.org/manual/nixpkgs/stable/#submitting-changes-stable-release-branches);
- **Yes**: [Backport the change to the vulnerable release branch(es)](https://nixos.org/manual/nixpkgs/stable/#submitting-changes-stable-release-branches).
- When the patch has made it into all the relevant branches (`master`, and the vulnerable releases), close the relevant issue(s).

@ -7,7 +7,7 @@
<section xml:id="function-library-lib.attrsets.attrByPath">
<title><function>lib.attrset.attrByPath</function></title>
<subtitle><literal>attrByPath :: [String] -> Any -> AttrSet</literal>
<subtitle><literal>attrByPath :: [String] -> Any -> AttrSet -> Any</literal>
</subtitle>
<xi:include href="./locations.xml" xpointer="lib.attrsets.attrByPath" />
@ -1677,8 +1677,7 @@ recursiveUpdate
<xi:include href="./locations.xml" xpointer="lib.attrsets.recurseIntoAttrs" />
<para>
Make various Nix tools consider the contents of the resulting
attribute set when looking for what to build, find, etc.
Make various Nix tools consider the contents of the resulting attribute set when looking for what to build, find, etc.
</para>
<para>
@ -1720,7 +1719,7 @@ recursiveUpdate
<xi:include href="./locations.xml" xpointer="lib.attrsets.cartesianProductOfSets" />
<para>
Return the cartesian product of attribute set value combinations.
Return the cartesian product of attribute set value combinations.
</para>
<variablelist>
@ -1749,5 +1748,4 @@ cartesianProductOfSets { a = [ 1 2 ]; b = [ 10 20 ]; }
]]></programlisting>
</example>
</section>
</section>

@ -2,37 +2,97 @@
## How to use Agda
Agda can be installed from `agda`:
```
$ nix-env -iA agda
```
Agda is available as the [agda](https://search.nixos.org/packages?channel=unstable&show=agda&from=0&size=30&sort=relevance&query=agda)
package.
To use Agda with libraries, the `agda.withPackages` function can be used. This function either takes:
The `agda` package installs an Agda-wrapper, which calls `agda` with `--library-file`
set to a generated library-file within the nix store, this means your library-file in
`$HOME/.agda/libraries` will be ignored. By default the agda package installs Agda
with no libraries, i.e. the generated library-file is empty. To use Agda with libraries,
the `agda.withPackages` function can be used. This function either takes:
* A list of packages,
* or a function which returns a list of packages when given the `agdaPackages` attribute set,
* or an attribute set containing a list of packages and a GHC derivation for compilation (see below).
* or an attribute set containing a function which returns a list of packages when given the `agdaPackages` attribute set and a GHC derivation for compilation (see below).
For example, suppose we wanted a version of Agda which has access to the standard library. This can be obtained with the expressions:
```
```nix
agda.withPackages [ agdaPackages.standard-library ]
```
or
```
```nix
agda.withPackages (p: [ p.standard-library ])
```
or can be called as in the [Compiling Agda](#compiling-agda) section.
If you want to use a library in your home directory (for instance if it is a development version) then typecheck it manually (using `agda.withPackages` if necessary) and then override the `src` attribute of the package to point to your local repository.
Agda will not by default use these libraries. To tell Agda to use the library we have some options:
If you want to use a different version of a library (for instance a development version)
override the `src` attribute of the package to point to your local repository
```nix
agda.withPackages (p: [
(p.standard-library.overrideAttrs (oldAttrs: {
version = "local version";
src = /path/to/local/repo/agda-stdlib;
}))
])
```
You can also reference a GitHub repository
```nix
agda.withPackages (p: [
(p.standard-library.overrideAttrs (oldAttrs: {
version = "1.5";
src = fetchFromGitHub {
repo = "agda-stdlib";
owner = "agda";
rev = "v1.5";
sha256 = "16fcb7ssj6kj687a042afaa2gq48rc8abihpm14k684ncihb2k4w";
};
}))
])
```
If you want to use a library not added to Nixpkgs, you can add a
dependency to a local library by calling `agdaPackages.mkDerivation`.
```nix
agda.withPackages (p: [
(p.mkDerivation {
pname = "your-agda-lib";
version = "1.0.0";
src = /path/to/your-agda-lib;
})
])
```
Again you can reference GitHub
```nix
agda.withPackages (p: [
(p.mkDerivation {
pname = "your-agda-lib";
version = "1.0.0";
src = fetchFromGitHub {
repo = "repo";
owner = "owner";
version = "...";
rev = "...";
sha256 = "...";
};
})
])
```
See [Building Agda Packages](#building-agda-packages) for more information on `mkDerivation`.
Agda will not by default use these libraries. To tell Agda to use a library we have some options:
* Call `agda` with the library flag:
```
```ShellSession
$ agda -l standard-library -i . MyFile.agda
```
* Write a `my-library.agda-lib` file for the project you are working on which may look like:
@ -46,10 +106,10 @@ depend: standard-library
More information can be found in the [official Agda documentation on library management](https://agda.readthedocs.io/en/v2.6.1/tools/package-system.html).
## Compiling Agda
Agda modules can be compiled with the `--compile` flag. A version of `ghc` with `ieee754` is made available to the Agda program via the `--with-compiler` flag.
Agda modules can be compiled using the GHC backend with the `--compile` flag. A version of `ghc` with `ieee754` is made available to the Agda program via the `--with-compiler` flag.
This can be overridden by a different version of `ghc` as follows:
```
```nix
agda.withPackages {
pkgs = [ ... ];
ghc = haskell.compiler.ghcHEAD;
@ -65,6 +125,21 @@ A derivation can then be written using `agdaPackages.mkDerivation`. This has sim
* `libraryName` should be the name that appears in the `*.agda-lib` file, defaulting to `pname`.
* `libraryFile` should be the file name of the `*.agda-lib` file, defaulting to `${libraryName}.agda-lib`.
Here is an example `default.nix`
```nix
{ nixpkgs ? <nixpkgs> }:
with (import nixpkgs {});
agdaPackages.mkDerivation {
version = "1.0";
pname = "my-agda-lib";
src = ./.;
buildInputs = [
agdaPackages.standard-library
];
}
```
### Building Agda packages
The default build phase for `agdaPackages.mkDerivation` simply runs `agda` on the `Everything.agda` file.
If something else is needed to build the package (e.g. `make`) then the `buildPhase` should be overridden.
@ -80,12 +155,18 @@ By default, Agda sources are files ending on `.agda`, or literate Agda files end
## Adding Agda packages to Nixpkgs
To add an Agda package to `nixpkgs`, the derivation should be written to `pkgs/development/libraries/agda/${library-name}/` and an entry should be added to `pkgs/top-level/agda-packages.nix`. Here it is called in a scope with access to all other Agda libraries, so the top line of the `default.nix` can look like:
```
```nix
{ mkDerivation, standard-library, fetchFromGitHub }:
```
and `mkDerivation` should be called instead of `agdaPackages.mkDerivation`. Here is an example skeleton derivation for iowa-stdlib:
```
Note that the derivation function is called with `mkDerivation` set to `agdaPackages.mkDerivation`, therefore you
could use a similar set as in your `default.nix` from [Writing Agda Packages](#writing-agda-packages) with
`agdaPackages.mkDerivation` replaced with `mkDerivation`.
Here is an example skeleton derivation for iowa-stdlib:
```nix
mkDerivation {
version = "1.5.0";
pname = "iowa-stdlib";

@ -25,7 +25,7 @@ let
abiVersions = [ "armeabi-v7a" "arm64-v8a" ];
cmakeVersions = [ "3.10.2" ];
includeNDK = true;
ndkVersion = "22.0.7026061";
ndkVersions = ["22.0.7026061"];
useGoogleAPIs = false;
useGoogleTVAddOns = false;
includeExtras = [
@ -52,7 +52,11 @@ The following parameters are supported:
* `cmakeVersions` specifies which CMake versions should be deployed.
* `includeNDK` specifies that the Android NDK bundle should be included.
Defaults to: `false`.
* `ndkVersion` specifies the NDK version that we want to use.
* `ndkVersions` specifies the NDK versions that we want to use. These are linked
under the `ndk` directory of the SDK root, and the first is linked under the
`ndk-bundle` directory.
* `ndkVersion` is equivalent to specifying one entry in `ndkVersions`, and
`ndkVersions` overrides this parameter if provided.
* `includeExtras` is an array of identifier strings referring to arbitrary
add-on packages that should be installed.
* `platformVersions` specifies which platform SDK versions should be included.
@ -80,7 +84,7 @@ Most of the function arguments have reasonable default settings.
You can specify license names:
* `extraLicenses` is a list of of license names.
* `extraLicenses` is a list of license names.
You can get these names from repo.json or `querypackages.sh licenses`. The SDK
license (`android-sdk-license`) is accepted for you if you set accept_license
to true. If you are doing something like working with preview SDKs, you will

@ -2,15 +2,15 @@
## Introduction {#beam-introduction}
In this document and related Nix expressions, we use the term, *BEAM*, to describe the environment. BEAM is the name of the Erlang Virtual Machine and, as far as we're concerned, from a packaging perspective, all languages that run on the BEAM are interchangeable. That which varies, like the build system, is transparent to users of any given BEAM package, so we make no distinction.
In this document and related Nix expressions, we use the term, _BEAM_, to describe the environment. BEAM is the name of the Erlang Virtual Machine and, as far as we're concerned, from a packaging perspective, all languages that run on the BEAM are interchangeable. That which varies, like the build system, is transparent to users of any given BEAM package, so we make no distinction.
## Structure {#beam-structure}
All BEAM-related expressions are available via the top-level `beam` attribute, which includes:
- `interpreters`: a set of compilers running on the BEAM, including multiple Erlang/OTP versions (`beam.interpreters.erlangR19`, etc), Elixir (`beam.interpreters.elixir`) and LFE (`beam.interpreters.lfe`).
- `interpreters`: a set of compilers running on the BEAM, including multiple Erlang/OTP versions (`beam.interpreters.erlangR19`, etc), Elixir (`beam.interpreters.elixir`) and LFE (Lisp Flavoured Erlang) (`beam.interpreters.lfe`).
- `packages`: a set of package builders (Mix and rebar3), each compiled with a specific Erlang/OTP version, e.g. `beam.packages.erlangR19`.
- `packages`: a set of package builders (Mix and rebar3), each compiled with a specific Erlang/OTP version, e.g. `beam.packages.erlangR19`.
The default Erlang compiler, defined by `beam.interpreters.erlang`, is aliased as `erlang`. The default BEAM package set is defined by `beam.packages.erlang` and aliased at the top level as `beamPackages`.
@ -26,7 +26,9 @@ We provide a version of Rebar3, under `rebar3`. We also provide a helper to fetc
### Mix & Erlang.mk {#build-tools-other}
Both Mix and Erlang.mk work exactly as expected. There is a bootstrap process that needs to be run for both, however, which is supported by the `buildMix` and `buildErlangMk` derivations, respectively.
Erlang.mk works exactly as expected. There is a bootstrap process that needs to be run, which is supported by the `buildErlangMk` derivation.
For Elixir applications use `mixRelease` to make a release. See examples for more details.
## How to Install BEAM Packages {#how-to-install-beam-packages}
@ -52,15 +54,150 @@ Erlang.mk functions similarly to Rebar3, except we use `buildErlangMk` instead o
#### Mix Packages {#mix-packages}
Mix functions similarly to Rebar3, except we use `buildMix` instead of `buildRebar3`.
`mixRelease` is used to make a release in the mix sense. Dependencies will need to be fetched with `fetchMixDeps` and passed to it.
#### mixRelease - Elixir Phoenix example
Here is how your `default.nix` file would look.
```nix
with import <nixpkgs> { };
let
packages = beam.packagesWith beam.interpreters.erlang;
src = builtins.fetchgit {
url = "ssh://git@github.com/your_id/your_repo";
rev = "replace_with_your_commit";
};
pname = "your_project";
version = "0.0.1";
mixEnv = "prod";
mixDeps = packages.fetchMixDeps {
pname = "mix-deps-${pname}";
inherit src mixEnv version;
# nix will complain and tell you the right value to replace this with
sha256 = lib.fakeSha256;
# if you have build time environment variables add them here
MY_ENV_VAR="my_value";
};
nodeDependencies = (pkgs.callPackage ./assets/default.nix { }).shell.nodeDependencies;
frontEndFiles = stdenvNoCC.mkDerivation {
pname = "frontend-${pname}";
nativeBuildInputs = [ nodejs ];
inherit version src;
buildPhase = ''
cp -r ./assets $TEMPDIR
mkdir -p $TEMPDIR/assets/node_modules/.cache
cp -r ${nodeDependencies}/lib/node_modules $TEMPDIR/assets
export PATH="${nodeDependencies}/bin:$PATH"
cd $TEMPDIR/assets
webpack --config ./webpack.config.js
cd ..
'';
installPhase = ''
cp -r ./priv/static $out/
'';
outputHashAlgo = "sha256";
outputHashMode = "recursive";
# nix will complain and tell you the right value to replace this with
outputHash = lib.fakeSha256;
impureEnvVars = lib.fetchers.proxyImpureEnvVars;
};
in packages.mixRelease {
inherit src pname version mixEnv mixDeps;
# if you have build time environment variables add them here
MY_ENV_VAR="my_value";
preInstall = ''
mkdir -p ./priv/static
cp -r ${frontEndFiles} ./priv/static
'';
}
```
Setup will require the following steps:
- Move your secrets to runtime environment variables. For more information refer to the [runtime.exs docs](https://hexdocs.pm/mix/Mix.Tasks.Release.html#module-runtime-configuration). On a fresh Phoenix build that would mean that both `DATABASE_URL` and `SECRET_KEY` need to be moved to `runtime.exs`.
- `cd assets` and `nix-shell -p node2nix --run node2nix --development` will generate a Nix expression containing your frontend dependencies
- commit and push those changes
- you can now `nix-build .`
- To run the release, set the `RELEASE_TMP` environment variable to a directory that your program has write access to. It will be used to store the BEAM settings.
Alternatively, we can use `buildHex` as a shortcut:
#### Example of creating a service for an Elixir - Phoenix project
In order to create a service with your release, you could add a `service.nix`
in your project with the following
```nix
{config, pkgs, lib, ...}:
let
release = pkgs.callPackage ./default.nix;
release_name = "app";
working_directory = "/home/app";
in
{
systemd.services.${release_name} = {
wantedBy = [ "multi-user.target" ];
after = [ "network.target" "postgresql.service" ];
requires = [ "network-online.target" "postgresql.service" ];
description = "my app";
environment = {
# RELEASE_TMP is used to write the state of the
# VM configuration when the system is running
# it needs to be a writable directory
RELEASE_TMP = working_directory;
# can be generated in an elixir console with
# Base.encode32(:crypto.strong_rand_bytes(32))
RELEASE_COOKIE = "my_cookie";
MY_VAR = "my_var";
};
serviceConfig = {
Type = "exec";
DynamicUser = true;
WorkingDirectory = working_directory;
# Implied by DynamicUser, but just to emphasize due to RELEASE_TMP
PrivateTmp = true;
ExecStart = ''
${release}/bin/${release_name} start
'';
ExecStop = ''
${release}/bin/${release_name} stop
'';
ExecReload = ''
${release}/bin/${release_name} restart
'';
Restart = "on-failure";
RestartSec = 5;
StartLimitBurst = 3;
StartLimitInterval = 10;
};
# disksup requires bash
path = [ pkgs.bash ];
};
environment.systemPackages = [ release ];
}
```
## How to Develop {#how-to-develop}
### Creating a Shell {#creating-a-shell}
Usually, we need to create a `shell.nix` file and do our development inside of the environment specified therein. Just install your version of erlang and other interpreter, and then user your normal build tools. As an example with elixir:
Usually, we need to create a `shell.nix` file and do our development inside of the environment specified therein. Just install your version of Erlang and any other interpreters, and then use your normal build tools. As an example with Elixir:
```nix
{ pkgs ? import "<nixpkgs"> {} }:
@ -79,6 +216,68 @@ mkShell {
}
```
#### Building in a Shell (for Mix Projects) {#building-in-a-shell}
#### Elixir - Phoenix project
Here is an example `shell.nix`.
```nix
with import <nixpkgs> { };
let
# define packages to install
basePackages = [
git
# replace with beam.packages.erlang.elixir_1_11 if you need
beam.packages.erlang.elixir
nodejs-15_x
postgresql_13
# only used for frontend dependencies
# you are free to use yarn2nix as well
nodePackages.node2nix
# formatting js file
nodePackages.prettier
];
inputs = basePackages ++ lib.optionals stdenv.isLinux [ inotify-tools ]
++ lib.optionals stdenv.isDarwin
(with darwin.apple_sdk.frameworks; [ CoreFoundation CoreServices ]);
# define shell startup command
hooks = ''
# this allows mix to work on the local directory
mkdir -p .nix-mix .nix-hex
export MIX_HOME=$PWD/.nix-mix
export HEX_HOME=$PWD/.nix-mix
export PATH=$MIX_HOME/bin:$HEX_HOME/bin:$PATH
# TODO: not sure how to make hex available without installing it afterwards.
mix local.hex --if-missing
export LANG=en_US.UTF-8
export ERL_AFLAGS="-kernel shell_history enabled"
# postges related
# keep all your db data in a folder inside the project
export PGDATA="$PWD/db"
# phoenix related env vars
export POOL_SIZE=15
export DB_URL="postgresql://postgres:postgres@localhost:5432/db"
export PORT=4000
export MIX_ENV=dev
# add your project env vars here, word readable in the nix store.
export ENV_VAR="your_env_var"
'';
in mkShell {
buildInputs = inputs;
shellHook = hooks;
}
```
Initializing the project will require the following steps:
Using a `shell.nix` as described (see <xref linkend="creating-a-shell"/>) should just work.
- create the db directory `initdb ./db` (inside your mix project folder)
- create the postgres user `createuser postgres -ds`
- create the db `createdb db`
- start the postgres instance `pg_ctl -l "$PGDATA/server.log" start`
- add the `/db` folder to your `.gitignore`
- you can start your phoenix server and get a shell with `iex -S mix phx.server`

@ -21,8 +21,8 @@ The recommended way of defining a derivation for a Coq library, is to use the `c
* if it is a string of the form `owner:branch` then it tries to download the `branch` of owner `owner` for a project of the same name using the same vcs, and the `version` attribute of the resulting derivation is set to `"dev"`, additionally if the owner is not provided (i.e. if the `owner:` prefix is missing), it defaults to the original owner of the package (see below),
* if it is a string of the form `"#N"`, and the domain is github, then it tries to download the current head of the pull request `#N` from github,
* `defaultVersion` (optional). Coq libraries may be compatible with some specific versions of Coq only. The `defaultVersion` attribute is used when no `version` is provided (or if `version = null`) to select the version of the library to use by default, depending on the context. This selection will mainly depend on a `coq` version number but also possibly on other packages versions (e.g. `mathcomp`). If its value ends up to be `null`, the package is marked for removal in end-user `coqPackages` attribute set.
* `release` (optional, defaults to `{}`), lists all the known releases of the library and for each of them provides an attribute set with at least a `sha256` attribute (you may use the shell command `nix-prefetch-url --unpack <archive-url>` to find it, where `<archive-url>` is for example `https://github.com/owner/repo/archive/version.tar.gz`), each attribute set of the list of releases also takes optional overloading arguments for the fetcher as below (i.e.`domain`, `owner`, `repo`, `rev` assuming the default fetcher is used) and optional overrides for the result of the fetcher (i.e. `version` and `src`).
* `fetcher` (optional, default to a generic fetching mechanism supporting github or gitlab based infrastructures), is a function that takes at least an `owner`, a `repo`, a `rev`, and a `sha256` and returns an attribute set with a `version` and `src`.
* `release` (optional, defaults to `{}`), lists all the known releases of the library and for each of them provides an attribute set with at least a `sha256` attribute (you may put the empty string `""` in order to automatically insert a fake sha256, this will trigger an error which will allow you to find the correct sha256), each attribute set of the list of releases also takes optional overloading arguments for the fetcher as below (i.e.`domain`, `owner`, `repo`, `rev` assuming the default fetcher is used) and optional overrides for the result of the fetcher (i.e. `version` and `src`).
* `fetcher` (optional, defaults to a generic fetching mechanism supporting github or gitlab based infrastructures), is a function that takes at least an `owner`, a `repo`, a `rev`, and a `sha256` and returns an attribute set with a `version` and `src`.
* `repo` (optional, defaults to the value of `pname`),
* `owner` (optional, defaults to `"coq-community"`).
* `domain` (optional, defaults to `"github.com"`), domains including the strings `"github"` or `"gitlab"` in their names are automatically supported, otherwise, one must change the `fetcher` argument to support them (cf `pkgs/development/coq-modules/heq/default.nix` for an example),
@ -31,6 +31,8 @@ The recommended way of defining a derivation for a Coq library, is to use the `c
* `namePrefix` (optional), provides a way to alter the computation of `name` from `pname`, by explaining which dependencies must occur in `name`,
* `extraBuildInputs` (optional), by default `buildInputs` just contains `coq`, this allows to add more build inputs,
* `mlPlugin` (optional, defaults to `false`). Some extensions (plugins) might require OCaml and sometimes other OCaml packages. Standard dependencies can be added by setting the current option to `true`. For a finer grain control, the `coq.ocamlPackages` attribute can be used in `extraBuildInputs` to depend on the same package set Coq was built against.
* `useDune2ifVersion` (optional, default to `(x: false)` uses Dune2 to build the package if the provided predicate evaluates to true on the version, e.g. `useDune2if = versions.isGe "1.1"` will use dune if the version of the package is greater or equal to `"1.1"`,
* `useDune2` (optional, defaults to `false`) uses Dune2 to build the package if set to true, the presence of this attribute overrides the behavior of the previous one.
* `enableParallelBuilding` (optional, defaults to `true`), since it is activated by default, we provide a way to disable it.
* `extraInstallFlags` (optional), allows to extend `installFlags` which initializes the variable `COQMF_COQLIB` so as to install in the proper subdirectory. Indeed Coq libraries should be installed in `$(out)/lib/coq/${coq.coq-version}/user-contrib/`. Such directories are automatically added to the `$COQPATH` environment variable by the hook defined in the Coq derivation.
* `setCOQBIN` (optional, defaults to `true`), by default, the environment variable `$COQBIN` is set to the current Coq's binary, but one can disable this behavior by setting it to `false`,

@ -4,7 +4,7 @@
For local development, it's recommended to use nix-shell to create a dotnet environment:
```
```nix
# shell.nix
with import <nixpkgs> {};
@ -20,7 +20,7 @@ mkShell {
It's very likely that more than one sdk will be needed on a given project. Dotnet provides several different frameworks (E.g dotnetcore, aspnetcore, etc.) as well as many versions for a given framework. Normally, dotnet is able to fetch a framework and install it relative to the executable. However, this would mean writing to the nix store in nixpkgs, which is read-only. To support the many-sdk use case, one can compose an environment using `dotnetCorePackages.combinePackages`:
```
```nix
with import <nixpkgs> {};
mkShell {
@ -37,7 +37,7 @@ mkShell {
This will produce a dotnet installation that has the dotnet 3.1, 3.0, and 2.1 sdk. The first sdk listed will have it's cli utility present in the resulting environment. Example info output:
```
```ShellSesssion
$ dotnet --info
.NET Core SDK (reflecting any global.json):
Version: 3.1.101
@ -64,7 +64,7 @@ $ dotnet --info
The `dotnetCorePackages.sdk_X_Y` is preferred over the old dotnet-sdk as both major and minor version are very important for a dotnet environment. If a given minor version isn't present (or was changed), then this will likely break your ability to build a project.
## dotnetCorePackages.sdk vs vs dotnetCorePackages.net vs dotnetCorePackages.netcore vs dotnetCorePackages.aspnetcore
## dotnetCorePackages.sdk vs dotnetCorePackages.net vs dotnetCorePackages.netcore vs dotnetCorePackages.aspnetcore
The `dotnetCorePackages.sdk` contains both a runtime and the full sdk of a given version. The `net`, `netcore` and `aspnetcore` packages are meant to serve as minimal runtimes to deploy alongside already built applications. For runtime versions >= .NET 5 `net` is used while `netcore` is used for older .NET Core runtime version.

@ -4,7 +4,7 @@
The easiest way to get a working idris version is to install the `idris` attribute:
```
```ShellSesssion
$ # On NixOS
$ nix-env -i nixos.idris
$ # On non-NixOS
@ -21,7 +21,7 @@ self: super: {
And then:
```
```ShellSesssion
$ # On NixOS
$ nix-env -iA nixos.myIdris
$ # On non-NixOS
@ -29,7 +29,7 @@ $ nix-env -iA nixpkgs.myIdris
```
To see all available Idris packages:
```
```ShellSesssion
$ # On NixOS
$ nix-env -qaPA nixos.idrisPackages
$ # On non-NixOS
@ -37,7 +37,7 @@ $ nix-env -qaPA nixpkgs.idrisPackages
```
Similarly, entering a `nix-shell`:
```
```ShellSesssion
$ nix-shell -p 'idrisPackages.with-packages (with idrisPackages; [ contrib pruviloj ])'
```
@ -45,14 +45,14 @@ $ nix-shell -p 'idrisPackages.with-packages (with idrisPackages; [ contrib pruvi
To have access to these libraries in idris, call it with an argument `-p <library name>` for each library:
```
```ShellSesssion
$ nix-shell -p 'idrisPackages.with-packages (with idrisPackages; [ contrib pruviloj ])'
[nix-shell:~]$ idris -p contrib -p pruviloj
```
A listing of all available packages the Idris binary has access to is available via `--listlibs`:
```
```ShellSesssion
$ idris --listlibs
00prelude-idx.ibc
pruviloj
@ -105,7 +105,7 @@ build-idris-package {
Assuming this file is saved as `yaml.nix`, it's buildable using
```
```ShellSesssion
$ nix-build -E '(import <nixpkgs> {}).idrisPackages.callPackage ./yaml.nix {}'
```
@ -121,7 +121,7 @@ with import <nixpkgs> {};
in another file (say `default.nix`) to be able to build it with
```
```ShellSesssion
$ nix-build -A yaml
```
@ -133,7 +133,7 @@ Specifically, you can set `idrisBuildOptions`, `idrisTestOptions`, `idrisInstall
For example you could set
```
```nix
build-idris-package {
idrisBuildOptions = [ "--log" "1" "--verbose" ]

@ -50,7 +50,7 @@ and install it in your profile with
```shell
nix-env -iA nixpkgs.myLuaEnv
```
The environment is is installed by referring to the attribute, and considering
The environment is installed by referring to the attribute, and considering
the `nixpkgs` channel was used.
#### Lua environment defined in `/etc/nixos/configuration.nix`
@ -129,7 +129,7 @@ the whitelist maintainers/scripts/luarocks-packages.csv and updated by running m
[luarocks2nix](https://github.com/nix-community/luarocks) is a tool capable of generating nix derivations from both rockspec and src.rock (and favors the src.rock).
The automation only goes so far though and some packages need to be customized.
These customizations go in `pkgs/development/lua-modules/overrides.nix`.
For instance if the rockspec defines `external_dependencies`, these need to be manually added in in its rockspec file then it won't work.
For instance if the rockspec defines `external_dependencies`, these need to be manually added in its rockspec file then it won't work.
You can try converting luarocks packages to nix packages with the command `nix-shell -p luarocks-nix` and then `luarocks nix PKG_NAME`.
Nix rely on luarocks to install lua packages, basically it runs:

@ -7,8 +7,9 @@
#### Overview
Several versions of the Python interpreter are available on Nix, as well as a
high amount of packages. The attribute `python` refers to the default
interpreter, which is currently CPython 2.7. It is also possible to refer to
high amount of packages. The attribute `python3` refers to the default
interpreter, which is currently CPython 3.8. The attribute `python` refers to
CPython 2.7 for backwards-compatibility. It is also possible to refer to
specific versions, e.g. `python38` refers to CPython 3.8, and `pypy` refers to
the default PyPy interpreter.
@ -78,7 +79,7 @@ $ nix-shell -p 'python38.withPackages(ps: with ps; [ numpy toolz ])'
By default `nix-shell` will start a `bash` session with this interpreter in our
`PATH`, so if we then run:
```
```Python console
[nix-shell:~/src/nixpkgs]$ python3
Python 3.8.1 (default, Dec 18 2019, 19:06:26)
[GCC 9.2.0] on linux
@ -89,7 +90,7 @@ Type "help", "copyright", "credits" or "license" for more information.
Note that no other modules are in scope, even if they were imperatively
installed into our user environment as a dependency of a Python application:
```
```Python console
>>> import requests
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
@ -145,8 +146,8 @@ print(f"The dot product of {a} and {b} is: {np.dot(a, b)}")
Executing this script requires a `python3` that has `numpy`. Using what we learned
in the previous section, we could startup a shell and just run it like so:
```
nix-shell -p 'python38.withPackages(ps: with ps; [ numpy ])' --run 'python3 foo.py'
```ShellSesssion
$ nix-shell -p 'python38.withPackages(ps: with ps; [ numpy ])' --run 'python3 foo.py'
The dot product of [1 2] and [3 4] is: 11
```
@ -334,7 +335,7 @@ Above, we were mostly just focused on use cases and what to do to get started
creating working Python environments in nix.
Now that you know the basics to be up and running, it is time to take a step
back and take a deeper look at at how Python packages are packaged on Nix. Then,
back and take a deeper look at how Python packages are packaged on Nix. Then,
we will look at how you can use development mode with your code.
#### Python library packages in Nixpkgs
@ -638,7 +639,7 @@ are disabled.
#### Using pythonImportsCheck
Although unit tests are highly prefered to valid correctness of a package. Not
Although unit tests are highly prefered to validate correctness of a package, not
all packages have test suites that can be ran easily, and some have none at all.
To help ensure the package still works, `pythonImportsCheck` can attempt to import
the listed modules.
@ -762,10 +763,10 @@ and in this case the `python38` interpreter is automatically used.
Versions 2.7, 3.6, 3.7, 3.8 and 3.9 of the CPython interpreter are available as
respectively `python27`, `python36`, `python37`, `python38` and `python39`. The
aliases `python2` and `python3` correspond to respectively `python27` and
`python38`. The default interpreter, `python`, maps to `python2`. The PyPy
interpreters compatible with Python 2.7 and 3 are available as `pypy27` and
`pypy3`, with aliases `pypy2` mapping to `pypy27` and `pypy` mapping to `pypy2`.
The Nix expressions for the interpreters can be found in
`python39`. The attribute `python` maps to `python2`. The PyPy interpreters
compatible with Python 2.7 and 3 are available as `pypy27` and `pypy3`, with
aliases `pypy2` mapping to `pypy27` and `pypy` mapping to `pypy2`. The Nix
expressions for the interpreters can be found in
`pkgs/development/interpreters/python`.
All packages depending on any Python interpreter get appended
@ -788,6 +789,23 @@ Each interpreter has the following attributes:
- `executable`. Name of the interpreter executable, e.g. `python3.8`.
- `pkgs`. Set of Python packages for that specific interpreter. The package set can be modified by overriding the interpreter and passing `packageOverrides`.
### Optimizations
The Python interpreters are by default not build with optimizations enabled, because
the builds are in that case not reproducible. To enable optimizations, override the
interpreter of interest, e.g using
```
let
pkgs = import ./. {};
mypython = pkgs.python3.override {
enableOptimizations = true;
reproducibleBuild = false;
self = mypython;
};
in mypython
```
### Building packages and applications
Python libraries and applications that use `setuptools` or
@ -918,7 +936,7 @@ because their behaviour is different:
* `nativeBuildInputs ? []`: Build-time only dependencies. Typically executables
as well as the items listed in `setup_requires`.
* `buildInputs ? []`: Build and/or run-time dependencies that need to be be
* `buildInputs ? []`: Build and/or run-time dependencies that need to be
compiled for the host machine. Typically non-Python libraries which are being
linked.
* `checkInputs ? []`: Dependencies needed for running the `checkPhase`. These
@ -1188,7 +1206,8 @@ community to help save time. No tool is preferred at the moment.
expressions for your Python project. Note that [sharing derivations from
pypi2nix with nixpkgs is possible but not
encouraged](https://github.com/nix-community/pypi2nix/issues/222#issuecomment-443497376).
- [python2nix](https://github.com/proger/python2nix) by Vladimir Kirillov.
- [nixpkgs-pytools](https://github.com/nix-community/nixpkgs-pytools)
- [poetry2nix](https://github.com/nix-community/poetry2nix)
### Deterministic builds
@ -1486,11 +1505,12 @@ If you need to change a package's attribute(s) from `configuration.nix` you coul
nixpkgs.config.packageOverrides = super: {
python = super.python.override {
packageOverrides = python-self: python-super: {
zerobin = python-super.zerobin.overrideAttrs (oldAttrs: {
src = super.fetchgit {
url = "https://github.com/sametmax/0bin";
rev = "a344dbb18fe7a855d0742b9a1cede7ce423b34ec";
sha256 = "16d769kmnrpbdr0ph0whyf4yff5df6zi4kmwx7sz1d3r6c8p6xji";
twisted = python-super.twisted.overrideAttrs (oldAttrs: {
src = super.fetchPipy {
pname = "twisted";
version = "19.10.0";
sha256 = "7394ba7f272ae722a74f3d969dcf599bc4ef093bc392038748a490f1724a515d";
extension = "tar.bz2";
};
});
};
@ -1498,9 +1518,11 @@ If you need to change a package's attribute(s) from `configuration.nix` you coul
};
```
`pythonPackages.zerobin` is now globally overridden. All packages and also the
`zerobin` NixOS service use the new definition. Note that `python-super` refers
to the old package set and `python-self` to the new, overridden version.
`pythonPackages.twisted` is now globally overridden.
All packages and also all NixOS services that reference `twisted`
(such as `services.buildbot-worker`) now use the new definition.
Note that `python-super` refers to the old package set and `python-self`
to the new, overridden version.
To modify only a Python package set instead of a whole Python derivation, use
this snippet:
@ -1508,7 +1530,7 @@ this snippet:
```nix
myPythonPackages = pythonPackages.override {
overrides = self: super: {
zerobin = ...;
twisted = ...;
};
}
```
@ -1521,11 +1543,12 @@ Use the following overlay template:
self: super: {
python = super.python.override {
packageOverrides = python-self: python-super: {
zerobin = python-super.zerobin.overrideAttrs (oldAttrs: {
src = super.fetchgit {
url = "https://github.com/sametmax/0bin";
rev = "a344dbb18fe7a855d0742b9a1cede7ce423b34ec";
sha256 = "16d769kmnrpbdr0ph0whyf4yff5df6zi4kmwx7sz1d3r6c8p6xji";
twisted = python-super.twisted.overrideAttrs (oldAttrs: {
src = super.fetchPypi {
pname = "twisted";
version = "19.10.0";
sha256 = "7394ba7f272ae722a74f3d969dcf599bc4ef093bc392038748a490f1724a515d";
extension = "tar.bz2";
};
});
};
@ -1550,13 +1573,11 @@ In a `setup.py` or `setup.cfg` it is common to declare dependencies:
### Contributing guidelines
Following rules are desired to be respected:
The following rules are desired to be respected:
* Python libraries are called from `python-packages.nix` and packaged with
`buildPythonPackage`. The expression of a library should be in
`pkgs/development/python-modules/<name>/default.nix`.
* Libraries in `pkgs/top-level/python-packages.nix` are sorted
alphanumerically to avoid merge conflicts and ease locating attributes.
* Python applications live outside of `python-packages.nix` and are packaged
with `buildPythonApplication`.
* Make sure libraries build for all Python interpreters.
@ -1566,8 +1587,11 @@ Following rules are desired to be respected:
case, when you disable tests, leave a comment explaining why.
* Commit names of Python libraries should reflect that they are Python
libraries, so write for example `pythonPackages.numpy: 1.11 -> 1.12`.
* Attribute names in `python-packages.nix` should be normalized according to
[PEP 0503](https://www.python.org/dev/peps/pep-0503/#normalized-names). This
means that characters should be converted to lowercase and `.` and `_` should
be replaced by a single `-` (foo-bar-baz instead of Foo__Bar.baz )
* Attribute names in `python-packages.nix` should be sorted alphanumerically.
* Attribute names in `python-packages.nix` as well as `pname`s should match the
library's name on PyPI, but be normalized according to [PEP
0503](https://www.python.org/dev/peps/pep-0503/#normalized-names). This means
that characters should be converted to lowercase and `.` and `_` should be
replaced by a single `-` (foo-bar-baz instead of Foo__Bar.baz).
If necessary, `pname` has to be given a different value within `fetchPypi`.
* Attribute names in `python-packages.nix` should be sorted alphanumerically to
avoid merge conflicts and ease locating attributes.

@ -103,7 +103,7 @@ supported Qt version.
### Example adding a Qt library {#qt-library-all-packages-nix}
The following represents the contents of `qt5-packages.nix`.
```
```nix
{
# ...
@ -121,7 +121,7 @@ Use the `meta.broken` attribute to disable the package for unsupported Qt versio
stdenv.mkDerivation {
# ...
# Disable this library with Qt &lt; 5.9.0
# Disable this library with Qt < 5.9.0
meta.broken = lib.versionOlder qtbase.version "5.9.0";
}
```
@ -133,7 +133,7 @@ to select the Qt 5 version used for the application.
### Example adding a Qt application {#qt-application-all-packages-nix}
The following represents the contents of `qt5-packages.nix`.
```
```nix
{
# ...
@ -144,7 +144,7 @@ The following represents the contents of `qt5-packages.nix`.
```
The following represents the contents of `all-packages.nix`.
```
```nix
{
# ...

@ -229,7 +229,7 @@ end
If you want to package a specific version, you can use the standard Gemfile syntax for that, e.g. `gem 'mdl', '0.5.0'`, but if you want the latest stable version anyway, it's easier to update by simply running the `bundle lock` and `bundix` steps again.
Now you can also also make a `default.nix` that looks like this:
Now you can also make a `default.nix` that looks like this:
```nix
{ bundlerApp }:

@ -2,13 +2,14 @@
To install the rust compiler and cargo put
```
rustc
cargo
```nix
environment.systemPackages = [
rustc
cargo
];
```
into the `environment.systemPackages` 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`.
For other versions such as daily builds (beta and nightly),
use either `rustup` from nixpkgs (which will manage the rust installation in your home directory),
@ -18,7 +19,7 @@ or use Mozilla's [Rust nightlies overlay](#using-the-rust-nightlies-overlay).
Rust applications are packaged by using the `buildRustPackage` helper from `rustPlatform`:
```
```nix
{ lib, rustPlatform }:
rustPlatform.buildRustPackage rec {
@ -49,7 +50,7 @@ package. `cargoHash256` is used for traditional Nix SHA-256 hashes,
such as the one in the example above. `cargoHash` should instead be
used for [SRI](https://www.w3.org/TR/SRI/) hashes. For example:
```
```nix
cargoHash = "sha256-l1vL2ZdtDRxSGvP0X/l3nMw8+6WF67KPutJEzUROjg8=";
```
@ -59,21 +60,21 @@ expression and building the package once. The correct checksum can
then be taken from the failed build. A fake hash can be used for
`cargoSha256` as follows:
```
```nix
cargoSha256 = lib.fakeSha256;
```
For `cargoHash` you can use:
```
```nix
cargoHash = lib.fakeHash;
```
Per the instructions in the [Cargo Book](https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html)
best practices guide, Rust applications should always commit the `Cargo.lock`
file in git to ensure a reproducible build. However, a few packages do not, and
Nix depends on this file, so if it missing you can use `cargoPatches` to apply
it in the `patchPhase`. Consider sending a PR upstream with a note to the
Nix depends on this file, so if it is missing you can use `cargoPatches` to
apply it in the `patchPhase`. Consider sending a PR upstream with a note to the
maintainer describing why it's important to include in the application.
The fetcher will verify that the `Cargo.lock` file is in sync with the `src`
@ -157,7 +158,7 @@ path) can be passed directly to `buildRustPackage`:
```nix
pkgs.rustPlatform.buildRustPackage {
(...)
/* ... */
target = "x86_64-fortanix-unknown-sgx";
}
```
@ -192,6 +193,13 @@ rustPlatform.buildRustPackage {
Please note that the code will be compiled twice here: once in `release` mode
for the `buildPhase`, and again in `debug` mode for the `checkPhase`.
Test flags, e.g., `--features xxx/yyy`, can be passed to `cargo test` via the
`cargoTestFlags` attribute.
Another attribute, called `checkFlags`, is used to pass arguments to the test
binary itself, as stated
(here)[https://doc.rust-lang.org/cargo/commands/cargo-test.html].
#### Tests relying on the structure of the `target/` directory
Some tests may rely on the structure of the `target/` directory. Those tests
@ -255,7 +263,7 @@ Otherwise, some steps may fail because of the modified directory structure of `t
source code in a reproducible way. If it is missing or out-of-date one can use
the `cargoPatches` attribute to update or add it.
```
```nix
rustPlatform.buildRustPackage rec {
(...)
cargoPatches = [
@ -321,9 +329,10 @@ attributes can also be used:
variable `buildAndTestSubdir` can be used to build a crate in a
Cargo workspace. Additional maturin flags can be passed through
`maturinBuildFlags`.
* `cargoCheckHook`: run tests using Cargo. Additional flags can be
passed to Cargo using `checkFlags` and `checkFlagsArray`. By
default, tests are run in parallel. This can be disabled by setting
* `cargoCheckHook`: run tests using Cargo. The build type for checks
can be set using `cargoCheckType`. Additional flags can be passed to
the tests using `checkFlags` and `checkFlagsArray`. By default,
tests are run in parallel. This can be disabled by setting
`dontUseCargoParallelTests`.
* `cargoInstallHook`: install binaries and static/shared libraries
that were built using `cargoBuildHook`.
@ -481,7 +490,7 @@ an example for a minimal `hello` crate:
Now, the file produced by the call to `carnix`, called `hello.nix`, looks like:
```
```nix
# Generated by carnix 0.6.5: carnix -o hello.nix --src ./. Cargo.lock --standalone
{ stdenv, buildRustCrate, fetchgit }:
let kernel = stdenv.buildPlatform.parsed.kernel.name;
@ -510,7 +519,7 @@ dependencies, for instance by adding a single line `libc="*"` to our
`Cargo.lock`. Then, `carnix` needs to be run again, and produces the
following nix file:
```
```nix
# Generated by carnix 0.6.5: carnix -o hello.nix --src ./. Cargo.lock --standalone
{ stdenv, buildRustCrate, fetchgit }:
let kernel = stdenv.buildPlatform.parsed.kernel.name;
@ -565,7 +574,7 @@ Some crates require external libraries. For crates from
Starting from that file, one can add more overrides, to add features
or build inputs by overriding the hello crate in a seperate file.
```
```nix
with import <nixpkgs> {};
((import ./hello.nix).hello {}).override {
crateOverrides = defaultCrateOverrides // {
@ -585,7 +594,7 @@ derivation depend on the crate's version, the `attrs` argument of
the override above can be read, as in the following example, which
patches the derivation:
```
```nix
with import <nixpkgs> {};
((import ./hello.nix).hello {}).override {
crateOverrides = defaultCrateOverrides // {
@ -606,7 +615,7 @@ dependencies. For instance, to override the build inputs for crate
`libc` in the example above, where `libc` is a dependency of the main
crate, we could do:
```
```nix
with import <nixpkgs> {};
((import hello.nix).hello {}).override {
crateOverrides = defaultCrateOverrides // {
@ -622,27 +631,27 @@ general. A number of other parameters can be overridden:
- The version of rustc used to compile the crate:
```
```nix
(hello {}).override { rust = pkgs.rust; };
```
- Whether to build in release mode or debug mode (release mode by
default):
```
```nix
(hello {}).override { release = false; };
```
- Whether to print the commands sent to rustc when building
(equivalent to `--verbose` in cargo:
```
```nix
(hello {}).override { verbose = false; };
```
- Extra arguments to be passed to `rustc`:
```
```nix
(hello {}).override { extraRustcOpts = "-Z debuginfo=2"; };
```
@ -654,7 +663,7 @@ general. A number of other parameters can be overridden:
`postInstall`. As an example, here is how to create a new module
before running the build script:
```
```nix
(hello {}).override {
preConfigure = ''
echo "pub const PATH=\"${hi.out}\";" >> src/path.rs"
@ -668,7 +677,7 @@ One can also supply features switches. For example, if we want to
compile `diesel_cli` only with the `postgres` feature, and no default
features, we would write:
```
```nix
(callPackage ./diesel.nix {}).diesel {
default = false;
postgres = true;
@ -691,7 +700,7 @@ Using the example `hello` project above, we want to do the following:
A typical `shell.nix` might look like:
```
```nix
with import <nixpkgs> {};
stdenv.mkDerivation {
@ -713,7 +722,7 @@ stdenv.mkDerivation {
```
You should now be able to run the following:
```
```ShellSesssion
$ nix-shell --pure
$ cargo build
$ cargo test
@ -723,7 +732,7 @@ $ cargo test
To control your rust version (i.e. use nightly) from within `shell.nix` (or
other nix expressions) you can use the following `shell.nix`
```
```nix
# Latest Nightly
with import <nixpkgs> {};
let src = fetchFromGitHub {
@ -738,7 +747,7 @@ with import "${src.out}/rust-overlay.nix" pkgs pkgs;
stdenv.mkDerivation {
name = "rust-env";
buildInputs = [
# Note: to use use stable, just replace `nightly` with `stable`
# Note: to use stable, just replace `nightly` with `stable`
latest.rustChannels.nightly.rust
# Add some extra dependencies from `pkgs`
@ -751,7 +760,7 @@ stdenv.mkDerivation {
```
Now run:
```
```ShellSession
$ rustc --version
rustc 1.26.0-nightly (188e693b3 2018-03-26)
```
@ -786,7 +795,7 @@ in the `~/.config/nixpkgs/overlays` directory.
Add the following to your `configuration.nix`, `home-configuration.nix`, `shell.nix`, or similar:
```
```nix
{ pkgs ? import <nixpkgs> {
overlays = [
(import (builtins.fetchTarball https://github.com/mozilla/nixpkgs-mozilla/archive/master.tar.gz))

@ -116,6 +116,44 @@ The resulting package can be added to `packageOverrides` in `~/.nixpkgs/config.n
After that you can install your special grafted `myVim` or `myNeovim` packages.
### What if your favourite Vim plugin isn't already packaged?
If one of your favourite plugins isn't packaged, you can package it yourself:
```
{ config, pkgs, ... }:
let
easygrep = pkgs.vimUtils.buildVimPlugin {
name = "vim-easygrep";
src = pkgs.fetchFromGitHub {
owner = "dkprice";
repo = "vim-easygrep";
rev = "d0c36a77cc63c22648e792796b1815b44164653a";
sha256 = "0y2p5mz0d5fhg6n68lhfhl8p4mlwkb82q337c22djs4w5zyzggbc";
};
};
in
{
environment.systemPackages = [
(
pkgs.neovim.override {
configure = {
packages.myPlugins = with pkgs.vimPlugins; {
start = [
vim-go # already packaged plugin
easygrep # custom package
];
opt = [];
};
# ...
};
}
)
];
}
```
## Managing plugins with vim-plug
To use [vim-plug](https://github.com/junegunn/vim-plug) to manage your Vim
@ -156,7 +194,7 @@ assuming that "using latest version" is ok most of the time.
First create a vim-scripts file having one plugin name per line. Example:
```
```vim
"tlib"
{'name': 'vim-addon-sql'}
{'filetype_regex': '\%(vim)$', 'names': ['reload', 'vim-dev-plugin']}
@ -197,7 +235,7 @@ nix-shell -p vimUtils.vim_with_vim2nix --command "vim -c 'source generate.vim'"
You should get a Vim buffer with the nix derivations (output1) and vam.pluginDictionaries (output2).
You can add your Vim to your system's configuration file like this and start it by "vim-my":
```
```nix
my-vim =
let plugins = let inherit (vimUtils) buildVimPluginFrom2Nix; in {
copy paste output1 here
@ -217,7 +255,7 @@ my-vim =
Sample output1:
```
```nix
"reload" = buildVimPluginFrom2Nix { # created by nix#NixDerivation
name = "reload";
src = fetchgit {
@ -248,7 +286,7 @@ Nix expressions for Vim plugins are stored in [pkgs/misc/vim-plugins](/pkgs/misc
Some plugins require overrides in order to function properly. Overrides are placed in [overrides.nix](/pkgs/misc/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
deoplete-fish = super.deoplete-fish.overrideAttrs(old: {
dependencies = with super; [ deoplete-nvim vim-fish ];
});

@ -15,9 +15,9 @@
</part>
<part>
<title>Standard environment</title>
<xi:include href="stdenv/stdenv.xml" />
<xi:include href="stdenv/meta.xml" />
<xi:include href="stdenv/multiple-output.xml" />
<xi:include href="stdenv/stdenv.chapter.xml" />
<xi:include href="stdenv/meta.chapter.xml" />
<xi:include href="stdenv/multiple-output.chapter.xml" />
<xi:include href="stdenv/cross-compilation.chapter.xml" />
<xi:include href="stdenv/platform-notes.chapter.xml" />
</part>
@ -32,10 +32,11 @@
</part>
<part>
<title>Contributing to Nixpkgs</title>
<xi:include href="contributing/quick-start.xml" />
<xi:include href="contributing/coding-conventions.xml" />
<xi:include href="contributing/quick-start.chapter.xml" />
<xi:include href="contributing/coding-conventions.chapter.xml" />
<xi:include href="contributing/submitting-changes.chapter.xml" />
<xi:include href="contributing/reviewing-contributions.xml" />
<xi:include href="contributing/contributing-to-documentation.xml" />
<xi:include href="contributing/vulnerability-roundup.chapter.xml" />
<xi:include href="contributing/reviewing-contributions.chapter.xml" />
<xi:include href="contributing/contributing-to-documentation.chapter.xml" />
</part>
</book>

@ -123,7 +123,7 @@ depsBuildBuild = [ buildPackages.stdenv.cc ];
Add the following to your `mkDerivation` invocation.
```nix
doCheck = stdenv.hostPlatform == stdenv.buildPlatfrom;
doCheck = stdenv.hostPlatform == stdenv.buildPlatform;
```
## Cross-building packages {#sec-cross-usage}
@ -190,7 +190,7 @@ If one imagines the saturating self references at the end being replaced with in
```
(native..., native, native, native, foreign, foreign, foreign...)
```
On can then imagine any sequence of platforms such that there are bootstrap stages with their 3 platforms determined by "sliding a window" that is the 3 tuple through the sequence. This was the original model for bootstrapping. Without a target platform (assume a better world where all compilers are multi-target and all standard libraries are built in their own derivation), this is sufficient. Conversely if one wishes to cross compile "faster", with a "Canadian Cross" bootstrapping stage where `build != host != target`, more bootstrapping stages are needed since no sliding window provides the pesky `pkgsBuildTarget` package set since it skips the Canadian cross stage's "host".
One can then imagine any sequence of platforms such that there are bootstrap stages with their 3 platforms determined by "sliding a window" that is the 3 tuple through the sequence. This was the original model for bootstrapping. Without a target platform (assume a better world where all compilers are multi-target and all standard libraries are built in their own derivation), this is sufficient. Conversely if one wishes to cross compile "faster", with a "Canadian Cross" bootstrapping stage where `build != host != target`, more bootstrapping stages are needed since no sliding window provides the pesky `pkgsBuildTarget` package set since it skips the Canadian cross stage's "host".
::: note

@ -0,0 +1,194 @@
# Meta-attributes {#chap-meta}
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
meta = with lib; {
description = "A program that produces a familiar, friendly greeting";
longDescription = ''
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 = licenses.gpl3Plus;
maintainers = [ maintainers.eelco ];
platforms = platforms.all;
};
```
Meta-attributes are not passed to the builder of the package. Thus, a change to a meta-attribute doesn’t trigger a recompilation of the package. The value of a meta-attribute must be a string.
The meta-attributes of a package can be queried from the command-line using `nix-env`:
```ShellSession
$ nix-env -qa hello --json
{
"hello": {
"meta": {
"description": "A program that produces a familiar, friendly greeting",
"homepage": "https://www.gnu.org/software/hello/manual/",
"license": {
"fullName": "GNU General Public License version 3 or later",
"shortName": "GPLv3+",
"url": "http://www.fsf.org/licensing/licenses/gpl.html"
},
"longDescription": "GNU Hello is a program that prints \"Hello, world!\" when you run it.\nIt is fully customizable.\n",
"maintainers": [
"Ludovic Court\u00e8s <ludo@gnu.org>"
],
"platforms": [
"i686-linux",
"x86_64-linux",
"armv5tel-linux",
"armv7l-linux",
"mips32-linux",
"x86_64-darwin",
"i686-cygwin",
"i686-freebsd",
"x86_64-freebsd",
"i686-openbsd",
"x86_64-openbsd"
],
"position": "/home/user/dev/nixpkgs/pkgs/applications/misc/hello/default.nix:14"
},
"name": "hello-2.9",
"system": "x86_64-linux"
}
}
```
`nix-env` knows about the `description` field specifically:
```ShellSession
$ nix-env -qa hello --description
hello-2.3 A program that produces a familiar, friendly greeting
```
## Standard meta-attributes {#sec-standard-meta-attributes}
It is expected that each meta-attribute is one of the following:
### `description` {#var-meta-description}
A short (one-line) description of the package. This is shown by `nix-env -q --description` and also on the Nixpkgs release pages.
Don’t include a period at the end. Don’t include newline characters. Capitalise the first character. For brevity, don’t repeat the name of package --- just describe what it does.
Wrong: `"libpng is a library that allows you to decode PNG images."`
Right: `"A library for decoding PNG images"`
### `longDescription` {#var-meta-longDescription}
An arbitrarily long description of the package.
### `branch` {#var-meta-branch}
Release branch. Used to specify that a package is not going to receive updates that are not in this branch; for example, Linux kernel 3.0 is supposed to be updated to 3.0.X, not 3.1.
### `homepage` {#var-meta-homepage}
The package’s homepage. Example: `https://www.gnu.org/software/hello/manual/`
### `downloadPage` {#var-meta-downloadPage}
The page where a link to the current version can be found. Example: `https://ftp.gnu.org/gnu/hello/`
### `changelog` {#var-meta-changelog}
A link or a list of links to the location of Changelog for a package. A link may use expansion to refer to the correct changelog version. Example: `"https://git.savannah.gnu.org/cgit/hello.git/plain/NEWS?h=v${version}"`
### `license` {#var-meta-license}
The license, or licenses, for the package. One from the attribute set defined in [`nixpkgs/lib/licenses.nix`](https://github.com/NixOS/nixpkgs/blob/master/lib/licenses.nix). At this moment using both a list of licenses and a single license is valid. If the license field is in the form of a list representation, then it means that parts of the package are licensed differently. Each license should preferably be referenced by their attribute. The non-list attribute value can also be a space delimited string representation of the contained attribute `shortNames` or `spdxIds`. The following are all valid examples:
- Single license referenced by attribute (preferred) `lib.licenses.gpl3Only`.
- Single license referenced by its attribute shortName (frowned upon) `"gpl3Only"`.
- Single license referenced by its attribute spdxId (frowned upon) `"GPL-3.0-only"`.
- Multiple licenses referenced by attribute (preferred) `with lib.licenses; [ asl20 free ofl ]`.
- Multiple licenses referenced as a space delimited string of attribute shortNames (frowned upon) `"asl20 free ofl"`.
For details, see [Licenses](#sec-meta-license).
### `maintainers` {#var-meta-maintainers}
A list of the maintainers of this Nix expression. Maintainers are defined in [`nixpkgs/maintainers/maintainer-list.nix`](https://github.com/NixOS/nixpkgs/blob/master/maintainers/maintainer-list.nix). There is no restriction to becoming a maintainer, just add yourself to that list in a separate commit titled “maintainers: add alice”, and reference maintainers with `maintainers = with lib.maintainers; [ alice bob ]`.
### `priority` {#var-meta-priority}
The *priority* of the package, used by `nix-env` to resolve file name conflicts between packages. See the Nix manual page for `nix-env` for details. Example: `"10"` (a low-priority package).
### `platforms` {#var-meta-platforms}
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
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.
### `tests` {#var-meta-tests}
::: warning
This attribute is special in that it is not actually under the `meta` attribute set but rather under the `passthru` attribute set. This is due to how `meta` attributes work, and the fact that they are supposed to contain only metadata, not derivations.
:::
An attribute set with as values tests. A test is a derivation, which builds successfully when the test passes, and fails to build otherwise. A derivation that is a test needs to have `meta.timeout` defined.
The NixOS tests are available as `nixosTests` in parameters of derivations. For instance, the OpenSMTPD derivation includes lines similar to:
```nix
{ /* ... */, nixosTests }:
{
# ...
passthru.tests = {
basic-functionality-and-dovecot-integration = nixosTests.opensmtpd;
};
}
```
### `timeout` {#var-meta-timeout}
A timeout (in seconds) for building the derivation. If the derivation takes longer than this time to build, it can fail due to breaking the timeout. However, all computers do not have the same computing power, hence some builders may decide to apply a multiplicative factor to this value. When filling this value in, try to keep it approximately consistent with other values already present in `nixpkgs`.
### `hydraPlatforms` {#var-meta-hydraPlatforms}
The list of Nix platform types for which the Hydra instance at `hydra.nixos.org` 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
meta.platforms = lib.platforms.linux;
meta.hydraPlatforms = [];
```
### `broken` {#var-meta-broken}
If set to `true`, the package is marked as "broken", meaning that it won’t show up in `nix-env -qa`, and cannot be built or installed. Such packages should be removed from Nixpkgs eventually unless they are fixed.
### `updateWalker` {#var-meta-updateWalker}
If set to `true`, the package is tested to be updated correctly by the `update-walker.sh` script without additional settings. Such packages have `meta.version` set and their homepage (or the page specified by `meta.downloadPage`) contains a direct link to the package tarball.
## Licenses {#sec-meta-license}
The `meta.license` attribute should preferably contain a value from `lib.licenses` defined in [`nixpkgs/lib/licenses.nix`](https://github.com/NixOS/nixpkgs/blob/master/lib/licenses.nix), or in-place license description of the same format if the license is unlikely to be useful in another expression.
Although it’s typically better to indicate the specific license, a few generic options are available:
### `lib.licenses.free`, `"free"`
Catch-all for free software licenses not listed above.
### `lib.licenses.unfreeRedistributable`, `"unfree-redistributable"`
Unfree package that can be redistributed in binary form. That is, it’s legal to redistribute the *output* of the derivation. This means that the package can be included in the Nixpkgs channel.
Sometimes proprietary software can only be redistributed unmodified. Make sure the builder doesn’t actually modify the original binaries; otherwise we’re breaking the license. For instance, the NVIDIA X11 drivers can be redistributed unmodified, but our builder applies `patchelf` to make them work. Thus, its license is `"unfree"` and it cannot be included in the Nixpkgs channel.
### `lib.licenses.unfree`, `"unfree"`
Unfree package that cannot be redistributed. You can build it yourself, but you cannot redistribute the output of the derivation. Thus it cannot be included in the Nixpkgs channel.
### `lib.licenses.unfreeRedistributableFirmware`, `"unfree-redistributable-firmware"`
This package supplies unfree, redistributable firmware. This is a separate value from `unfree-redistributable` because not everybody cares whether firmware is free.

@ -1,349 +0,0 @@
<chapter xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xml:id="chap-meta">
<title>Meta-attributes</title>
<para>
Nix packages can declare <emphasis>meta-attributes</emphasis> 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 <varname>meta</varname> declaration like this:
<programlisting>
meta = with lib; {
description = "A program that produces a familiar, friendly greeting";
longDescription = ''
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 = licenses.gpl3Plus;
maintainers = [ maintainers.eelco ];
platforms = platforms.all;
};
</programlisting>
</para>
<para>
Meta-attributes are not passed to the builder of the package. Thus, a change to a meta-attribute doesn’t trigger a recompilation of the package. The value of a meta-attribute must be a string.
</para>
<para>
The meta-attributes of a package can be queried from the command-line using <command>nix-env</command>:
<screen>
<prompt>$ </prompt>nix-env -qa hello --json
{
"hello": {
"meta": {
"description": "A program that produces a familiar, friendly greeting",
"homepage": "https://www.gnu.org/software/hello/manual/",
"license": {
"fullName": "GNU General Public License version 3 or later",
"shortName": "GPLv3+",
"url": "http://www.fsf.org/licensing/licenses/gpl.html"
},
"longDescription": "GNU Hello is a program that prints \"Hello, world!\" when you run it.\nIt is fully customizable.\n",
"maintainers": [
"Ludovic Court\u00e8s &lt;ludo@gnu.org>"
],
"platforms": [
"i686-linux",
"x86_64-linux",
"armv5tel-linux",
"armv7l-linux",
"mips32-linux",
"x86_64-darwin",
"i686-cygwin",
"i686-freebsd",
"x86_64-freebsd",
"i686-openbsd",
"x86_64-openbsd"
],
"position": "/home/user/dev/nixpkgs/pkgs/applications/misc/hello/default.nix:14"
},
"name": "hello-2.9",
"system": "x86_64-linux"
}
}
</screen>
<command>nix-env</command> knows about the <varname>description</varname> field specifically:
<screen>
<prompt>$ </prompt>nix-env -qa hello --description
hello-2.3 A program that produces a familiar, friendly greeting
</screen>
</para>
<section xml:id="sec-standard-meta-attributes">
<title>Standard meta-attributes</title>
<para>
It is expected that each meta-attribute is one of the following:
</para>
<variablelist>
<varlistentry xml:id="var-meta-description">
<term>
<varname>description</varname>
</term>
<listitem>
<para>
A short (one-line) description of the package. This is shown by <command>nix-env -q --description</command> and also on the Nixpkgs release pages.
</para>
<para>
Don’t include a period at the end. Don’t include newline characters. Capitalise the first character. For brevity, don’t repeat the name of package — just describe what it does.
</para>
<para>
Wrong: <literal>"libpng is a library that allows you to decode PNG images."</literal>
</para>
<para>
Right: <literal>"A library for decoding PNG images"</literal>
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-longDescription">
<term>
<varname>longDescription</varname>
</term>
<listitem>
<para>
An arbitrarily long description of the package.
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-branch">
<term>
<varname>branch</varname>
</term>
<listitem>
<para>
Release branch. Used to specify that a package is not going to receive updates that are not in this branch; for example, Linux kernel 3.0 is supposed to be updated to 3.0.X, not 3.1.
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-homepage">
<term>
<varname>homepage</varname>
</term>
<listitem>
<para>
The package’s homepage. Example: <literal>https://www.gnu.org/software/hello/manual/</literal>
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-downloadPage">
<term>
<varname>downloadPage</varname>
</term>
<listitem>
<para>
The page where a link to the current version can be found. Example: <literal>https://ftp.gnu.org/gnu/hello/</literal>
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-changelog">
<term>
<varname>changelog</varname>
</term>
<listitem>
<para>
A link or a list of links to the location of Changelog for a package. A link may use expansion to refer to the correct changelog version. Example: <literal>"https://git.savannah.gnu.org/cgit/hello.git/plain/NEWS?h=v${version}"</literal>
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-license">
<term>
<varname>license</varname>
</term>
<listitem>
<para>
The license, or licenses, for the package. One from the attribute set defined in <link
xlink:href="https://github.com/NixOS/nixpkgs/blob/master/lib/licenses.nix"> <filename>nixpkgs/lib/licenses.nix</filename></link>. At this moment using both a list of licenses and a single license is valid. If the license field is in the form of a list representation, then it means that parts of the package are licensed differently. Each license should preferably be referenced by their attribute. The non-list attribute value can also be a space delimited string representation of the contained attribute shortNames or spdxIds. The following are all valid examples:
<itemizedlist>
<listitem>
<para>
Single license referenced by attribute (preferred) <literal>lib.licenses.gpl3Only</literal>.
</para>
</listitem>
<listitem>
<para>
Single license referenced by its attribute shortName (frowned upon) <literal>"gpl3Only"</literal>.
</para>
</listitem>
<listitem>
<para>
Single license referenced by its attribute spdxId (frowned upon) <literal>"GPL-3.0-only"</literal>.
</para>
</listitem>
<listitem>
<para>
Multiple licenses referenced by attribute (preferred) <literal>with lib.licenses; [ asl20 free ofl ]</literal>.
</para>
</listitem>
<listitem>
<para>
Multiple licenses referenced as a space delimited string of attribute shortNames (frowned upon) <literal>"asl20 free ofl"</literal>.
</para>
</listitem>
</itemizedlist>
For details, see <xref linkend='sec-meta-license'/>.
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-maintainers">
<term>
<varname>maintainers</varname>
</term>
<listitem>
<para>
A list of the maintainers of this Nix expression. Maintainers are defined in <link xlink:href="https://github.com/NixOS/nixpkgs/blob/master/maintainers/maintainer-list.nix"><filename>nixpkgs/maintainers/maintainer-list.nix</filename></link>. There is no restriction to becoming a maintainer, just add yourself to that list in a separate commit titled 'maintainers: add alice', and reference maintainers with <literal>maintainers = with lib.maintainers; [ alice bob ]</literal>.
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-priority">
<term>
<varname>priority</varname>
</term>
<listitem>
<para>
The <emphasis>priority</emphasis> of the package, used by <command>nix-env</command> to resolve file name conflicts between packages. See the Nix manual page for <command>nix-env</command> for details. Example: <literal>"10"</literal> (a low-priority package).
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-platforms">
<term>
<varname>platforms</varname>
</term>
<listitem>
<para>
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:
<programlisting>
meta.platforms = lib.platforms.linux;
</programlisting>
Attribute Set <varname>lib.platforms</varname> defines <link xlink:href="https://github.com/NixOS/nixpkgs/blob/master/lib/systems/doubles.nix"> various common lists</link> of platforms types.
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-tests">
<term>
<varname>tests</varname>
</term>
<listitem>
<warning>
<para>
This attribute is special in that it is not actually under the <literal>meta</literal> attribute set but rather under the <literal>passthru</literal> attribute set. This is due to how <literal>meta</literal> attributes work, and the fact that they are supposed to contain only metadata, not derivations.
</para>
</warning>
<para>
An attribute set with as values tests. A test is a derivation, which builds successfully when the test passes, and fails to build otherwise. A derivation that is a test needs to have <literal>meta.timeout</literal> defined.
</para>
<para>
The NixOS tests are available as <literal>nixosTests</literal> in parameters of derivations. For instance, the OpenSMTPD derivation includes lines similar to:
<programlisting>
{ /* ... */, nixosTests }:
{
# ...
passthru.tests = {
basic-functionality-and-dovecot-integration = nixosTests.opensmtpd;
};
}
</programlisting>
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-timeout">
<term>
<varname>timeout</varname>
</term>
<listitem>
<para>
A timeout (in seconds) for building the derivation. If the derivation takes longer than this time to build, it can fail due to breaking the timeout. However, all computers do not have the same computing power, hence some builders may decide to apply a multiplicative factor to this value. When filling this value in, try to keep it approximately consistent with other values already present in <literal>nixpkgs</literal>.
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-hydraPlatforms">
<term>
<varname>hydraPlatforms</varname>
</term>
<listitem>
<para>
The list of Nix platform types for which the Hydra instance at <literal>hydra.nixos.org</literal> will build the package. (Hydra is the Nix-based continuous build system.) It defaults to the value of <varname>meta.platforms</varname>. Thus, the only reason to set <varname>meta.hydraPlatforms</varname> is if you want <literal>hydra.nixos.org</literal> to build the package on a subset of <varname>meta.platforms</varname>, or not at all, e.g.
<programlisting>
meta.platforms = lib.platforms.linux;
meta.hydraPlatforms = [];
</programlisting>
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-broken">
<term>
<varname>broken</varname>
</term>
<listitem>
<para>
If set to <literal>true</literal>, the package is marked as “broken”, meaning that it won’t show up in <literal>nix-env -qa</literal>, and cannot be built or installed. Such packages should be removed from Nixpkgs eventually unless they are fixed.
</para>
</listitem>
</varlistentry>
<varlistentry xml:id="var-meta-updateWalker">
<term>
<varname>updateWalker</varname>
</term>
<listitem>
<para>
If set to <literal>true</literal>, the package is tested to be updated correctly by the <literal>update-walker.sh</literal> script without additional settings. Such packages have <varname>meta.version</varname> set and their homepage (or the page specified by <varname>meta.downloadPage</varname>) contains a direct link to the package tarball.
</para>
</listitem>
</varlistentry>
</variablelist>
</section>
<section xml:id="sec-meta-license">
<title>Licenses</title>
<para>
The <varname>meta.license</varname> attribute should preferrably contain a value from <varname>lib.licenses</varname> defined in <link xlink:href="https://github.com/NixOS/nixpkgs/blob/master/lib/licenses.nix"> <filename>nixpkgs/lib/licenses.nix</filename></link>, or in-place license description of the same format if the license is unlikely to be useful in another expression.
</para>
<para>
Although it's typically better to indicate the specific license, a few generic options are available:
<variablelist>
<varlistentry>
<term>
<varname>lib.licenses.free</varname>, <varname>"free"</varname>
</term>
<listitem>
<para>
Catch-all for free software licenses not listed above.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<varname>lib.licenses.unfreeRedistributable</varname>, <varname>"unfree-redistributable"</varname>
</term>
<listitem>
<para>
Unfree package that can be redistributed in binary form. That is, it’s legal to redistribute the <emphasis>output</emphasis> of the derivation. This means that the package can be included in the Nixpkgs channel.
</para>
<para>
Sometimes proprietary software can only be redistributed unmodified. Make sure the builder doesn’t actually modify the original binaries; otherwise we’re breaking the license. For instance, the NVIDIA X11 drivers can be redistributed unmodified, but our builder applies <command>patchelf</command> to make them work. Thus, its license is <varname>"unfree"</varname> and it cannot be included in the Nixpkgs channel.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<varname>lib.licenses.unfree</varname>, <varname>"unfree"</varname>
</term>
<listitem>
<para>
Unfree package that cannot be redistributed. You can build it yourself, but you cannot redistribute the output of the derivation. Thus it cannot be included in the Nixpkgs channel.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<varname>lib.licenses.unfreeRedistributableFirmware</varname>, <varname>"unfree-redistributable-firmware"</varname>
</term>
<listitem>
<para>
This package supplies unfree, redistributable firmware. This is a separate value from <varname>unfree-redistributable</varname> because not everybody cares whether firmware is free.
</para>
</listitem>
</varlistentry>
</variablelist>
</para>
</section>
</chapter>

@ -0,0 +1,128 @@
# Multiple-output packages {#chap-multiple-output}
## Introduction {#sec-multiple-outputs-introduction}
The Nix language allows a derivation to produce multiple outputs, which is similar to what is utilized by other Linux distribution packaging systems. The outputs reside in separate Nix store paths, so they can be mostly handled independently of each other, including passing to build inputs, garbage collection or binary substitution. The exception is that building from source always produces all the outputs.
The main motivation is to save disk space by reducing runtime closure sizes; consequently also sizes of substituted binaries get reduced. Splitting can be used to have more granular runtime dependencies, for example the typical reduction is to split away development-only files, as those are typically not needed during runtime. As a result, closure sizes of many packages can get reduced to a half or even much less.
::: note
The reduction effects could be instead achieved by building the parts in completely separate derivations. That would often additionally reduce build-time closures, but it tends to be much harder to write such derivations, as build systems typically assume all parts are being built at once. This compromise approach of single source package producing multiple binary packages is also utilized often by rpm and deb.
:::
A number of attributes can be used to work with a derivation with multiple outputs. The attribute `outputs` is a list of strings, which are the names of the outputs. For each of these names, an identically named attribute is created, corresponding to that output. The attribute `meta.outputsToInstall` is used to determine the default set of outputs to install when using the derivation name unqualified.
## Installing a split package {#sec-multiple-outputs-installing}
When installing a package with multiple outputs, the package’s `meta.outputsToInstall` attribute determines which outputs are actually installed. `meta.outputsToInstall` is a list whose [default installs binaries and the associated man pages](https://github.com/NixOS/nixpkgs/blob/f1680774340d5443a1409c3421ced84ac1163ba9/pkgs/stdenv/generic/make-derivation.nix#L310-L320). The following sections describe ways to install different outputs.
### Selecting outputs to install via NixOS {#sec-multiple-outputs-installing-nixos}
NixOS provides two ways to select the outputs to install for packages listed in `environment.systemPackages`:
- The configuration option `environment.extraOutputsToInstall` is appended to each package’s `meta.outputsToInstall` attribute to determine the outputs to install. It can for example be used to install `info` documentation or debug symbols for all packages.
- The outputs can be listed as packages in `environment.systemPackages`. For example, the `"out"` and `"info"` outputs for the `coreutils` package can be installed by including `coreutils` and `coreutils.info` in `environment.systemPackages`.
### Selecting outputs to install via `nix-env` {#sec-multiple-outputs-installing-nix-env}
`nix-env` lacks an easy way to select the outputs to install. When installing a package, `nix-env` always installs the outputs listed in `meta.outputsToInstall`, even when the user explicitly selects an output.
::: warning
`nix-env` silenty disregards the outputs selected by the user, and instead installs the outputs from `meta.outputsToInstall`. For example,
```ShellSession
$ nix-env -iA nixpkgs.coreutils.info
```
installs the `"out"` output (`coreutils.meta.outputsToInstall` is `[ "out" ]`) instead of the requested `"info"`.
:::
The only recourse to select an output with `nix-env` is to override the package’s `meta.outputsToInstall`, using the functions described in <xref linkend="chap-overrides" />. For example, the following overlay adds the `"info"` output for the `coreutils` package:
```nix
self: super:
{
coreutils = super.coreutils.overrideAttrs (oldAttrs: {
meta = oldAttrs.meta // { outputsToInstall = oldAttrs.meta.outputsToInstall or [ "out" ] ++ [ "info" ]; };
});
}
```
## Using a split package {#sec-multiple-outputs-using-split-packages}
In the Nix language the individual outputs can be reached explicitly as attributes, e.g. `coreutils.info`, but the typical case is just using packages as build inputs.
When a multiple-output derivation gets into a build input of another derivation, the `dev` output is added if it exists, otherwise the first output is added. In addition to that, `propagatedBuildOutputs` of that package which by default contain `$outputBin` and `$outputLib` are also added. (See <xref linkend="multiple-output-file-type-groups" />.)
In some cases it may be desirable to combine different outputs under a single store path. A function `symlinkJoin` can be used to do this. (Note that it may negate some closure size benefits of using a multiple-output package.)
## Writing a split derivation {#sec-multiple-outputs-}
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>`; it’s relatively well-readable. The whole machinery is triggered by defining the `outputs` attribute to contain the list of desired output names (strings).
```nix
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 didn’t get elsewhere.
::: note
There is a special handling of the `debug` output, described at <xref linkend="stdenv-separateDebugInfo" />.
:::
### “Binaries first” {#multiple-output-file-binaries-first-convention}
A commonly adopted convention in `nixpkgs` is that executables provided by the package are contained within its first output. This convention allows the dependent packages to reference the executables provided by packages in a uniform manner. For instance, provided with the knowledge that the `perl` package contains a `perl` executable it can be referenced as `${pkgs.perl}/bin/perl` within a Nix derivation that needs to execute a Perl script.
The `glibc` package is a deliberate single exception to the “binaries first” convention. The `glibc` has `libs` as its first output allowing the libraries provided by `glibc` to be referenced directly (e.g. `${stdenv.glibc}/lib/ld-linux-x86-64.so.2`). The executables provided by `glibc` can be accessed via its `bin` attribute (e.g. `${stdenv.glibc.bin}/bin/ldd`).
The reason for why `glibc` deviates from the convention is because referencing a library provided by `glibc` is a very common operation among Nix packages. For instance, third-party executables packaged by Nix are typically patched and relinked with the relevant version of `glibc` libraries from Nix packages (please see the documentation on [patchelf](https://github.com/NixOS/patchelf/blob/master/README) for more details).
### File type groups {#multiple-output-file-type-groups}
The support code currently recognizes some particular kinds of outputs and either instructs the build system of the package to put files into their desired outputs or it moves the files during the fixup phase. Each group of file types has an `outputFoo` variable specifying the output name where they should go. If that variable isn’t defined by the derivation writer, it is guessed – a default output name is defined, falling back to other possibilities if the output isn’t defined.
#### ` $outputDev`
is for development-only files. These include C(++) headers (`include/`), pkg-config (`lib/pkgconfig/`), cmake (`lib/cmake/`) and aclocal files (`share/aclocal/`). They go to `dev` or `out` by default.
#### ` $outputBin`
is meant for user-facing binaries, typically residing in `bin/`. They go to `bin` or `out` by default.
#### ` $outputLib`
is meant for libraries, typically residing in `lib/` and `libexec/`. They go to `lib` or `out` by default.
#### ` $outputDoc`
is for user documentation, typically residing in `share/doc/`. It goes to `doc` or `out` by default.
#### ` $outputDevdoc`
is for _developer_ documentation. Currently we count gtk-doc and devhelp books, typically residing in `share/gtk-doc/` and `share/devhelp/`, in there. It goes to `devdoc` or is removed (!) by default. This is because e.g. gtk-doc tends to be rather large and completely unused by nixpkgs users.
#### ` $outputMan`
is for man pages (except for section 3), typically residing in `share/man/man[0-9]/`. They go to `man` or `$outputBin` by default.
#### ` $outputDevman`
is for section 3 man pages, typically residing in `share/man/man[0-9]/`. They go to `devman` or `$outputMan` by default.
#### ` $outputInfo`
is for info pages, typically residing in `share/info/`. They go to `info` or `$outputBin` by default.
### Common caveats {#sec-multiple-outputs-caveats}
- Some configure scripts don’t like some of the parameters passed by default by the framework, e.g. `--docdir=/foo/bar`. You can disable this by setting `setOutputFlags = false;`.
- The outputs of a single derivation can retain references to each other, but note that circular references are not allowed. (And each strongly-connected component would act as a single output anyway.)
- Most of split packages contain their core functionality in libraries. These libraries tend to refer to various kind of data that typically gets into `out`, e.g. locale strings, so there is often no advantage in separating the libraries into `lib`, as keeping them in `out` is easier.
- Some packages have hidden assumptions on install paths, which complicates splitting.

@ -1,262 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE chapter [
<!ENTITY ndash "&#x2013;"> <!-- @vcunat likes to use this one ;-) -->
]>
<chapter xmlns="http://docbook.org/ns/docbook"
xmlns:xlink="http://www.w3.org/1999/xlink"
xml:id="chap-multiple-output">
<title>Multiple-output packages</title>
<section xml:id="sec-multiple-outputs-introduction">
<title>Introduction</title>
<para>
The Nix language allows a derivation to produce multiple outputs, which is similar to what is utilized by other Linux distribution packaging systems. The outputs reside in separate Nix store paths, so they can be mostly handled independently of each other, including passing to build inputs, garbage collection or binary substitution. The exception is that building from source always produces all the outputs.
</para>
<para>
The main motivation is to save disk space by reducing runtime closure sizes; consequently also sizes of substituted binaries get reduced. Splitting can be used to have more granular runtime dependencies, for example the typical reduction is to split away development-only files, as those are typically not needed during runtime. As a result, closure sizes of many packages can get reduced to a half or even much less.
</para>
<note>
<para>
The reduction effects could be instead achieved by building the parts in completely separate derivations. That would often additionally reduce build-time closures, but it tends to be much harder to write such derivations, as build systems typically assume all parts are being built at once. This compromise approach of single source package producing multiple binary packages is also utilized often by rpm and deb.
</para>
</note>
<para>
A number of attributes can be used to work with a derivation with multiple outputs. The attribute <varname>outputs</varname> is a list of strings, which are the names of the outputs. For each of these names, an identically named attribute is created, corresponding to that output. The attribute <varname>meta.outputsToInstall</varname> is used to determine the default set of outputs to install when using the derivation name unqualified.
</para>
</section>
<section xml:id="sec-multiple-outputs-installing">
<title>Installing a split package</title>
<para>
When installing a package with multiple outputs, the package's <varname>meta.outputsToInstall</varname> attribute determines which outputs are actually installed. <varname>meta.outputsToInstall</varname> is a list whose <link xlink:href="https://github.com/NixOS/nixpkgs/blob/f1680774340d5443a1409c3421ced84ac1163ba9/pkgs/stdenv/generic/make-derivation.nix#L310-L320">default installs binaries and the associated man pages</link>. The following sections describe ways to install different outputs.
</para>
<section xml:id="sec-multiple-outputs-installing-nixos">
<title>Selecting outputs to install via NixOS</title>
<para>
NixOS provides two ways to select the outputs to install for packages listed in <varname>environment.systemPackages</varname>:
</para>
<itemizedlist>
<listitem>
<para>
The configuration option <varname>environment.extraOutputsToInstall</varname> is appended to each package's <varname>meta.outputsToInstall</varname> attribute to determine the outputs to install. It can for example be used to install <literal>info</literal> documentation or debug symbols for all packages.
</para>
</listitem>
<listitem>
<para>
The outputs can be listed as packages in <varname>environment.systemPackages</varname>. For example, the <literal>"out"</literal> and <literal>"info"</literal> outputs for the <varname>coreutils</varname> package can be installed by including <varname>coreutils</varname> and <varname>coreutils.info</varname> in <varname>environment.systemPackages</varname>.
</para>
</listitem>
</itemizedlist>
</section>
<section xml:id="sec-multiple-outputs-installing-nix-env">
<title>Selecting outputs to install via <command>nix-env</command></title>
<para>
<command>nix-env</command> lacks an easy way to select the outputs to install. When installing a package, <command>nix-env</command> always installs the outputs listed in <varname>meta.outputsToInstall</varname>, even when the user explicitly selects an output.
</para>
<warning>
<para>
<command>nix-env</command> silenty disregards the outputs selected by the user, and instead installs the outputs from <varname>meta.outputsToInstall</varname>. For example,
</para>
<screen><prompt>$ </prompt>nix-env -iA nixpkgs.coreutils.info</screen>
<para>
installs the <literal>"out"</literal> output (<varname>coreutils.meta.outputsToInstall</varname> is <literal>[ "out" ]</literal>) instead of the requested <literal>"info"</literal>.
</para>
</warning>
<para>
The only recourse to select an output with <command>nix-env</command> is to override the package's <varname>meta.outputsToInstall</varname>, using the functions described in <xref linkend="chap-overrides" />. For example, the following overlay adds the <literal>"info"</literal> output for the <varname>coreutils</varname> package:
</para>
<programlisting>self: super:
{
coreutils = super.coreutils.overrideAttrs (oldAttrs: {
meta = oldAttrs.meta // { outputsToInstall = oldAttrs.meta.outputsToInstall or [ "out" ] ++ [ "info" ]; };
});
}
</programlisting>
</section>
</section>
<section xml:id="sec-multiple-outputs-using-split-packages">
<title>Using a split package</title>
<para>
In the Nix language the individual outputs can be reached explicitly as attributes, e.g. <varname>coreutils.info</varname>, but the typical case is just using packages as build inputs.
</para>
<para>
When a multiple-output derivation gets into a build input of another derivation, the <varname>dev</varname> output is added if it exists, otherwise the first output is added. In addition to that, <varname>propagatedBuildOutputs</varname> of that package which by default contain <varname>$outputBin</varname> and <varname>$outputLib</varname> are also added. (See <xref linkend="multiple-output-file-type-groups" />.)
</para>
<para>
In some cases it may be desirable to combine different outputs under a single store path. A function <literal>symlinkJoin</literal> can be used to do this. (Note that it may negate some closure size benefits of using a multiple-output package.)
</para>
</section>
<section xml:id="sec-multiple-outputs-">
<title>Writing a split derivation</title>
<para>
Here you find how to write a derivation that produces multiple outputs.
</para>
<para>
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 &lt;<filename>nixpkgs/pkgs/build-support/setup-hooks/multiple-outputs.sh</filename>&gt;; it's relatively well-readable. The whole machinery is triggered by defining the <varname>outputs</varname> attribute to contain the list of desired output names (strings).
</para>
<programlisting>outputs = [ "bin" "dev" "out" "doc" ];</programlisting>
<para>
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 <varname>out</varname> output, as it catches any files that didn't get elsewhere.
</para>
<note>
<para>
There is a special handling of the <varname>debug</varname> output, described at <xref linkend="stdenv-separateDebugInfo" />.
</para>
</note>
<section xml:id="multiple-output-file-binaries-first-convention">
<title><quote>Binaries first</quote></title>
<para>
A commonly adopted convention in <literal>nixpkgs</literal> is that executables provided by the package are contained within its first output. This convention allows the dependent packages to reference the executables provided by packages in a uniform manner. For instance, provided with the knowledge that the <literal>perl</literal> package contains a <literal>perl</literal> executable it can be referenced as <literal>${pkgs.perl}/bin/perl</literal> within a Nix derivation that needs to execute a Perl script.
</para>
<para>
The <literal>glibc</literal> package is a deliberate single exception to the <quote>binaries first</quote> convention. The <literal>glibc</literal> has <literal>libs</literal> as its first output allowing the libraries provided by <literal>glibc</literal> to be referenced directly (e.g. <literal>${stdenv.glibc}/lib/ld-linux-x86-64.so.2</literal>). The executables provided by <literal>glibc</literal> can be accessed via its <literal>bin</literal> attribute (e.g. <literal>${stdenv.glibc.bin}/bin/ldd</literal>).
</para>
<para>
The reason for why <literal>glibc</literal> deviates from the convention is because referencing a library provided by <literal>glibc</literal> is a very common operation among Nix packages. For instance, third-party executables packaged by Nix are typically patched and relinked with the relevant version of <literal>glibc</literal> libraries from Nix packages (please see the documentation on <link xlink:href="https://github.com/NixOS/patchelf/blob/master/README">patchelf</link> for more details).
</para>
</section>
<section xml:id="multiple-output-file-type-groups">
<title>File type groups</title>
<para>
The support code currently recognizes some particular kinds of outputs and either instructs the build system of the package to put files into their desired outputs or it moves the files during the fixup phase. Each group of file types has an <varname>outputFoo</varname> variable specifying the output name where they should go. If that variable isn't defined by the derivation writer, it is guessed &ndash; a default output name is defined, falling back to other possibilities if the output isn't defined.
</para>
<variablelist>
<varlistentry>
<term>
<varname> $outputDev</varname>
</term>
<listitem>
<para>
is for development-only files. These include C(++) headers (<filename>include/</filename>), pkg-config (<filename>lib/pkgconfig/</filename>), cmake (<filename>lib/cmake/</filename>) and aclocal files (<varname>share/aclocal/</varname>). They go to <varname>dev</varname> or <varname>out</varname> by default.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<varname> $outputBin</varname>
</term>
<listitem>
<para>
is meant for user-facing binaries, typically residing in <filename>bin/</filename>. They go to <varname>bin</varname> or <varname>out</varname> by default.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<varname> $outputLib</varname>
</term>
<listitem>
<para>
is meant for libraries, typically residing in <filename>lib/</filename> and <filename>libexec/</filename>. They go to <varname>lib</varname> or <varname>out</varname> by default.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<varname> $outputDoc</varname>
</term>
<listitem>
<para>
is for user documentation, typically residing in <filename>share/doc/</filename>. It goes to <varname>doc</varname> or <varname>out</varname> by default.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<varname> $outputDevdoc</varname>
</term>
<listitem>
<para>
is for <emphasis>developer</emphasis> documentation. Currently we count gtk-doc and devhelp books, typically residing in <filename>share/gtk-doc/</filename> and <filename>share/devhelp/</filename>, in there. It goes to <varname>devdoc</varname> or is removed (!) by default. This is because e.g. gtk-doc tends to be rather large and completely unused by nixpkgs users.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<varname> $outputMan</varname>
</term>
<listitem>
<para>
is for man pages (except for section 3), typically residing in <filename>share/man/man[0-9]/</filename>. They go to <varname>man</varname> or <varname>$outputBin</varname> by default.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<varname> $outputDevman</varname>
</term>
<listitem>
<para>
is for section 3 man pages, typically residing in <filename>share/man/man3/</filename>. They go to <varname>devman</varname> or <varname>$outputMan</varname> by default.
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<varname> $outputInfo</varname>
</term>
<listitem>
<para>
is for info pages, typically residing in <filename>share/info/</filename>. They go to <varname>info</varname> or <varname>$outputBin</varname> by default.
</para>
</listitem>
</varlistentry>
</variablelist>
</section>
<section xml:id="sec-multiple-outputs-caveats">
<title>Common caveats</title>
<itemizedlist>
<listitem>
<para>
Some configure scripts don't like some of the parameters passed by default by the framework, e.g. <literal>--docdir=/foo/bar</literal>. You can disable this by setting <literal>setOutputFlags = false;</literal>.
</para>
</listitem>
<listitem>
<para>
The outputs of a single derivation can retain references to each other, but note that circular references are not allowed. (And each strongly-connected component would act as a single output anyway.)
</para>
</listitem>
<listitem>
<para>
Most of split packages contain their core functionality in libraries. These libraries tend to refer to various kind of data that typically gets into <varname>out</varname>, e.g. locale strings, so there is often no advantage in separating the libraries into <varname>lib</varname>, as keeping them in <varname>out</varname> is easier.
</para>
</listitem>
<listitem>
<para>
Some packages have hidden assumptions on install paths, which complicates splitting.
</para>
</listitem>
</itemizedlist>
</section>
</section>
<!--Writing a split derivation-->
</chapter>

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

@ -170,7 +170,7 @@
</programlisting>
</para>
<para>
Note that <literal>allowlistedLicenses</literal> only applies to unfree licenses unless <literal>allowUnfree</literal> is enabled. It is not a generic allowlist for all types of licenses. <literal>blocklistedLicenses</literal> applies to all licenses.
Note that <literal>allowlistedLicenses</literal> only applies to unfree licenses unless <literal>allowUnfree</literal> is enabled. It is not a generic allowlist for all types of licenses. <literal>blocklistedLicenses</literal> applies to all licenses.
</para>
</listitem>
</itemizedlist>

@ -28,8 +28,7 @@
</para>
<para>
NOTE: DO NOT USE THIS in nixpkgs.
Further overlays can be added by calling the <literal>pkgs.extend</literal> or <literal>pkgs.appendOverlays</literal>, although it is often preferable to avoid these functions, because they recompute the Nixpkgs fixpoint, which is somewhat expensive to do.
NOTE: DO NOT USE THIS in nixpkgs. Further overlays can be added by calling the <literal>pkgs.extend</literal> or <literal>pkgs.appendOverlays</literal>, although it is often preferable to avoid these functions, because they recompute the Nixpkgs fixpoint, which is somewhat expensive to do.
</para>
</section>
@ -139,98 +138,72 @@ self: super:
</para>
</section>
<section xml:id="sec-overlays-alternatives">
<title>Using overlays to configure alternatives</title>
<title>Using overlays to configure alternatives</title>
<para>
Certain software packages have different implementations of the same interface. Other distributions have functionality to switch between these. For example, Debian provides <link
xlink:href="https://wiki.debian.org/DebianAlternatives">DebianAlternatives</link>. Nixpkgs has what we call <literal>alternatives</literal>, which are configured through overlays.
</para>
<section xml:id="sec-overlays-alternatives-blas-lapack">
<title>BLAS/LAPACK</title>
<para>
Certain software packages have different implementations of the
same interface. Other distributions have functionality to switch
between these. For example, Debian provides <link
xlink:href="https://wiki.debian.org/DebianAlternatives">DebianAlternatives</link>.
Nixpkgs has what we call <literal>alternatives</literal>, which
are configured through overlays.
In Nixpkgs, we have multiple implementations of the BLAS/LAPACK numerical linear algebra interfaces. They are:
</para>
<section xml:id="sec-overlays-alternatives-blas-lapack">
<title>BLAS/LAPACK</title>
<itemizedlist>
<listitem>
<para>
In Nixpkgs, we have multiple implementations of the BLAS/LAPACK
numerical linear algebra interfaces. They are:
<link xlink:href="https://www.openblas.net/">OpenBLAS</link>
</para>
<itemizedlist>
<listitem>
<para>
<link xlink:href="https://www.openblas.net/">OpenBLAS</link>
</para>
<para>
The Nixpkgs attribute is <literal>openblas</literal> for
ILP64 (integer width = 64 bits) and
<literal>openblasCompat</literal> for LP64 (integer width =
32 bits). <literal>openblasCompat</literal> is the default.
</para>
</listitem>
<listitem>
<para>
<link xlink:href="http://www.netlib.org/lapack/">LAPACK
reference</link> (also provides BLAS)
</para>
<para>
The Nixpkgs attribute is <literal>lapack-reference</literal>.
</para>
</listitem>
<listitem>
<para>
<link
xlink:href="https://software.intel.com/en-us/mkl">Intel
MKL</link> (only works on the x86_64 architecture, unfree)
</para>
<para>
The Nixpkgs attribute is <literal>mkl</literal>.
</para>
</listitem>
<listitem>
<para>
<link
<para>
The Nixpkgs attribute is <literal>openblas</literal> for ILP64 (integer width = 64 bits) and <literal>openblasCompat</literal> for LP64 (integer width = 32 bits). <literal>openblasCompat</literal> is the default.
</para>
</listitem>
<listitem>
<para>
<link xlink:href="http://www.netlib.org/lapack/">LAPACK reference</link> (also provides BLAS)
</para>
<para>
The Nixpkgs attribute is <literal>lapack-reference</literal>.
</para>
</listitem>
<listitem>
<para>
<link
xlink:href="https://software.intel.com/en-us/mkl">Intel MKL</link> (only works on the x86_64 architecture, unfree)
</para>
<para>
The Nixpkgs attribute is <literal>mkl</literal>.
</para>
</listitem>
<listitem>
<para>
<link
xlink:href="https://github.com/flame/blis">BLIS</link>
</para>
<para>
BLIS, available through the attribute
<literal>blis</literal>, is a framework for linear algebra kernels. In
addition, it implements the BLAS interface.
</para>
</listitem>
<listitem>
<para>
<link
xlink:href="https://developer.amd.com/amd-aocl/blas-library/">AMD
BLIS/LIBFLAME</link> (optimized for modern AMD x86_64 CPUs)
</para>
<para>
The AMD fork of the BLIS library, with attribute
<literal>amd-blis</literal>, extends BLIS with optimizations for
modern AMD CPUs. The changes are usually submitted to
the upstream BLIS project after some time. However, AMD BLIS
typically provides some performance improvements on AMD Zen CPUs.
The complementary AMD LIBFLAME library, with attribute
<literal>amd-libflame</literal>, provides a LAPACK implementation.
</para>
</listitem>
</itemizedlist>
</para>
<para>
Introduced in <link
xlink:href="https://github.com/NixOS/nixpkgs/pull/83888">PR
#83888</link>, we are able to override the <literal>blas</literal>
and <literal>lapack</literal> packages to use different implementations,
through the <literal>blasProvider</literal> and
<literal>lapackProvider</literal> argument. This can be used
to select a different provider. BLAS providers will have
symlinks in <literal>$out/lib/libblas.so.3</literal> and
<literal>$out/lib/libcblas.so.3</literal> to their respective
BLAS libraries. Likewise, LAPACK providers will have symlinks
in <literal>$out/lib/liblapack.so.3</literal> and
<literal>$out/lib/liblapacke.so.3</literal> to their respective
LAPACK libraries. For example, Intel MKL is both a BLAS and
LAPACK provider. An overlay can be created to use Intel MKL
that looks like:
BLIS, available through the attribute <literal>blis</literal>, is a framework for linear algebra kernels. In addition, it implements the BLAS interface.
</para>
<programlisting>
</listitem>
<listitem>
<para>
<link
xlink:href="https://developer.amd.com/amd-aocl/blas-library/">AMD BLIS/LIBFLAME</link> (optimized for modern AMD x86_64 CPUs)
</para>
<para>
The AMD fork of the BLIS library, with attribute <literal>amd-blis</literal>, extends BLIS with optimizations for modern AMD CPUs. The changes are usually submitted to the upstream BLIS project after some time. However, AMD BLIS typically provides some performance improvements on AMD Zen CPUs. The complementary AMD LIBFLAME library, with attribute <literal>amd-libflame</literal>, provides a LAPACK implementation.
</para>
</listitem>
</itemizedlist>
<para>
Introduced in <link
xlink:href="https://github.com/NixOS/nixpkgs/pull/83888">PR #83888</link>, we are able to override the <literal>blas</literal> and <literal>lapack</literal> packages to use different implementations, through the <literal>blasProvider</literal> and <literal>lapackProvider</literal> argument. This can be used to select a different provider. BLAS providers will have symlinks in <literal>$out/lib/libblas.so.3</literal> and <literal>$out/lib/libcblas.so.3</literal> to their respective BLAS libraries. Likewise, LAPACK providers will have symlinks in <literal>$out/lib/liblapack.so.3</literal> and <literal>$out/lib/liblapacke.so.3</literal> to their respective LAPACK libraries. For example, Intel MKL is both a BLAS and LAPACK provider. An overlay can be created to use Intel MKL that looks like:
</para>
<programlisting>
self: super:
{
@ -243,46 +216,24 @@ self: super:
};
}
</programlisting>
<para>
This overlay uses Intel’s MKL library for both BLAS and LAPACK
interfaces. Note that the same can be accomplished at runtime
using <literal>LD_LIBRARY_PATH</literal> of
<literal>libblas.so.3</literal> and
<literal>liblapack.so.3</literal>. For instance:
</para>
<para>
This overlay uses Intel’s MKL library for both BLAS and LAPACK interfaces. Note that the same can be accomplished at runtime using <literal>LD_LIBRARY_PATH</literal> of <literal>libblas.so.3</literal> and <literal>liblapack.so.3</literal>. For instance:
</para>
<screen>
<prompt>$ </prompt>LD_LIBRARY_PATH=$(nix-build -A mkl)/lib:$LD_LIBRARY_PATH nix-shell -p octave --run octave
</screen>
<para>
Intel MKL requires an <literal>openmp</literal> implementation
when running with multiple processors. By default,
<literal>mkl</literal> will use Intel’s <literal>iomp</literal>
implementation if no other is specified, but this is a
runtime-only dependency and binary compatible with the LLVM
implementation. To use that one instead, Intel recommends users
set it with <literal>LD_PRELOAD</literal>. Note that
<literal>mkl</literal> is only available on
<literal>x86_64-linux</literal> and
<literal>x86_64-darwin</literal>. Moreover, Hydra is not
building and distributing pre-compiled binaries using it.
</para>
<para>
For BLAS/LAPACK switching to work correctly, all packages must
depend on <literal>blas</literal> or <literal>lapack</literal>.
This ensures that only one BLAS/LAPACK library is used at one
time. There are two versions versions of BLAS/LAPACK currently
in the wild, <literal>LP64</literal> (integer size = 32 bits)
and <literal>ILP64</literal> (integer size = 64 bits). Some
software needs special flags or patches to work with
<literal>ILP64</literal>. You can check if
<literal>ILP64</literal> is used in Nixpkgs with
<varname>blas.isILP64</varname> and
<varname>lapack.isILP64</varname>. Some software does NOT work
with <literal>ILP64</literal>, and derivations need to specify
an assertion to prevent this. You can prevent
<literal>ILP64</literal> from being used with the following:
</para>
<programlisting>
<para>
Intel MKL requires an <literal>openmp</literal> implementation when running with multiple processors. By default, <literal>mkl</literal> will use Intel’s <literal>iomp</literal> implementation if no other is specified, but this is a runtime-only dependency and binary compatible with the LLVM implementation. To use that one instead, Intel recommends users set it with <literal>LD_PRELOAD</literal>. Note that <literal>mkl</literal> is only available on <literal>x86_64-linux</literal> and <literal>x86_64-darwin</literal>. Moreover, Hydra is not building and distributing pre-compiled binaries using it.
</para>
<para>
For BLAS/LAPACK switching to work correctly, all packages must depend on <literal>blas</literal> or <literal>lapack</literal>. This ensures that only one BLAS/LAPACK library is used at one time. There are two versions of BLAS/LAPACK currently in the wild, <literal>LP64</literal> (integer size = 32 bits) and <literal>ILP64</literal> (integer size = 64 bits). Some software needs special flags or patches to work with <literal>ILP64</literal>. You can check if <literal>ILP64</literal> is used in Nixpkgs with <varname>blas.isILP64</varname> and <varname>lapack.isILP64</varname>. Some software does NOT work with <literal>ILP64</literal>, and derivations need to specify an assertion to prevent this. You can prevent <literal>ILP64</literal> from being used with the following:
</para>
<programlisting>
{ stdenv, blas, lapack, ... }:
assert (!blas.isILP64) &amp;&amp; (!lapack.isILP64);
@ -291,41 +242,38 @@ stdenv.mkDerivation {
...
}
</programlisting>
</section>
<section xml:id="sec-overlays-alternatives-mpi">
<title>Switching the MPI implementation</title>
<para>
All programs that are built with
<link xlink:href="https://en.wikipedia.org/wiki/Message_Passing_Interface">MPI</link>
support use the generic attribute <varname>mpi</varname>
as an input. At the moment Nixpkgs natively provides two different
MPI implementations:
<itemizedlist>
<listitem>
<para>
<link xlink:href="https://www.open-mpi.org/">Open MPI</link>
(default), attribute name <varname>openmpi</varname>
</para>
</listitem>
<listitem>
<para>
<link xlink:href="https://www.mpich.org/">MPICH</link>,
attribute name <varname>mpich</varname>
</para>
</listitem>
</itemizedlist>
</para>
<para>
To provide MPI enabled applications that use <literal>MPICH</literal>, instead
of the default <literal>Open MPI</literal>, simply use the following overlay:
</para>
<programlisting>
</section>
<section xml:id="sec-overlays-alternatives-mpi">
<title>Switching the MPI implementation</title>
<para>
All programs that are built with <link xlink:href="https://en.wikipedia.org/wiki/Message_Passing_Interface">MPI</link> support use the generic attribute <varname>mpi</varname> as an input. At the moment Nixpkgs natively provides two different MPI implementations:
<itemizedlist>
<listitem>
<para>
<link xlink:href="https://www.open-mpi.org/">Open MPI</link> (default), attribute name <varname>openmpi</varname>
</para>
</listitem>
<listitem>
<para>
<link xlink:href="https://www.mpich.org/">MPICH</link>, attribute name <varname>mpich</varname>
</para>
</listitem>
</itemizedlist>
</para>
<para>
To provide MPI enabled applications that use <literal>MPICH</literal>, instead of the default <literal>Open MPI</literal>, simply use the following overlay:
</para>
<programlisting>
self: super:
{
mpi = self.mpich;
}
</programlisting>
</section>
</section>
</section>
</chapter>

@ -219,16 +219,17 @@ rec {
/* Like the above, but aims to support cross compilation. It's still ugly, but
hopefully it helps a little bit. */
makeScopeWithSplicing = splicePackages: newScope: otherSplices: keep: f:
makeScopeWithSplicing = splicePackages: newScope: otherSplices: keep: extra: f:
let
spliced = splicePackages {
spliced0 = splicePackages {
pkgsBuildBuild = otherSplices.selfBuildBuild;
pkgsBuildHost = otherSplices.selfBuildHost;
pkgsBuildTarget = otherSplices.selfBuildTarget;
pkgsHostHost = otherSplices.selfHostHost;
pkgsHostTarget = self; # Not `otherSplices.selfHostTarget`;
pkgsTargetTarget = otherSplices.selfTargetTarget;
} // keep self;
};
spliced = extra spliced0 // spliced0 // keep self;
self = f self // {
newScope = scope: newScope (spliced // scope);
callPackage = newScope spliced; # == self.newScope {};
@ -239,6 +240,7 @@ rec {
newScope
otherSplices
keep
extra
(lib.fixedPoints.extends g f);
packages = f;
};

@ -66,8 +66,9 @@ let
stringLength sub substring tail trace;
inherit (self.trivial) id const pipe concat or and bitAnd bitOr bitXor
bitNot boolToString mergeAttrs flip mapNullable inNixShell isFloat min max
importJSON importTOML warn info showWarnings nixpkgsVersion version mod compare
splitByAndCompare functionArgs setFunctionArgs isFunction toHexString toBaseDigits;
importJSON importTOML warn warnIf info showWarnings nixpkgsVersion version
mod compare splitByAndCompare functionArgs setFunctionArgs isFunction
toHexString toBaseDigits;
inherit (self.fixedPoints) fix fix' converge extends composeExtensions
composeManyExtensions makeExtensible makeExtensibleWithCustomName;
inherit (self.attrsets) attrByPath hasAttrByPath setAttrByPath

@ -307,4 +307,28 @@ rec {
${expr "" v}
</plist>'';
/* Translate a simple Nix expression to Dhall notation.
* Note that integers are translated to Integer and never
* the Natural type.
*/
toDhall = { }@args: v:
with builtins;
let concatItems = lib.strings.concatStringsSep ", ";
in if isAttrs v then
"{ ${
concatItems (lib.attrsets.mapAttrsToList
(key: value: "${key} = ${toDhall args value}") v)
} }"
else if isList v then
"[ ${concatItems (map (toDhall args) v)} ]"
else if isInt v then
"${if v < 0 then "" else "+"}${toString v}"
else if isBool v then
(if v then "True" else "False")
else if isFunction v then
abort "generators.toDhall: cannot convert a function to Dhall"
else if isNull v then
abort "generators.toDhall: cannot convert a null to Dhall"
else
builtins.toJSON v;
}

@ -125,6 +125,11 @@ lib.mapAttrs (n: v: v // { shortName = n; }) ({
fullName = ''BSD 4-clause "Original" or "Old" License'';
};
bsdOriginalUC = spdx {
spdxId = "BSD-4-Clause-UC";
fullName = "BSD 4-Clause University of California-Specific";
};
bsdProtection = spdx {
spdxId = "BSD-Protection";
fullName = "BSD Protection License";
@ -603,6 +608,11 @@ lib.mapAttrs (n: v: v // { shortName = n; }) ({
free = false;
};
odbl = spdx {
spdxId = "ODbL-1.0";
fullName = "Open Data Commons Open Database License v1.0";
};
ofl = spdx {
spdxId = "OFL-1.1";
fullName = "SIL Open Font License 1.1";

@ -23,6 +23,7 @@ let
isAttrs
isBool
isFunction
isList
isString
length
mapAttrs
@ -37,7 +38,7 @@ let
setAttrByPath
toList
types
warn
warnIf
;
inherit (lib.options)
isOption
@ -188,6 +189,9 @@ rec {
loadModule = args: fallbackFile: fallbackKey: m:
if isFunction m || isAttrs m then
unifyModuleSyntax fallbackFile fallbackKey (applyIfFunction fallbackKey m args)
else if isList m then
let defs = [{ file = fallbackFile; value = m; }]; in
throw "Module imports can't be nested lists. Perhaps you meant to remove one level of lists? Definitions: ${showDefs defs}"
else unifyModuleSyntax (toString m) (toString m) (applyIfFunction (toString m) (import m) args);
/*
@ -295,13 +299,11 @@ rec {
# a module will resolve strictly the attributes used as argument but
# not their values. The values are forwarding the result of the
# evaluation of the option.
requiredArgs = builtins.attrNames (lib.functionArgs f);
context = name: ''while evaluating the module argument `${name}' in "${key}":'';
extraArgs = builtins.listToAttrs (map (name: {
inherit name;
value = builtins.addErrorContext (context name)
(args.${name} or config._module.args.${name});
}) requiredArgs);
extraArgs = builtins.mapAttrs (name: _:
builtins.addErrorContext (context name)
(args.${name} or config._module.args.${name})
) (lib.functionArgs f);
# Note: we append in the opposite order such that we can add an error
# context on the explicited arguments of "args" too. This update
@ -361,6 +363,17 @@ rec {
*/
byName = attr: f: modules:
foldl' (acc: module:
if !(builtins.isAttrs module.${attr}) then
throw ''
You're trying to declare a value of type `${builtins.typeOf module.${attr}}'
rather than an attribute-set for the option
`${builtins.concatStringsSep "." prefix}'!
This usually happens if `${builtins.concatStringsSep "." prefix}' has option
definitions inside that are not matched. Please check how to properly define
this option by e.g. referring to `man 5 configuration.nix'!
''
else
acc // (mapAttrs (n: v:
(acc.${n} or []) ++ f module v
) module.${attr}
@ -505,8 +518,8 @@ rec {
value = if opt ? apply then opt.apply res.mergedValue else res.mergedValue;
warnDeprecation =
if opt.type.deprecationMessage == null then id
else warn "The type `types.${opt.type.name}' of option `${showOption loc}' defined in ${showFiles opt.declarations} is deprecated. ${opt.type.deprecationMessage}";
warnIf (opt.type.deprecationMessage != null)
"The type `types.${opt.type.name}' of option `${showOption loc}' defined in ${showFiles opt.declarations} is deprecated. ${opt.type.deprecationMessage}";
in warnDeprecation opt //
{ value = builtins.addErrorContext "while evaluating the option `${showOption loc}':" value;

@ -138,12 +138,13 @@ rec {
in if m == null
then throw ("File contains no gitdir reference: " + path)
else
let gitDir = absolutePath (dirOf path) (lib.head m);
commonDir' = if pathIsRegularFile "${gitDir}/commondir"
then lib.fileContents "${gitDir}/commondir"
else gitDir;
commonDir = absolutePath gitDir commonDir';
refFile = lib.removePrefix "${commonDir}/" "${gitDir}/${file}";
let gitDir = absolutePath (dirOf path) (lib.head m);
commonDir'' = if pathIsRegularFile "${gitDir}/commondir"
then lib.fileContents "${gitDir}/commondir"
else gitDir;
commonDir' = lib.removeSuffix "/" commonDir'';
commonDir = absolutePath gitDir commonDir';
refFile = lib.removePrefix "${commonDir}/" "${gitDir}/${file}";
in readCommitFromFile refFile commonDir
else if pathIsRegularFile fileName

@ -606,7 +606,7 @@ rec {
This function will fail if the input string is longer than the
requested length.
Type: fixedWidthString :: int -> string -> string
Type: fixedWidthString :: int -> string -> string -> string
Example:
fixedWidthString 5 "0" (toString 15)
@ -644,8 +644,8 @@ rec {
floatToString = float: let
result = toString float;
precise = float == fromJSON result;
in if precise then result
else lib.warn "Imprecise conversion from float to string ${result}" result;
in lib.warnIf (!precise) "Imprecise conversion from float to string ${result}"
result;
/* Check whether a value can be coerced to a string */
isCoercibleToString = x:

@ -107,6 +107,24 @@ rec {
powerpc64le = "ppc64le";
}.${final.parsed.cpu.name} or final.parsed.cpu.name;
darwinArch = {
armv7a = "armv7";
aarch64 = "arm64";
}.${final.parsed.cpu.name} or final.parsed.cpu.name;
darwinPlatform =
if final.isMacOS then "macos"
else if final.isiOS then "ios"
else null;
# The canonical name for this attribute is darwinSdkVersion, but some
# platforms define the old name "sdkVer".
darwinSdkVersion = final.sdkVer or "10.12";
darwinMinVersion = final.darwinSdkVersion;
darwinMinVersionVariable =
if final.isMacOS then "MACOSX_DEPLOYMENT_TARGET"
else if final.isiOS then "IPHONEOS_DEPLOYMENT_TARGET"
else null;
emulator = pkgs: let
qemu-user = pkgs.qemu.override {
smartcardSupport = false;

@ -6,43 +6,53 @@ let
inherit (lib.attrsets) matchAttrs;
all = [
"aarch64-linux"
"armv5tel-linux" "armv6l-linux" "armv7a-linux" "armv7l-linux"
# Cygwin
"i686-cygwin" "x86_64-cygwin"
"mipsel-linux"
# Darwin
"x86_64-darwin" "i686-darwin" "aarch64-darwin" "armv7a-darwin"
"i686-cygwin" "i686-freebsd" "i686-linux" "i686-netbsd" "i686-openbsd"
# FreeBSD
"i686-freebsd" "x86_64-freebsd"
"x86_64-cygwin" "x86_64-freebsd" "x86_64-linux"
"x86_64-netbsd" "x86_64-openbsd" "x86_64-solaris"
# Genode
"aarch64-genode" "i686-genode" "x86_64-genode"
"x86_64-darwin" "i686-darwin" "aarch64-darwin" "armv7a-darwin"
# illumos
"x86_64-solaris"
"x86_64-windows" "i686-windows"
# JS
"js-ghcjs"
"wasm64-wasi" "wasm32-wasi"
# Linux
"aarch64-linux" "armv5tel-linux" "armv6l-linux" "armv7a-linux"
"armv7l-linux" "i686-linux" "mipsel-linux" "powerpc64-linux"
"powerpc64le-linux" "riscv32-linux" "riscv64-linux" "x86_64-linux"
"x86_64-redox"
# MMIXware
"mmix-mmixware"
"powerpc64-linux"
"powerpc64le-linux"
# NetBSD
"aarch64-netbsd" "armv6l-netbsd" "armv7a-netbsd" "armv7l-netbsd"
"i686-netbsd" "mipsel-netbsd" "powerpc-netbsd" "riscv32-netbsd"
"riscv64-netbsd" "x86_64-netbsd"
"riscv32-linux" "riscv64-linux"
# none
"aarch64-none" "arm-none" "armv6l-none" "avr-none" "i686-none" "msp430-none"
"or1k-none" "powerpc-none" "riscv32-none" "riscv64-none" "vc4-none"
"x86_64-none"
"arm-none" "armv6l-none" "aarch64-none"
"avr-none"
"i686-none" "x86_64-none"
"powerpc-none"
"msp430-none"
"riscv64-none" "riscv32-none"
"vc4-none"
"or1k-none"
# OpenBSD
"i686-openbsd" "x86_64-openbsd"
"mmix-mmixware"
# Redox
"x86_64-redox"
"js-ghcjs"
# WASI
"wasm64-wasi" "wasm32-wasi"
"aarch64-genode" "i686-genode" "x86_64-genode"
# Windows
"x86_64-windows" "i686-windows"
];
allParsed = map parse.mkSystemFromString all;
@ -73,7 +83,7 @@ in {
darwin = filterDoubles predicates.isDarwin;
freebsd = filterDoubles predicates.isFreeBSD;
# Should be better, but MinGW is unclear.
gnu = filterDoubles (matchAttrs { kernel = parse.kernels.linux; abi = parse.abis.gnu; }) ++ filterDoubles (matchAttrs { kernel = parse.kernels.linux; abi = parse.abis.gnueabi; }) ++ filterDoubles (matchAttrs { kernel = parse.kernels.linux; abi = parse.abis.gnueabihf; }) ++ filterDoubles (matchAttrs { kernel = parse.kernels.linux; abi = parse.abis.elfv1; }) ++ filterDoubles (matchAttrs { kernel = parse.kernels.linux; abi = parse.abis.elfv2; });
gnu = filterDoubles (matchAttrs { kernel = parse.kernels.linux; abi = parse.abis.gnu; }) ++ filterDoubles (matchAttrs { kernel = parse.kernels.linux; abi = parse.abis.gnueabi; }) ++ filterDoubles (matchAttrs { kernel = parse.kernels.linux; abi = parse.abis.gnueabihf; });
illumos = filterDoubles predicates.isSunOS;
linux = filterDoubles predicates.isLinux;
netbsd = filterDoubles predicates.isNetBSD;

@ -21,14 +21,10 @@ rec {
config = "powerpc64le-unknown-linux-musl";
};
ppc64-elfv1 = {
config = "powerpc64-unknown-linux-elfv1";
};
ppc64-elfv2 = {
config = "powerpc64-unknown-linux-elfv2";
ppc64 = {
config = "powerpc64-unknown-linux-gnu";
gcc = { abi = "elfv2"; }; # for gcc configuration
};
ppc64 = ppc64-elfv2; # default to modern elfv2
ppc64-musl = {
config = "powerpc64-unknown-linux-musl";
gcc = { abi = "elfv2"; }; # for gcc configuration
@ -60,6 +56,7 @@ rec {
armv7a-android-prebuilt = {
config = "armv7a-unknown-linux-androideabi";
rustc.config = "armv7-linux-androideabi";
sdkVer = "29";
ndkVer = "21";
useAndroidPrebuilt = true;
@ -67,6 +64,7 @@ rec {
aarch64-android-prebuilt = {
config = "aarch64-unknown-linux-android";
rustc.config = "aarch64-linux-android";
sdkVer = "29";
ndkVer = "21";
useAndroidPrebuilt = true;
@ -219,6 +217,7 @@ rec {
sdkVer = "14.3";
xcodeVer = "12.3";
xcodePlatform = "iPhoneSimulator";
darwinPlatform = "ios-simulator";
useiOSPrebuilt = true;
};
@ -228,6 +227,7 @@ rec {
sdkVer = "14.3";
xcodeVer = "12.3";
xcodePlatform = "iPhoneSimulator";
darwinPlatform = "ios-simulator";
useiOSPrebuilt = true;
};
@ -250,11 +250,19 @@ rec {
# BSDs
amd64-netbsd = {
amd64-netbsd = lib.warn "The amd64-netbsd system example is deprecated. Use x86_64-netbsd instead." x86_64-netbsd;
x86_64-netbsd = {
config = "x86_64-unknown-netbsd";
libc = "nblibc";
};
x86_64-netbsd-llvm = {
config = "x86_64-unknown-netbsd";
libc = "nblibc";
useLLVM = true;
};
#
# WASM
#

@ -337,18 +337,10 @@ rec {
The "gnu" ABI is ambiguous on 32-bit ARM. Use "gnueabi" or "gnueabihf" instead.
'';
}
{ assertion = platform: platform.system != "powerpc64-linux";
message = ''
The "gnu" ABI is ambiguous on big-endian 64-bit PPC. Use "elfv1" or "elfv2" instead.
'';
}
];
};
gnuabi64 = { abi = "64"; };
elfv1 = { abi = "elfv1"; };
elfv2 = { abi = "elfv2"; };
musleabi = { float = "soft"; };
musleabihf = { float = "hard"; };
musl = {};
@ -452,7 +444,6 @@ rec {
if lib.versionAtLeast (parsed.cpu.version or "0") "6"
then abis.gnueabihf
else abis.gnueabi
else if cpu == "powerpc64" then abis.elfv2
else abis.gnu
else abis.unknown;
};

@ -303,14 +303,12 @@ rec {
preferBuiltin = true;
target = "zImage";
extraConfig = ''
# Serial port for Raspberry Pi 3. Upstream forgot to add it to the ARMv7 defconfig.
# Serial port for Raspberry Pi 3. Wasn't included in ARMv7 defconfig
# until 4.17.
SERIAL_8250_BCM2835AUX y
SERIAL_8250_EXTENDED y
SERIAL_8250_SHARE_IRQ y
# Fix broken sunxi-sid nvmem driver.
TI_CPTS y
# Hangs ODROID-XU4
ARM_BIG_LITTLE_CPUIDLE n

@ -169,12 +169,15 @@ checkConfigOutput "foo" config.submodule.foo ./declare-submoduleWith-special.nix
## shorthandOnlyDefines config behaves as expected
checkConfigOutput "true" config.submodule.config ./declare-submoduleWith-shorthand.nix ./define-submoduleWith-shorthand.nix
checkConfigError 'is not of type `boolean' config.submodule.config ./declare-submoduleWith-shorthand.nix ./define-submoduleWith-noshorthand.nix
checkConfigError 'value is a boolean while a set was expected' config.submodule.config ./declare-submoduleWith-noshorthand.nix ./define-submoduleWith-shorthand.nix
checkConfigError "You're trying to declare a value of type \`bool'\nrather than an attribute-set for the option" config.submodule.config ./declare-submoduleWith-noshorthand.nix ./define-submoduleWith-shorthand.nix
checkConfigOutput "true" config.submodule.config ./declare-submoduleWith-noshorthand.nix ./define-submoduleWith-noshorthand.nix
## submoduleWith should merge all modules in one swoop
checkConfigOutput "true" config.submodule.inner ./declare-submoduleWith-modules.nix
checkConfigOutput "true" config.submodule.outer ./declare-submoduleWith-modules.nix
# Should also be able to evaluate the type name (which evaluates freeformType,
# which evaluates all the modules defined by the type)
checkConfigOutput "submodule" options.submodule.type.description ./declare-submoduleWith-modules.nix
## Paths should be allowed as values and work as expected
checkConfigOutput "true" config.submodule.enable ./declare-submoduleWith-path.nix

@ -8,9 +8,6 @@
default = false;
};
}
{
outer = true;
}
];
};
default = {};
@ -25,6 +22,7 @@
})
{
inner = true;
outer = true;
}
];
}

@ -15,9 +15,9 @@ in
with lib.systems.doubles; lib.runTests {
testall = mseteq all (linux ++ darwin ++ freebsd ++ openbsd ++ netbsd ++ illumos ++ wasi ++ windows ++ embedded ++ mmix ++ js ++ genode ++ redox);
testarm = mseteq arm [ "armv5tel-linux" "armv6l-linux" "armv6l-none" "armv7a-linux" "armv7l-linux" "arm-none" "armv7a-darwin" ];
testarm = mseteq arm [ "armv5tel-linux" "armv6l-linux" "armv6l-netbsd" "armv6l-none" "armv7a-linux" "armv7a-netbsd" "armv7l-linux" "armv7l-netbsd" "arm-none" "armv7a-darwin" ];
testi686 = mseteq i686 [ "i686-linux" "i686-freebsd" "i686-genode" "i686-netbsd" "i686-openbsd" "i686-cygwin" "i686-windows" "i686-none" "i686-darwin" ];
testmips = mseteq mips [ "mipsel-linux" ];
testmips = mseteq mips [ "mipsel-linux" "mipsel-netbsd" ];
testmmix = mseteq mmix [ "mmix-mmixware" ];
testx86_64 = mseteq x86_64 [ "x86_64-linux" "x86_64-darwin" "x86_64-freebsd" "x86_64-genode" "x86_64-redox" "x86_64-openbsd" "x86_64-netbsd" "x86_64-cygwin" "x86_64-solaris" "x86_64-windows" "x86_64-none" ];
@ -29,7 +29,7 @@ with lib.systems.doubles; lib.runTests {
testgnu = mseteq gnu (linux /* ++ kfreebsd ++ ... */);
testillumos = mseteq illumos [ "x86_64-solaris" ];
testlinux = mseteq linux [ "aarch64-linux" "armv5tel-linux" "armv6l-linux" "armv7a-linux" "armv7l-linux" "i686-linux" "mipsel-linux" "riscv32-linux" "riscv64-linux" "x86_64-linux" "powerpc64-linux" "powerpc64le-linux" ];
testnetbsd = mseteq netbsd [ "i686-netbsd" "x86_64-netbsd" ];
testnetbsd = mseteq netbsd [ "aarch64-netbsd" "armv6l-netbsd" "armv7a-netbsd" "armv7l-netbsd" "i686-netbsd" "mipsel-netbsd" "powerpc-netbsd" "riscv32-netbsd" "riscv64-netbsd" "x86_64-netbsd" ];
testopenbsd = mseteq openbsd [ "i686-openbsd" "x86_64-openbsd" ];
testwindows = mseteq windows [ "i686-cygwin" "x86_64-cygwin" "i686-windows" "x86_64-windows" ];
testunix = mseteq unix (linux ++ darwin ++ freebsd ++ openbsd ++ netbsd ++ illumos ++ cygwin ++ redox);

@ -158,7 +158,7 @@ rec {
seq deepSeq genericClosure;
## nixpks version strings
## nixpkgs version strings
/* Returns the current full nixpkgs version number. */
version = release + versionSuffix;
@ -297,12 +297,15 @@ rec {
# Usage:
# {
# foo = lib.warn "foo is deprecated" oldFoo;
# bar = lib.warnIf (bar == "") "Empty bar is deprecated" bar;
# }
#
# TODO: figure out a clever way to integrate location information from
# something like __unsafeGetAttrPos.
warn = msg: builtins.trace "warning: ${msg}";
warnIf = cond: msg: if cond then warn msg else id;
info = msg: builtins.trace "INFO: ${msg}";
showWarnings = warnings: res: lib.fold (w: x: warn w x) res warnings;

@ -147,9 +147,13 @@ rec {
, # The deprecation message to display when this type is used by an option
# If null, the type isn't deprecated
deprecationMessage ? null
, # The types that occur in the definition of this type. This is used to
# issue deprecation warnings recursively. Can also be used to reuse
# nested types
nestedTypes ? {}
}:
{ _type = "option-type";
inherit name check merge emptyValue getSubOptions getSubModules substSubModules typeMerge functor deprecationMessage;
inherit name check merge emptyValue getSubOptions getSubModules substSubModules typeMerge functor deprecationMessage nestedTypes;
description = if description == null then name else description;
};
@ -337,7 +341,7 @@ rec {
};
shellPackage = package // {
check = x: (package.check x) && (hasAttr "shellPath" x);
check = x: isDerivation x && hasAttr "shellPath" x;
};
path = mkOptionType {
@ -365,6 +369,7 @@ rec {
getSubModules = elemType.getSubModules;
substSubModules = m: listOf (elemType.substSubModules m);
functor = (defaultFunctor name) // { wrapped = elemType; };
nestedTypes.elemType = elemType;
};
nonEmptyListOf = elemType:
@ -389,6 +394,7 @@ rec {
getSubModules = elemType.getSubModules;
substSubModules = m: attrsOf (elemType.substSubModules m);
functor = (defaultFunctor name) // { wrapped = elemType; };
nestedTypes.elemType = elemType;
};
# A version of attrsOf that's lazy in its values at the expense of
@ -413,6 +419,7 @@ rec {
getSubModules = elemType.getSubModules;
substSubModules = m: lazyAttrsOf (elemType.substSubModules m);
functor = (defaultFunctor name) // { wrapped = elemType; };
nestedTypes.elemType = elemType;
};
# TODO: drop this in the future:
@ -421,6 +428,7 @@ rec {
deprecationMessage = "Mixing lists with attribute values is no longer"
+ " possible; please use `types.attrsOf` instead. See"
+ " https://github.com/NixOS/nixpkgs/issues/1800 for the motivation.";
nestedTypes.elemType = elemType;
};
# Value of given type but with no merging (i.e. `uniq list`s are not concatenated).
@ -433,6 +441,7 @@ rec {
getSubModules = elemType.getSubModules;
substSubModules = m: uniq (elemType.substSubModules m);
functor = (defaultFunctor name) // { wrapped = elemType; };
nestedTypes.elemType = elemType;
};
# Null or value of ...
@ -451,6 +460,7 @@ rec {
getSubModules = elemType.getSubModules;
substSubModules = m: nullOr (elemType.substSubModules m);
functor = (defaultFunctor name) // { wrapped = elemType; };
nestedTypes.elemType = elemType;
};
functionTo = elemType: mkOptionType {
@ -535,6 +545,9 @@ rec {
substSubModules = m: submoduleWith (attrs // {
modules = m;
});
nestedTypes = lib.optionalAttrs (freeformType != null) {
freeformType = freeformType;
};
functor = defaultFunctor name // {
type = types.submoduleWith;
payload = {
@ -596,6 +609,8 @@ rec {
then functor.type mt1 mt2
else null;
functor = (defaultFunctor name) // { wrapped = [ t1 t2 ]; };
nestedTypes.left = t1;
nestedTypes.right = t2;
};
# Any of the types in the given list
@ -627,6 +642,8 @@ rec {
substSubModules = m: coercedTo coercedType coerceFunc (finalType.substSubModules m);
typeMerge = t1: t2: null;
functor = (defaultFunctor name) // { wrapped = finalType; };
nestedTypes.coercedType = coercedType;
nestedTypes.finalType = finalType;
};
# Obsolete alternative to configOf. It takes its option

File diff suppressed because it is too large Load Diff

@ -38,6 +38,7 @@ lua-messagepack,,,,,
lua-resty-http,,,,,
lua-resty-jwt,,,,,
lua-resty-openidc,,,,,
lua-resty-openssl,,,,,
lua-resty-session,,,,,
lua-term,,,,,
lua-toml,,,,,

1 # nix name luarocks name server version luaversion maintainers
38 lua-resty-http
39 lua-resty-jwt
40 lua-resty-openidc
41 lua-resty-openssl
42 lua-resty-session
43 lua-term
44 lua-toml

@ -18,7 +18,7 @@ stdenv.mkDerivation {
'';
meta = {
maintainers = with lib.maintainers; [ eelco rycee ];
maintainers = with lib.maintainers; [ eelco ];
description = "Utility to generate a Nix expression for a Perl package from CPAN";
platforms = lib.platforms.unix;
};

@ -0,0 +1,537 @@
# Used by pkgs/misc/vim-plugins/update.py and pkgs/applications/editors/kakoune/plugins/update.py
# format:
# $ nix run nixpkgs.python3Packages.black -c black update.py
# type-check:
# $ nix run nixpkgs.python3Packages.mypy -c mypy update.py
# linted:
# $ nix run nixpkgs.python3Packages.flake8 -c flake8 --ignore E501,E265 update.py
import argparse
import functools
import http
import json
import os
import subprocess
import sys
import time
import traceback
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime
from functools import wraps
from multiprocessing.dummy import Pool
from pathlib import Path
from typing import Dict, List, Optional, Tuple, Union, Any, Callable
from urllib.parse import urljoin, urlparse
from tempfile import NamedTemporaryFile
import git
ATOM_ENTRY = "{http://www.w3.org/2005/Atom}entry" # " vim gets confused here
ATOM_LINK = "{http://www.w3.org/2005/Atom}link" # "
ATOM_UPDATED = "{http://www.w3.org/2005/Atom}updated" # "
def retry(ExceptionToCheck: Any, tries: int = 4, delay: float = 3, backoff: float = 2):
"""Retry calling the decorated function using an exponential backoff.
http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/
original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry
(BSD licensed)
:param ExceptionToCheck: the exception on which to retry
:param tries: number of times to try (not retry) before giving up
:param delay: initial delay between retries in seconds
:param backoff: backoff multiplier e.g. value of 2 will double the delay
each retry
"""
def deco_retry(f: Callable) -> Callable:
@wraps(f)
def f_retry(*args: Any, **kwargs: Any) -> Any:
mtries, mdelay = tries, delay
while mtries > 1:
try:
return f(*args, **kwargs)
except ExceptionToCheck as e:
print(f"{str(e)}, Retrying in {mdelay} seconds...")
time.sleep(mdelay)
mtries -= 1
mdelay *= backoff
return f(*args, **kwargs)
return f_retry # true decorator
return deco_retry
def make_request(url: str) -> urllib.request.Request:
token = os.getenv("GITHUB_API_TOKEN")
headers = {}
if token is not None:
headers["Authorization"] = f"token {token}"
return urllib.request.Request(url, headers=headers)
class Repo:
def __init__(
self, owner: str, name: str, branch: str, alias: Optional[str]
) -> None:
self.owner = owner
self.name = name
self.branch = branch
self.alias = alias
self.redirect: Dict[str, str] = {}
def url(self, path: str) -> str:
return urljoin(f"https://github.com/{self.owner}/{self.name}/", path)
def __repr__(self) -> str:
return f"Repo({self.owner}, {self.name})"
@retry(urllib.error.URLError, tries=4, delay=3, backoff=2)
def has_submodules(self) -> bool:
try:
req = make_request(self.url(f"blob/{self.branch}/.gitmodules"))
urllib.request.urlopen(req, timeout=10).close()
except urllib.error.HTTPError as e:
if e.code == 404:
return False
else:
raise
return True
@retry(urllib.error.URLError, tries=4, delay=3, backoff=2)
def latest_commit(self) -> Tuple[str, datetime]:
commit_url = self.url(f"commits/{self.branch}.atom")
commit_req = make_request(commit_url)
with urllib.request.urlopen(commit_req, timeout=10) as req:
self.check_for_redirect(commit_url, req)
xml = req.read()
root = ET.fromstring(xml)
latest_entry = root.find(ATOM_ENTRY)
assert latest_entry is not None, f"No commits found in repository {self}"
commit_link = latest_entry.find(ATOM_LINK)
assert commit_link is not None, f"No link tag found feed entry {xml}"
url = urlparse(commit_link.get("href"))
updated_tag = latest_entry.find(ATOM_UPDATED)
assert (
updated_tag is not None and updated_tag.text is not None
), f"No updated tag found feed entry {xml}"
updated = datetime.strptime(updated_tag.text, "%Y-%m-%dT%H:%M:%SZ")
return Path(str(url.path)).name, updated
def check_for_redirect(self, url: str, req: http.client.HTTPResponse):
response_url = req.geturl()
if url != response_url:
new_owner, new_name = (
urllib.parse.urlsplit(response_url).path.strip("/").split("/")[:2]
)
end_line = "\n" if self.alias is None else f" as {self.alias}\n"
plugin_line = "{owner}/{name}" + end_line
old_plugin = plugin_line.format(owner=self.owner, name=self.name)
new_plugin = plugin_line.format(owner=new_owner, name=new_name)
self.redirect[old_plugin] = new_plugin
def prefetch_git(self, ref: str) -> str:
data = subprocess.check_output(
["nix-prefetch-git", "--fetch-submodules", self.url(""), ref]
)
return json.loads(data)["sha256"]
def prefetch_github(self, ref: str) -> str:
data = subprocess.check_output(
["nix-prefetch-url", "--unpack", self.url(f"archive/{ref}.tar.gz")]
)
return data.strip().decode("utf-8")
class Plugin:
def __init__(
self,
name: str,
commit: str,
has_submodules: bool,
sha256: str,
date: Optional[datetime] = None,
) -> None:
self.name = name
self.commit = commit
self.has_submodules = has_submodules
self.sha256 = sha256
self.date = date
@property
def normalized_name(self) -> str:
return self.name.replace(".", "-")
@property
def version(self) -> str:
assert self.date is not None
return self.date.strftime("%Y-%m-%d")
def as_json(self) -> Dict[str, str]:
copy = self.__dict__.copy()
del copy["date"]
return copy
class Editor:
"""The configuration of the update script."""
def __init__(
self,
name: str,
root: Path,
get_plugins: str,
generate_nix: Callable[[List[Tuple[str, str, Plugin]], str], None],
default_in: Optional[Path] = None,
default_out: Optional[Path] = None,
deprecated: Optional[Path] = None,
cache_file: Optional[str] = None,
):
self.name = name
self.root = root
self.get_plugins = get_plugins
self.generate_nix = generate_nix
self.default_in = default_in or root.joinpath(f"{name}-plugin-names")
self.default_out = default_out or root.joinpath("generated.nix")
self.deprecated = deprecated or root.joinpath("deprecated.json")
self.cache_file = cache_file or f"{name}-plugin-cache.json"
class CleanEnvironment(object):
def __enter__(self) -> None:
self.old_environ = os.environ.copy()
local_pkgs = str(Path(__file__).parent.parent.parent)
os.environ["NIX_PATH"] = f"localpkgs={local_pkgs}"
self.empty_config = NamedTemporaryFile()
self.empty_config.write(b"{}")
self.empty_config.flush()
os.environ["NIXPKGS_CONFIG"] = self.empty_config.name
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
os.environ.update(self.old_environ)
self.empty_config.close()
def get_current_plugins(editor: Editor) -> List[Plugin]:
with CleanEnvironment():
out = subprocess.check_output(["nix", "eval", "--json", editor.get_plugins])
data = json.loads(out)
plugins = []
for name, attr in data.items():
p = Plugin(name, attr["rev"], attr["submodules"], attr["sha256"])
plugins.append(p)
return plugins
def prefetch_plugin(
user: str,
repo_name: str,
branch: str,
alias: Optional[str],
cache: "Optional[Cache]" = None,
) -> Tuple[Plugin, Dict[str, str]]:
repo = Repo(user, repo_name, branch, alias)
commit, date = repo.latest_commit()
has_submodules = repo.has_submodules()
cached_plugin = cache[commit] if cache else None
if cached_plugin is not None:
cached_plugin.name = alias or repo_name
cached_plugin.date = date
return cached_plugin, repo.redirect
print(f"prefetch {user}/{repo_name}")
if has_submodules:
sha256 = repo.prefetch_git(commit)
else:
sha256 = repo.prefetch_github(commit)
return (
Plugin(alias or repo_name, commit, has_submodules, sha256, date=date),
repo.redirect,
)
def fetch_plugin_from_pluginline(plugin_line: str) -> Plugin:
plugin, _ = prefetch_plugin(*parse_plugin_line(plugin_line))
return plugin
def print_download_error(plugin: str, ex: Exception):
print(f"{plugin}: {ex}", file=sys.stderr)
ex_traceback = ex.__traceback__
tb_lines = [
line.rstrip("\n")
for line in traceback.format_exception(ex.__class__, ex, ex_traceback)
]
print("\n".join(tb_lines))
def check_results(
results: List[Tuple[str, str, Union[Exception, Plugin], Dict[str, str]]]
) -> Tuple[List[Tuple[str, str, Plugin]], Dict[str, str]]:
failures: List[Tuple[str, Exception]] = []
plugins = []
redirects: Dict[str, str] = {}
for (owner, name, result, redirect) in results:
if isinstance(result, Exception):
failures.append((name, result))
else:
plugins.append((owner, name, result))
redirects.update(redirect)
print(f"{len(results) - len(failures)} plugins were checked", end="")
if len(failures) == 0:
print()
return plugins, redirects
else:
print(f", {len(failures)} plugin(s) could not be downloaded:\n")
for (plugin, exception) in failures:
print_download_error(plugin, exception)
sys.exit(1)
def parse_plugin_line(line: str) -> Tuple[str, str, str, Optional[str]]:
branch = "master"
alias = None
name, repo = line.split("/")
if " as " in repo:
repo, alias = repo.split(" as ")
alias = alias.strip()
if "@" in repo:
repo, branch = repo.split("@")
return (name.strip(), repo.strip(), branch.strip(), alias)
def load_plugin_spec(plugin_file: str) -> List[Tuple[str, str, str, Optional[str]]]:
plugins = []
with open(plugin_file) as f:
for line in f:
plugin = parse_plugin_line(line)
if not plugin[0]:
msg = f"Invalid repository {line}, must be in the format owner/repo[ as alias]"
print(msg, file=sys.stderr)
sys.exit(1)
plugins.append(plugin)
return plugins
def get_cache_path(cache_file_name: str) -> Optional[Path]:
xdg_cache = os.environ.get("XDG_CACHE_HOME", None)
if xdg_cache is None:
home = os.environ.get("HOME", None)
if home is None:
return None
xdg_cache = str(Path(home, ".cache"))
return Path(xdg_cache, cache_file_name)
class Cache:
def __init__(self, initial_plugins: List[Plugin], cache_file_name: str) -> None:
self.cache_file = get_cache_path(cache_file_name)
downloads = {}
for plugin in initial_plugins:
downloads[plugin.commit] = plugin
downloads.update(self.load())
self.downloads = downloads
def load(self) -> Dict[str, Plugin]:
if self.cache_file is None or not self.cache_file.exists():
return {}
downloads: Dict[str, Plugin] = {}
with open(self.cache_file) as f:
data = json.load(f)
for attr in data.values():
p = Plugin(
attr["name"], attr["commit"], attr["has_submodules"], attr["sha256"]
)
downloads[attr["commit"]] = p
return downloads
def store(self) -> None:
if self.cache_file is None:
return
os.makedirs(self.cache_file.parent, exist_ok=True)
with open(self.cache_file, "w+") as f:
data = {}
for name, attr in self.downloads.items():
data[name] = attr.as_json()
json.dump(data, f, indent=4, sort_keys=True)
def __getitem__(self, key: str) -> Optional[Plugin]:
return self.downloads.get(key, None)
def __setitem__(self, key: str, value: Plugin) -> None:
self.downloads[key] = value
def prefetch(
args: Tuple[str, str, str, Optional[str]], cache: Cache
) -> Tuple[str, str, Union[Exception, Plugin], dict]:
assert len(args) == 4
owner, repo, branch, alias = args
try:
plugin, redirect = prefetch_plugin(owner, repo, branch, alias, cache)
cache[plugin.commit] = plugin
return (owner, repo, plugin, redirect)
except Exception as e:
return (owner, repo, e, {})
def rewrite_input(
input_file: Path,
deprecated: Path,
redirects: Dict[str, str] = None,
append: Tuple = (),
):
with open(input_file, "r") as f:
lines = f.readlines()
lines.extend(append)
if redirects:
lines = [redirects.get(line, line) for line in lines]
cur_date_iso = datetime.now().strftime("%Y-%m-%d")
with open(deprecated, "r") as f:
deprecations = json.load(f)
for old, new in redirects.items():
old_plugin = fetch_plugin_from_pluginline(old)
new_plugin = fetch_plugin_from_pluginline(new)
if old_plugin.normalized_name != new_plugin.normalized_name:
deprecations[old_plugin.normalized_name] = {
"new": new_plugin.normalized_name,
"date": cur_date_iso,
}
with open(deprecated, "w") as f:
json.dump(deprecations, f, indent=4, sort_keys=True)
f.write("\n")
lines = sorted(lines, key=str.casefold)
with open(input_file, "w") as f:
f.writelines(lines)
def parse_args(editor: Editor):
parser = argparse.ArgumentParser(
description=(
f"Updates nix derivations for {editor.name} plugins"
f"By default from {editor.default_in} to {editor.default_out}"
)
)
parser.add_argument(
"--add",
dest="add_plugins",
default=[],
action="append",
help=f"Plugin to add to {editor.name}Plugins from Github in the form owner/repo",
)
parser.add_argument(
"--input-names",
"-i",
dest="input_file",
default=editor.default_in,
help="A list of plugins in the form owner/repo",
)
parser.add_argument(
"--out",
"-o",
dest="outfile",
default=editor.default_out,
help="Filename to save generated nix code",
)
parser.add_argument(
"--proc",
"-p",
dest="proc",
type=int,
default=30,
help="Number of concurrent processes to spawn.",
)
parser.add_argument(
"--no-commit", "-n", action="store_true", default=False,
help="Whether to autocommit changes"
)
return parser.parse_args()
def commit(repo: git.Repo, message: str, files: List[Path]) -> None:
repo.index.add([str(f.resolve()) for f in files])
if repo.index.diff("HEAD"):
print(f'committing to nixpkgs "{message}"')
repo.index.commit(message)
else:
print("no changes in working tree to commit")
def get_update(input_file: str, outfile: str, proc: int, editor: Editor):
cache: Cache = Cache(get_current_plugins(editor), editor.cache_file)
_prefetch = functools.partial(prefetch, cache=cache)
def update() -> dict:
plugin_names = load_plugin_spec(input_file)
try:
pool = Pool(processes=proc)
results = pool.map(_prefetch, plugin_names)
finally:
cache.store()
plugins, redirects = check_results(results)
editor.generate_nix(plugins, outfile)
return redirects
return update
def update_plugins(editor: Editor):
"""The main entry function of this module. All input arguments are grouped in the `Editor`."""
args = parse_args(editor)
nixpkgs_repo = git.Repo(editor.root, search_parent_directories=True)
update = get_update(args.input_file, args.outfile, args.proc, editor)
redirects = update()
rewrite_input(args.input_file, editor.deprecated, redirects)
autocommit = not args.no_commit
if autocommit:
commit(nixpkgs_repo, f"{editor.name}Plugins: update", [args.outfile])
if redirects:
update()
if autocommit:
commit(
nixpkgs_repo,
f"{editor.name}Plugins: resolve github repository redirects",
[args.outfile, args.input_file, editor.deprecated],
)
for plugin_line in args.add_plugins:
rewrite_input(args.input_file, editor.deprecated, append=(plugin_line + "\n",))
update()
plugin = fetch_plugin_from_pluginline(plugin_line)
if autocommit:
commit(
nixpkgs_repo,
"{editor}Plugins.{name}: init at {version}".format(
editor=editor.name, name=plugin.normalized_name, version=plugin.version
),
[args.outfile, args.input_file],
)

@ -56,6 +56,15 @@ with lib.maintainers; {
scope = "Group registration for D. E. Shaw employees who collectively maintain packages.";
};
determinatesystems = {
# Verify additions to this team with at least one already existing member of the team.
members = [
cole-h
grahamc
];
scope = "Group registration for packages maintained by Determinate Systems.";
};
freedesktop = {
members = [ jtojnar worldofpeace ];
scope = "Maintain Freedesktop.org packages for graphical desktop.";
@ -82,20 +91,42 @@ with lib.maintainers; {
jtojnar
worldofpeace
dasj19
maxeaubrey
];
scope = "Maintain GNOME desktop environment and platform.";
};
home-assistant = {
members = [
fab
globin
hexa
mic92
];
scope = "Maintain the Home Assistant ecosystem";
};
jitsi = {
members = [
mmilata
petabyteboy
prusnak
ryantm
];
scope = "Maintain Jitsi.";
};
kodi = {
members = [
aanderse
cpages
edwtjo
minijackson
peterhoeg
sephalon
];
scope = "Maintain Kodi and related packages.";
};
matrix = {
members = [
ma27
@ -104,6 +135,7 @@ with lib.maintainers; {
mguentner
ekleog
ralith
mjlbach
];
scope = "Maintain the ecosystem around Matrix, a decentralized messenger.";
};
@ -134,6 +166,7 @@ with lib.maintainers; {
timokau
omasanori
raskin
collares
];
scope = "Maintain SageMath and the dependencies that are likely to break it.";
};

@ -1,5 +1,5 @@
.PHONY: all
all: manual-combined.xml format
all: manual-combined.xml
.PHONY: debug
debug: generated manual-combined.xml

@ -26,7 +26,11 @@ Enter passphrase for /dev/disk/by-uuid/3f6b0024-3a44-4fde-a43a-767b872abe5d: ***
<prompt># </prompt>mkfs.ext4 /dev/mapper/<replaceable>crypted</replaceable>
</screen>
To ensure that this file system is automatically mounted at boot time as
The LUKS volume should be automatically picked up by
<command>nixos-generate-config</command>, but you might want to verify that your
<filename>hardware-configuration.nix</filename> looks correct.
To manually ensure that the system is automatically mounted at boot time as
<filename>/</filename>, add the following to
<filename>configuration.nix</filename>:
<programlisting>

@ -133,7 +133,7 @@ true
<programlisting>
{ config, pkgs, ... }:
let netConfig = { hostName }: {
let netConfig = hostName: {
networking.hostName = hostName;
networking.useDHCP = false;
};

@ -150,7 +150,6 @@
<xref linkend="opt-services.xserver.videoDrivers"/> = [ "nvidiaLegacy390" ];
<xref linkend="opt-services.xserver.videoDrivers"/> = [ "nvidiaLegacy340" ];
<xref linkend="opt-services.xserver.videoDrivers"/> = [ "nvidiaLegacy304" ];
<xref linkend="opt-services.xserver.videoDrivers"/> = [ "nvidiaLegacy173" ];
</programlisting>
You may need to reboot after enabling this driver to prevent a clash with
other kernel modules.
@ -159,21 +158,16 @@
<simplesect xml:id="sec-x11--graphics-cards-amd">
<title>Proprietary AMD drivers</title>
<para>
AMD provides a proprietary driver for its graphics cards that has 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:
AMD provides a proprietary driver for its graphics cards that is not
enabled by default because it’s not Free Software, is often broken
in nixpkgs and as of this writing doesn't offer more features or
performance. If you still want to use it anyway, you need to explicitly set:
<programlisting>
<xref linkend="opt-services.xserver.videoDrivers"/> = [ "ati_unfree" ];
<xref linkend="opt-services.xserver.videoDrivers"/> = [ "amdgpu-pro" ];
</programlisting>
You will need to reboot after enabling this driver to prevent a clash with
other kernel modules.
</para>
<note>
<para>
For recent AMD GPUs you most likely want to keep either the defaults
or <literal>"amdgpu"</literal> (both free).
</para>
</note>
</simplesect>
<simplesect xml:id="sec-x11-touchpads">
<title>Touchpads</title>
@ -210,18 +204,18 @@
XKB
</link>
keyboard layouts using the option
<option>
<link linkend="opt-services.xserver.extraLayouts">
services.xserver.extraLayouts
</link>
</option>.
<option><link linkend="opt-services.xserver.extraLayouts">
services.xserver.extraLayouts</link></option>.
</para>
<para>
As a first example, we are going to create a layout based on the basic US
layout, with an additional layer to type some greek symbols by pressing the
right-alt key.
</para>
<para>
To do this we are going to create a <literal>us-greek</literal> file
with a <literal>xkb_symbols</literal> section.
Create a file called <literal>us-greek</literal> with the following
content (under a directory called <literal>symbols</literal>; it's
an XKB peculiarity that will help with testing):
</para>
<programlisting>
xkb_symbols &quot;us-greek&quot;
@ -237,14 +231,13 @@ xkb_symbols &quot;us-greek&quot;
};
</programlisting>
<para>
To install the layout, the filepath, a description and the list of
languages must be given:
A minimal layout specification must include the following:
</para>
<programlisting>
<xref linkend="opt-services.xserver.extraLayouts"/>.us-greek = {
description = "US layout with alt-gr greek";
languages = [ "eng" ];
symbolsFile = /path/to/us-greek;
symbolsFile = /yourpath/symbols/us-greek;
}
</programlisting>
<note>
@ -254,9 +247,27 @@ xkb_symbols &quot;us-greek&quot;
</para>
</note>
<para>
The layout should now be installed and ready to use: try it by
running <literal>setxkbmap us-greek</literal> and type
<literal>&lt;alt&gt;+a</literal>. To change the default the usual
Applying this customization requires rebuilding several packages,
and a broken XKB file can lead to the X session crashing at login.
Therefore, you're strongly advised to <emphasis role="strong">test
your layout before applying it</emphasis>:
<screen>
<prompt>$ </prompt>nix-shell -p xorg.xkbcomp
<prompt>$ </prompt>setxkbmap -I/yourpath us-greek -print | xkbcomp -I/yourpath - $DISPLAY
</screen>
</para>
<para>
You can inspect the predefined XKB files for examples:
<screen>
<prompt>$ </prompt>echo "$(nix-build --no-out-link '&lt;nixpkgs&gt;' -A xorg.xkeyboardconfig)/etc/X11/xkb/"
</screen>
</para>
<para>
Once the configuration is applied, and you did a logout/login
cycle, the layout should be ready to use. You can try it by e.g.
running <literal>setxkbmap us-greek</literal> and then type
<literal>&lt;alt&gt;+a</literal> (it may not get applied in your
terminal straight away). To change the default, the usual
<option>
<link linkend="opt-services.xserver.layout">
services.xserver.layout

@ -50,7 +50,7 @@
</varlistentry>
<varlistentry>
<term>
<varname>pkgs.formats.ini</varname> { <replaceable>listsAsDuplicateKeys</replaceable> ? false, ... }
<varname>pkgs.formats.ini</varname> { <replaceable>listsAsDuplicateKeys</replaceable> ? false, <replaceable>listToValue</replaceable> ? null, ... }
</term>
<listitem>
<para>
@ -66,6 +66,16 @@
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<varname>listToValue</varname>
</term>
<listitem>
<para>
A function for turning a list of values into a single value.
</para>
</listitem>
</varlistentry>
</variablelist>
It returns a set with INI-specific attributes <varname>type</varname> and <varname>generate</varname> as specified <link linkend='pkgs-formats-result'>below</link>.
</para>
@ -167,7 +177,7 @@ in {
# We know that the `user` attribute exists because we set a default value
# for it above, allowing us to use it without worries here
users.users.${cfg.settings.user} = {};
users.users.${cfg.settings.user} = { isSystemUser = true; };
# ...
};

@ -25,7 +25,8 @@
<screen>
<prompt>$ </prompt>cd /path/to/nixpkgs/nixos/doc/manual
<prompt>$ </prompt>make
<prompt>$ </prompt>nix-shell
<prompt>nix-shell$ </prompt>make
</screen>
<para>

@ -186,6 +186,25 @@ start_all()
</para>
</listitem>
</varlistentry>
<varlistentry>
<term>
<methodname>get_screen_text_variants</methodname>
</term>
<listitem>
<para>
Return a list of different interpretations of what is currently visible
on the machine's screen using optical character recognition. The number
and order of the interpretations is not specified and is subject to
change, but if no exception is raised at least one will be returned.
</para>
<note>
<para>
This requires passing <option>enableOCR</option> to the test attribute
set.
</para>
</note>
</listitem>
</varlistentry>
<varlistentry>
<term>
<methodname>get_screen_text</methodname>
@ -350,7 +369,8 @@ start_all()
<para>
Wait until the supplied regular expressions matches the textual contents
of the screen by using optical character recognition (see
<methodname>get_screen_text</methodname>).
<methodname>get_screen_text</methodname> and
<methodname>get_screen_text_variants</methodname>).
</para>
<note>
<para>
@ -448,6 +468,17 @@ import ./make-test-python.nix {
<replaceable>Python code…</replaceable>
'';
}
</programlisting>
This will produce a Nix warning at evaluation time. To fully disable the
linter, wrap the test script in comment directives to disable the Black linter
directly (again, don't commit this within the Nixpkgs repository):
<programlisting>
testScript =
''
# fmt: off
<replaceable>Python code…</replaceable>
# fmt: on
'';
</programlisting>
</para>
</section>

@ -374,7 +374,7 @@
You may want to look at the options starting with
<option><link linkend="opt-boot.loader.efi.canTouchEfiVariables">boot.loader.efi</link></option>
and
<option><link linkend="opt-boot.loader.systemd-boot.enable">boot.loader.systemd</link></option>
<option><link linkend="opt-boot.loader.systemd-boot.enable">boot.loader.systemd-boot</link></option>
as well.
</para>
</listitem>

@ -1017,6 +1017,14 @@ systemd.services.nginx.serviceConfig.ProtectHome = "read-only";
will have changed.
</para>
</listitem>
<listitem>
<para>
The syntax of the PostgreSQL configuration file is now checked at build
time. If your configuration includes a file inaccessible inside the build
sandbox, set <varname>services.postgresql.checkConfig</varname> to
<literal>false</literal>.
</para>
</listitem>
<listitem>
<para>
The rkt module has been removed, it was archived by upstream.

@ -23,20 +23,81 @@
Support is planned until the end of December 2021, handing over to 21.11.
</para>
</listitem>
<listitem>
<para>The default Linux kernel was updated to the 5.10 LTS series, coming from the 5.4 LTS series.</para>
</listitem>
<listitem>
<para>GNOME desktop environment was upgraded to 3.38, see its <link xlink:href="https://help.gnome.org/misc/release-notes/3.38/">release notes</link>.</para>
</listitem>
<listitem>
<para>
<link xlink:href="https://www.gnuradio.org/">GNURadio</link> 3.8 was
<link xlink:href="https://github.com/NixOS/nixpkgs/issues/82263">finnally</link>
<link xlink:href="https://github.com/NixOS/nixpkgs/issues/82263">finally</link>
packaged, along with a rewrite to the Nix expressions, allowing users to
override the features upstream supports selecting to compile or not to.
Additionally, the attribute <code>gnuradio</code> and <code>gnuradio3_7</code>
now point to an externally wrapped by default derivations, that allow you to
also add `extraPythonPackages` to the Python interpreter used by GNURadio.
Missing environmental variables needed for operational GUI were also added
(<link xlink:href="https://github.com/NixOS/nixpkgs/issues/75478">#7547</link>).
(<link xlink:href="https://github.com/NixOS/nixpkgs/issues/75478">#75478</link>).
</para>
</listitem>
<listitem>
<para>
<link xlink:href="https://www.gnuradio.org/">GNURadio</link> has a
<code>pkgs</code> attribute set, and there's a <code>gnuradio.callPackage</code>
function that extends <code>pkgs</code> with a <code>mkDerivation</code>, and a
<code>mkDerivationWith</code>, like Qt5. Now all <code>gnuradio.pkgs</code> are
defined with <code>gnuradio.callPackage</code> and some packages that depend
on gnuradio are defined with this as well.
</para>
</listitem>
<listitem>
<para>
<link xlink:href="https://www.privoxy.org/">Privoxy</link> has been updated
to version 3.0.32 (See <link xlink:href="https://lists.privoxy.org/pipermail/privoxy-announce/2021-February/000007.html">announcement</link>).
Compared to the previous release, Privoxy has gained support for HTTPS
inspection (still experimental), Brotli decompression, several new filters
and lots of bug fixes, including security ones. In addition, the package
is now built with compression and external filters support, which were
previously disabled.
</para>
<para>
Regarding the NixOS module, new options for HTTPS inspection have been added
and <option>services.privoxy.extraConfig</option> has been replaced by the new
<xref linkend="opt-services.privoxy.settings"/>
(See <link xlink:href="https://github.com/NixOS/rfcs/blob/master/rfcs/0042-config-option.md">RFC 0042</link>
for the motivation).
</para>
</listitem>
<listitem>
<para>
Python optimizations were disabled again. Builds with optimizations enabled
are not reproducible. Optimizations can now be enabled with an option.
</para>
</listitem>
<listitem>
<para>
<link xlink:href="https://kodi.tv/">Kodi</link> has been updated to version 19.0 "Matrix". See
the <link xlink:href="https://kodi.tv/article/kodi-190-matrix-release">announcement</link> for
further details.
</para>
</listitem>
<listitem>
<para>
The <option>services.packagekit.backend</option> option has been removed as
it only supported a single setting which would always be the default.
Instead new <link
xlink:href="https://github.com/NixOS/rfcs/blob/master/rfcs/0042-config-option.md">RFC
0042</link> compliant <xref linkend="opt-services.packagekit.settings"/>
and <xref linkend="opt-services.packagekit.vendorSettings"/> options have
been introduced.
</para>
</listitem>
<listitem>
<para>
<link xlink:href="https://nginx.org">Nginx</link> has been updated to stable version 1.20.0.
Now nginx uses the zlib-ng library by default.
</para>
</listitem>
</itemizedlist>
@ -74,6 +135,16 @@
<xref linkend="opt-services.samba-wsdd.enable" /> Web Services Dynamic Discovery host daemon
</para>
</listitem>
<listitem>
<para>
<link xlink:href="https://www.discourse.org/">Discourse</link>, a
modern and open source discussion platform.
</para>
<para>
See the <link linkend="module-services-discourse">Discourse
section of the NixOS manual</link> for more information.
</para>
</listitem>
</itemizedlist>
</section>
@ -200,7 +271,7 @@
</listitem>
<listitem>
<para>
xfsprogs was update from 4.19 to 5.10. It now enables reflink support by default on filesystem creation.
xfsprogs was update from 4.19 to 5.11. It now enables reflink support by default on filesystem creation.
Support for reflinks was added with an experimental status to kernel 4.9 and deemed stable in kernel 4.16.
If you want to be able to mount XFS filesystems created with this release of xfsprogs on kernel releases older than those, you need to format them
with <literal>mkfs.xfs -m reflink=0</literal>.
@ -259,7 +330,18 @@
</listitem>
<listitem>
<para>
<literal>vim</literal> switched to Python 3, dropping all Python 2 support.
<literal>vim</literal> and <literal>neovim</literal> switched to Python 3, dropping all Python 2 support.
</para>
</listitem>
<listitem>
<para>
<link linkend="opt-networking.wireguard.interfaces">networking.wireguard.interfaces.&lt;name&gt;.generatePrivateKeyFile</link>,
which is off by default, had a <literal>chmod</literal> race condition
fixed. As an aside, the parent directory's permissions were widened,
and the key files were made owner-writable.
This only affects newly created keys.
However, if the exact permissions are important for your setup, read
<link xlink:href="https://github.com/NixOS/nixpkgs/pull/121294">#121294</link>.
</para>
</listitem>
<listitem>
@ -539,6 +621,100 @@ self: super:
<package>imagemagick6Big</package> if you need the older version.
</para>
</listitem>
<listitem>
<para>
<xref linkend="opt-services.xserver.videoDrivers" /> no longer uses the deprecated <literal>cirrus</literal> and <literal>vesa</literal> device dependent X drivers by default. It also enables both <literal>amdgpu</literal> and <literal>nouveau</literal> drivers by default now.
</para>
</listitem>
<listitem>
<para>
The <literal>kindlegen</literal> package is gone, because it is no longer supported or hosted by Amazon. Sadly, its replacement, Kindle Previewer, has no Linux support. However, there are other ways to generate MOBI files. See <link xlink:href="https://github.com/NixOS/nixpkgs/issues/96439">the discussion</link> for more info.
</para>
</listitem>
<listitem>
<para>
The <package>apacheKafka</package> packages are now built with
version-matched JREs. Versions 2.6 and above, the ones that recommend it,
use jdk11, while versions below remain on jdk8. The NixOS service has
been adjusted to start the service using the same version as the package,
adjustable with the new
<link linkend="opt-services.apache-kafka.jre">services.apache-kafka.jre</link>
option. Furthermore, the default list of
<link linkend="opt-services.apache-kafka.jvmOptions">services.apache-kafka.jvmOptions</link>
have been removed. You should set your own according to the
<link xlink:href="https://kafka.apache.org/documentation/#java">upstream documentation</link>
for your Kafka version.
</para>
</listitem>
<listitem>
<para>
The <package>kodi</package> package has been modified to allow concise addon management. Consider
the following configuration from previous releases of NixOS to install <package>kodi</package>,
including the <package>kodiPackages.inputstream-adaptive</package> and <package>kodiPackages.vfs-sftp</package>
addons:
<programlisting>
environment.systemPackages = [
pkgs.kodi
];
nixpkgs.config.kodi = {
enableInputStreamAdaptive = true;
enableVFSSFTP = true;
};
</programlisting>
All Kodi <literal>config</literal> flags have been removed, and as a result the above configuration
should now be written as:
<programlisting>
environment.systemPackages = [
(pkgs.kodi.withPackages (p: with p; [
inputstream-adaptive
vfs-sftp
]))
];
</programlisting>
</para>
</listitem>
<listitem>
<para>
<option>environment.defaultPackages</option> now includes the nano package.
If <package>pkgs.nano</package> is not added to the list,
make sure another editor is installed and the <literal>EDITOR</literal>
environment variable is set to it.
Environment variables can be set using <option>environment.variables</option>.
</para>
</listitem>
<listitem>
<para>
<option>services.minio.dataDir</option> changed type to a list of paths, required for specifiyng multiple data directories for using with erasure coding.
Currently, the service doesn't enforce nor checks the correct number of paths to correspond to minio requirements.
</para>
</listitem>
<listitem>
<para>
All CUDA toolkit versions prior to CUDA 10 have been removed.
</para>
</listitem>
<listitem>
<para>
The <package>babeld</package> service is now being run as an unprivileged user. To achieve that the module configures
<literal>skip-kernel-setup true</literal> and takes care of setting forwarding and rp_filter sysctls by itself as well
as for each interface in <varname>services.babeld.interfaces</varname>.
</para>
</listitem>
<listitem>
<para>
The <option>services.zigbee2mqtt.config</option> option has been renamed to <option>services.zigbee2mqtt.settings</option> and
now follows <link xlink:href="https://github.com/NixOS/rfcs/blob/master/rfcs/0042-config-option.md">RFC 0042</link>.
</para>
</listitem>
<listitem>
<para>
The <package>yadm</package> dotfile manager has been updated from 2.x to 3.x, which has new (XDG) default locations for some data/state files. Most yadm commands will fail and print a legacy path warning (which describes how to upgrade/migrate your repository). If you have scripts, daemons, scheduled jobs, shell profiles, etc. that invoke yadm, expect them to fail or misbehave until you perform this migration and prepare accordingly.
</para>
</listitem>
</itemizedlist>
</section>
@ -634,8 +810,8 @@ self: super:
</para>
<para>
Aditionally to the much stricter runtime environmet the
<literal>/dev/urandom</literal> mount lines we previously had in the code (that would
Additionally to the much stricter runtime environment the
<literal>/dev/urandom</literal> mount lines we previously had in the code (that
randomly failed during the stop-phase) have been removed as systemd will take care of those for us.
</para>
@ -653,6 +829,23 @@ self: super:
default in the CLI tooling which in turn enables us to use
<literal>unbound-control</literal> without passing a custom configuration location.
</para>
<para>
The module has also been reworked to be <link
xlink:href="https://github.com/NixOS/rfcs/blob/master/rfcs/0042-config-option.md">RFC
0042</link> compliant. As such,
<option>sevices.unbound.extraConfig</option> has been removed and replaced
by <xref linkend="opt-services.unbound.settings"/>. <option>services.unbound.interfaces</option>
has been renamed to <option>services.unbound.settings.server.interface</option>.
</para>
<para>
<option>services.unbound.forwardAddresses</option> and
<option>services.unbound.allowedAccess</option> have also been changed to
use the new settings interface. You can follow the instructions when
executing <literal>nixos-rebuild</literal> to upgrade your configuration to
use the new interface.
</para>
</listitem>
<listitem>
<para>
@ -709,6 +902,13 @@ self: super:
The option's description was incorrect regarding ownership management and has been simplified greatly.
</para>
</listitem>
<listitem>
<para>
When defining a new user, one of <xref linkend="opt-users.users._name_.isNormalUser" /> and <xref linkend="opt-users.users._name_.isSystemUser" /> is now required.
This is to prevent accidentally giving a UID above 1000 to system users, which could have unexpected consequences, like running user activation scripts for system users.
Note that users defined with an explicit UID below 500 are exempted from this check, as <xref linkend="opt-users.users._name_.isSystemUser" /> has no effect for those.
</para>
</listitem>
<listitem>
<para>
The GNOME desktop manager once again installs <package>gnome3.epiphany</package> by default.
@ -723,7 +923,7 @@ self: super:
<listitem>
<para>
Platforms, like <varname>stdenv.hostPlatform</varname>, no longer have a <varname>platform</varname> attribute.
It has been (mostly) flattoned away:
It has been (mostly) flattened away:
</para>
<itemizedlist>
<listitem><para><varname>platform.gcc</varname> is now <varname>gcc</varname></para></listitem>
@ -754,6 +954,87 @@ self: super:
once during the time when the timer was inactive.
</para>
</listitem>
<listitem>
<para>
The <literal>rustPlatform.buildRustPackage</literal> function is split into several hooks:
<package>cargoSetupHook</package> to set up vendoring for Cargo-based projects,
<package>cargoBuildHook</package> to build a project using Cargo,
<package>cargoInstallHook</package> to install a project using Cargo, and
<package>cargoCheckHook</package> to run tests in Cargo-based projects. With this change,
mixed-language projects can use the relevant hooks within builders other than
<literal>buildRustPackage</literal>. However, these changes also required several API changes to
<literal>buildRustPackage</literal> itself:
<itemizedlist>
<listitem>
<para>
The <literal>target</literal> argument was removed. Instead, <literal>buildRustPackage</literal>
will always use the same target as the C/C++ compiler that is used.
</para>
</listitem>
<listitem>
<para>
The <literal>cargoParallelTestThreads</literal> argument was removed. Parallel tests are
now disabled through <literal>dontUseCargoParallelTests</literal>.
</para>
</listitem>
</itemizedlist>
</para>
</listitem>
<listitem>
<para>
The <literal>rustPlatform.maturinBuildHook</literal> hook was added. This hook can be used
with <literal>buildPythonPackage</literal> to build Python packages that are written in Rust
and use Maturin as their build tool.
</para>
</listitem>
<listitem>
<para>
Kubernetes has <link xlink:href="https://kubernetes.io/blog/2020/12/02/dont-panic-kubernetes-and-docker/">deprecated docker</link> as container runtime.
As a consequence, the Kubernetes module now has support for configuration of custom remote container runtimes and enables containerd by default.
Note that containerd is more strict regarding container image OCI-compliance.
As an example, images with CMD or ENTRYPOINT defined as strings (not lists) will fail on containerd, while working fine on docker.
Please test your setup and container images with containerd prior to upgrading.
</para>
</listitem>
<listitem>
<para>
The GitLab module now has support for automatic backups. A
schedule can be set with the
<link linkend="opt-services.gitlab.backup.startAt">services.gitlab.backup.startAt</link>
option.
</para>
</listitem>
<listitem>
<para>
Prior to this release, systemd would also read system units from an undocumented <literal>/etc/systemd-mutable/system</literal> path.
This path has been dropped from the defaults. That path (or others) can be re-enabled by adding it to the
<link linkend="opt-boot.extraSystemdUnitPaths">boot.extraSystemdUnitPaths</link> list.
</para>
</listitem>
<listitem>
<para>
PostgreSQL 9.5 is scheduled EOL during the 21.05 life cycle and has been removed.
</para>
</listitem>
<listitem>
<para>
<link xlink:href="https://www.xfce.org/">Xfce4</link> relies on
GIO/GVfs for userspace virtual filesystem access in applications
like <link xlink:href="https://docs.xfce.org/xfce/thunar/">thunar</link> and
<link xlink:href="https://docs.xfce.org/apps/gigolo/">gigolo</link>.
For that to work, the gvfs nixos service is enabled by default,
and it can be configured with the specific package that provides
GVfs. Until now Xfce4 was setting it to use a lighter version of
GVfs (without support for samba). To avoid conflicts with other
desktop environments this setting has been dropped. Users that
still want it should add the following to their system
configuration:
<programlisting>
<xref linkend="opt-services.gvfs.package" /> = pkgs.gvfs.override { samba = null; };
</programlisting>
</para>
</listitem>
</itemizedlist>
</section>
</section>

@ -15,6 +15,8 @@
, # size of the boot partition, is only used if partitionTableType is
# either "efi" or "hybrid"
# This will be undersized slightly, as this is actually the offset of
# the end of the partition. Generally it will be 1MiB smaller.
bootSize ? "256M"
, # The files and directories to be placed in the target file system.
@ -163,6 +165,8 @@ let format' = format; in let
closureInfo = pkgs.closureInfo { rootPaths = [ config.system.build.toplevel channelSources ]; };
blockSize = toString (4 * 1024); # ext4fs block size (not block device sector size)
prepareImage = ''
export PATH=${binPath}
@ -175,6 +179,24 @@ let format' = format; in let
echo $(( "$1" * 512 ))
}
# Given lines of numbers, adds them together
sum_lines() {
local acc=0
while read -r number; do
acc=$((acc+number))
done
echo "$acc"
}
mebibyte=$(( 1024 * 1024 ))
# Approximative percentage of reserved space in an ext4 fs over 512MiB.
# 0.05208587646484375
# × 1000, integer part: 52
compute_fudge() {
echo $(( $1 * 52 / 1000 ))
}
mkdir $out
root="$PWD/root"
@ -235,12 +257,53 @@ let format' = format; in let
${if diskSize == "auto" then ''
${if partitionTableType == "efi" || partitionTableType == "hybrid" then ''
additionalSpace=$(( ($(numfmt --from=iec '${additionalSpace}') + $(numfmt --from=iec '${bootSize}')) / 1000 ))
# Add the GPT at the end
gptSpace=$(( 512 * 34 * 1 ))
# Normally we'd need to account for alignment and things, if bootSize
# represented the actual size of the boot partition. But it instead
# represents the offset at which it ends.
# So we know bootSize is the reserved space in front of the partition.
reservedSpace=$(( gptSpace + $(numfmt --from=iec '${bootSize}') ))
'' else if partitionTableType == "legacy+gpt" then ''
# Add the GPT at the end
gptSpace=$(( 512 * 34 * 1 ))
# And include the bios_grub partition; the ext4 partition starts at 2MB exactly.
reservedSpace=$(( gptSpace + 2 * mebibyte ))
'' else if partitionTableType == "legacy" then ''
# Add the 1MiB aligned reserved space (includes MBR)
reservedSpace=$(( mebibyte ))
'' else ''
additionalSpace=$(( $(numfmt --from=iec '${additionalSpace}') / 1000 ))
reservedSpace=0
''}
diskSize=$(( $(set -- $(du -d0 $root); echo "$1") + $additionalSpace ))
truncate -s "$diskSize"K $diskImage
additionalSpace=$(( $(numfmt --from=iec '${additionalSpace}') + reservedSpace ))
# Compute required space in filesystem blocks
diskUsage=$(find . ! -type d -exec 'du' '--apparent-size' '--block-size' "${blockSize}" '{}' ';' | cut -f1 | sum_lines)
# Each inode takes space!
numInodes=$(find . | wc -l)
# Convert to bytes, inodes take two blocks each!
diskUsage=$(( (diskUsage + 2 * numInodes) * ${blockSize} ))
# Then increase the required space to account for the reserved blocks.
fudge=$(compute_fudge $diskUsage)
requiredFilesystemSpace=$(( diskUsage + fudge ))
diskSize=$(( requiredFilesystemSpace + additionalSpace ))
# Round up to the nearest mebibyte.
# This ensures whole 512 bytes sector sizes in the disk image
# and helps towards aligning partitions optimally.
if (( diskSize % mebibyte )); then
diskSize=$(( ( diskSize / mebibyte + 1) * mebibyte ))
fi
truncate -s "$diskSize" $diskImage
printf "Automatic disk size...\n"
printf " Closure space use: %d bytes\n" $diskUsage
printf " fudge: %d bytes\n" $fudge
printf " Filesystem size needed: %d bytes\n" $requiredFilesystemSpace
printf " Additional space: %d bytes\n" $additionalSpace
printf " Disk image size: %d bytes\n" $diskSize
'' else ''
truncate -s ${toString diskSize}M $diskImage
''}
@ -251,9 +314,9 @@ let format' = format; in let
# Get start & length of the root partition in sectors to $START and $SECTORS.
eval $(partx $diskImage -o START,SECTORS --nr ${rootPartition} --pairs)
mkfs.${fsType} -F -L ${label} $diskImage -E offset=$(sectorsToBytes $START) $(sectorsToKilobytes $SECTORS)K
mkfs.${fsType} -b ${blockSize} -F -L ${label} $diskImage -E offset=$(sectorsToBytes $START) $(sectorsToKilobytes $SECTORS)K
'' else ''
mkfs.${fsType} -F -L ${label} $diskImage
mkfs.${fsType} -b ${blockSize} -F -L ${label} $diskImage
''}
echo "copying staging root to image..."
@ -283,6 +346,9 @@ in pkgs.vmTools.runInLinuxVM (
# Some tools assume these exist
ln -s vda /dev/xvda
ln -s vda /dev/sda
# make systemd-boot find ESP without udev
mkdir /dev/block
ln -s /dev/vda1 /dev/block/254:1
mountPoint=/mnt
mkdir $mountPoint

@ -126,11 +126,37 @@ let
}
'';
singleMDDoc = name: value: ''
## ${lib.escape [ "<" ">" ] name}
${value.description}
${lib.optionalString (value ? type) ''
*_Type_*:
${value.type}
''}
${lib.optionalString (value ? default) ''
*_Default_*
```
${builtins.toJSON value.default}
```
''}
${lib.optionalString (value ? example) ''
*_Example_*
```
${builtins.toJSON value.example}
```
''}
'';
in {
inherit optionsNix;
optionsAsciiDoc = lib.concatStringsSep "\n" (lib.mapAttrsToList singleAsciiDoc optionsNix);
optionsMDDoc = lib.concatStringsSep "\n" (lib.mapAttrsToList singleMDDoc optionsNix);
optionsJSON = pkgs.runCommand "options.json"
{ meta.description = "List of NixOS options in JSON format";
buildInputs = [ pkgs.brotli ];

@ -18,13 +18,15 @@ rec {
];
qemuSerialDevice = if pkgs.stdenv.isi686 || pkgs.stdenv.isx86_64 then "ttyS0"
else if pkgs.stdenv.isAarch32 || pkgs.stdenv.isAarch64 then "ttyAMA0"
else if (with pkgs.stdenv.hostPlatform; isAarch32 || isAarch64 || isPower) then "ttyAMA0"
else throw "Unknown QEMU serial device for system '${pkgs.stdenv.hostPlatform.system}'";
qemuBinary = qemuPkg: {
x86_64-linux = "${qemuPkg}/bin/qemu-kvm -cpu max";
armv7l-linux = "${qemuPkg}/bin/qemu-system-arm -enable-kvm -machine virt -cpu host";
aarch64-linux = "${qemuPkg}/bin/qemu-system-aarch64 -enable-kvm -machine virt,gic-version=host -cpu host";
powerpc64le-linux = "${qemuPkg}/bin/qemu-system-ppc64 -machine powernv";
powerpc64-linux = "${qemuPkg}/bin/qemu-system-ppc64 -machine powernv";
x86_64-darwin = "${qemuPkg}/bin/qemu-kvm -cpu max";
}.${pkgs.stdenv.hostPlatform.system} or "${qemuPkg}/bin/qemu-kvm";
}

@ -1,7 +1,7 @@
#! /somewhere/python3
from contextlib import contextmanager, _GeneratorContextManager
from queue import Queue, Empty
from typing import Tuple, Any, Callable, Dict, Iterator, Optional, List
from typing import Tuple, Any, Callable, Dict, Iterator, Optional, List, Iterable
from xml.sax.saxutils import XMLGenerator
import queue
import io
@ -205,6 +205,37 @@ class Logger:
self.xml.endElement("nest")
def _perform_ocr_on_screenshot(
screenshot_path: str, model_ids: Iterable[int]
) -> List[str]:
if shutil.which("tesseract") is None:
raise Exception("OCR requested but enableOCR is false")
magick_args = (
"-filter Catrom -density 72 -resample 300 "
+ "-contrast -normalize -despeckle -type grayscale "
+ "-sharpen 1 -posterize 3 -negate -gamma 100 "
+ "-blur 1x65535"
)
tess_args = f"-c debug_file=/dev/null --psm 11"
cmd = f"convert {magick_args} {screenshot_path} tiff:{screenshot_path}.tiff"
ret = subprocess.run(cmd, shell=True, capture_output=True)
if ret.returncode != 0:
raise Exception(f"TIFF conversion failed with exit code {ret.returncode}")
model_results = []
for model_id in model_ids:
cmd = f"tesseract {screenshot_path}.tiff - {tess_args} --oem {model_id}"
ret = subprocess.run(cmd, shell=True, capture_output=True)
if ret.returncode != 0:
raise Exception(f"OCR failed with exit code {ret.returncode}")
model_results.append(ret.stdout.decode("utf-8"))
return model_results
class Machine:
def __init__(self, args: Dict[str, Any]) -> None:
if "name" in args:
@ -637,43 +668,29 @@ class Machine:
"""Debugging: Dump the contents of the TTY<n>"""
self.execute("fold -w 80 /dev/vcs{} | systemd-cat".format(tty))
def get_screen_text(self) -> str:
if shutil.which("tesseract") is None:
raise Exception("get_screen_text used but enableOCR is false")
magick_args = (
"-filter Catrom -density 72 -resample 300 "
+ "-contrast -normalize -despeckle -type grayscale "
+ "-sharpen 1 -posterize 3 -negate -gamma 100 "
+ "-blur 1x65535"
)
tess_args = "-c debug_file=/dev/null --psm 11 --oem 2"
def _get_screen_text_variants(self, model_ids: Iterable[int]) -> List[str]:
with tempfile.TemporaryDirectory() as tmpdir:
screenshot_path = os.path.join(tmpdir, "ppm")
self.send_monitor_command(f"screendump {screenshot_path}")
return _perform_ocr_on_screenshot(screenshot_path, model_ids)
with self.nested("performing optical character recognition"):
with tempfile.NamedTemporaryFile() as tmpin:
self.send_monitor_command("screendump {}".format(tmpin.name))
cmd = "convert {} {} tiff:- | tesseract - - {}".format(
magick_args, tmpin.name, tess_args
)
ret = subprocess.run(cmd, shell=True, capture_output=True)
if ret.returncode != 0:
raise Exception(
"OCR failed with exit code {}".format(ret.returncode)
)
def get_screen_text_variants(self) -> List[str]:
return self._get_screen_text_variants([0, 1, 2])
return ret.stdout.decode("utf-8")
def get_screen_text(self) -> str:
return self._get_screen_text_variants([2])[0]
def wait_for_text(self, regex: str) -> None:
def screen_matches(last: bool) -> bool:
text = self.get_screen_text()
matches = re.search(regex, text) is not None
variants = self.get_screen_text_variants()
for text in variants:
if re.search(regex, text) is not None:
return True
if last and not matches:
self.log("Last OCR attempt failed. Text was: {}".format(text))
if last:
self.log("Last OCR attempt failed. Text was: {}".format(variants))
return matches
return False
with self.nested("waiting for {} to appear on screen".format(regex)):
retry(screen_matches)
@ -718,6 +735,7 @@ class Machine:
shell_path = os.path.join(self.state_dir, "shell")
self.shell_socket = create_socket(shell_path)
display_available = any(x in os.environ for x in ["DISPLAY", "WAYLAND_DISPLAY"])
qemu_options = (
" ".join(
[
@ -727,7 +745,7 @@ class Machine:
"-device virtio-serial",
"-device virtconsole,chardev=shell",
"-device virtio-rng-pci",
"-serial stdio" if "DISPLAY" in os.environ else "-nographic",
"-serial stdio" if display_available else "-nographic",
]
)
+ " "

@ -54,8 +54,13 @@ rec {
};
# Run an automated test suite in the given virtual network.
# `driver' is the script that runs the network.
runTests = driver:
runTests = {
# the script that runs the network
driver,
# a source position in the format of builtins.unsafeGetAttrPos
# for meta.position
pos,
}:
stdenv.mkDerivation {
name = "vm-test-run-${driver.testName}";
@ -69,6 +74,8 @@ rec {
'';
passthru = driver.passthru;
inherit pos;
};
@ -79,6 +86,11 @@ rec {
# Skip linting (mainly intended for faster dev cycles)
, skipLint ? false
, passthru ? {}
, # For meta.position
pos ? # position used in error messages and for meta.position
(if t.meta.description or null != null
then builtins.unsafeGetAttrPos "description" t.meta
else builtins.unsafeGetAttrPos "testScript" t)
, ...
} @ t:
let
@ -131,10 +143,8 @@ rec {
"it's currently ${toString testNameLen} characters long.")
else
"nixos-test-driver-${name}";
warn = if skipLint then lib.warn "Linting is disabled!" else lib.id;
in
warn (runCommand testDriverName
lib.warnIf skipLint "Linting is disabled" (runCommand testDriverName
{
buildInputs = [ makeWrapper ];
testScript = testScript';
@ -176,7 +186,7 @@ rec {
driver = mkDriver null;
driverInteractive = mkDriver pkgs.qemu;
test = passMeta (runTests driver);
test = passMeta (runTests { inherit driver pos; });
nodeNames = builtins.attrNames driver.nodes;
invalidNodeNames = lib.filter

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

Loading…
Cancel
Save