Merge commit 'dd14e5d78e90a2ccd6007e569820de9b4861a6c2' into HEAD

wip/nixpkgs-raku
Katharina Fey 3 years ago
commit e1ebe378ad
Signed by: kookie
GPG Key ID: 90734A9E619C8A6C
  1. 53
      infra/libkookie/nixpkgs/unstable/.github/CODEOWNERS
  2. 19
      infra/libkookie/nixpkgs/unstable/.github/ISSUE_TEMPLATE/bug_report.md
  3. 8
      infra/libkookie/nixpkgs/unstable/.github/PULL_REQUEST_TEMPLATE.md
  4. 2
      infra/libkookie/nixpkgs/unstable/.github/STALE-BOT.md
  5. 154
      infra/libkookie/nixpkgs/unstable/.github/labeler.yml
  6. 29
      infra/libkookie/nixpkgs/unstable/.github/workflows/backport.yml
  7. 20
      infra/libkookie/nixpkgs/unstable/.github/workflows/basic-eval.yml
  8. 32
      infra/libkookie/nixpkgs/unstable/.github/workflows/direct-push.yml
  9. 29
      infra/libkookie/nixpkgs/unstable/.github/workflows/editorconfig.yml
  10. 19
      infra/libkookie/nixpkgs/unstable/.github/workflows/labels.yml
  11. 7
      infra/libkookie/nixpkgs/unstable/.github/workflows/manual-nixos.yml
  12. 7
      infra/libkookie/nixpkgs/unstable/.github/workflows/manual-nixpkgs.yml
  13. 39
      infra/libkookie/nixpkgs/unstable/.github/workflows/merge-staging.yml
  14. 26
      infra/libkookie/nixpkgs/unstable/.github/workflows/nixos-manual.yml
  15. 21
      infra/libkookie/nixpkgs/unstable/.github/workflows/no-channel.yml
  16. 49
      infra/libkookie/nixpkgs/unstable/.github/workflows/periodic-merge-24h.yml
  17. 55
      infra/libkookie/nixpkgs/unstable/.github/workflows/periodic-merge-6h.yml
  18. 134
      infra/libkookie/nixpkgs/unstable/.github/workflows/rebase.yml
  19. 2
      infra/libkookie/nixpkgs/unstable/.version
  20. 21
      infra/libkookie/nixpkgs/unstable/CONTRIBUTING.md
  21. 10
      infra/libkookie/nixpkgs/unstable/README.md
  22. 35
      infra/libkookie/nixpkgs/unstable/doc/Makefile
  23. 12
      infra/libkookie/nixpkgs/unstable/doc/README.md
  24. 29
      infra/libkookie/nixpkgs/unstable/doc/builders/fetchers.chapter.md
  25. 6
      infra/libkookie/nixpkgs/unstable/doc/builders/images.xml
  26. 48
      infra/libkookie/nixpkgs/unstable/doc/builders/images/appimagetools.section.md
  27. 102
      infra/libkookie/nixpkgs/unstable/doc/builders/images/appimagetools.xml
  28. 42
      infra/libkookie/nixpkgs/unstable/doc/builders/images/dockertools.section.md
  29. 37
      infra/libkookie/nixpkgs/unstable/doc/builders/images/ocitools.section.md
  30. 61
      infra/libkookie/nixpkgs/unstable/doc/builders/images/ocitools.xml
  31. 28
      infra/libkookie/nixpkgs/unstable/doc/builders/images/snap/example-firefox.nix
  32. 12
      infra/libkookie/nixpkgs/unstable/doc/builders/images/snap/example-hello.nix
  33. 71
      infra/libkookie/nixpkgs/unstable/doc/builders/images/snaptools.section.md
  34. 59
      infra/libkookie/nixpkgs/unstable/doc/builders/images/snaptools.xml
  35. 39
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/cataclysm-dda.section.md
  36. 32
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/citrix.section.md
  37. 46
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/citrix.xml
  38. 13
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/dlib.section.md
  39. 24
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/dlib.xml
  40. 2
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/elm.section.md
  41. 2
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/emacs.section.md
  42. 2
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/firefox.section.md
  43. 45
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/fuse.section.md
  44. 38
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/ibus.section.md
  45. 57
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/ibus.xml
  46. 7
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/index.xml
  47. 4
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/opengl.section.md
  48. 28
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/steam.section.md
  49. 2
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/weechat.section.md
  50. 8
      infra/libkookie/nixpkgs/unstable/doc/builders/packages/xorg.section.md
  51. 6
      infra/libkookie/nixpkgs/unstable/doc/builders/special/fhs-environments.section.md
  52. 10
      infra/libkookie/nixpkgs/unstable/doc/builders/special/mkshell.section.md
  53. 49
      infra/libkookie/nixpkgs/unstable/doc/builders/trivial-builders.chapter.md
  54. 604
      infra/libkookie/nixpkgs/unstable/doc/contributing/coding-conventions.chapter.md
  55. 949
      infra/libkookie/nixpkgs/unstable/doc/contributing/coding-conventions.xml
  56. 99
      infra/libkookie/nixpkgs/unstable/doc/contributing/contributing-to-documentation.chapter.md
  57. 30
      infra/libkookie/nixpkgs/unstable/doc/contributing/contributing-to-documentation.xml
  58. 77
      infra/libkookie/nixpkgs/unstable/doc/contributing/quick-start.chapter.md
  59. 152
      infra/libkookie/nixpkgs/unstable/doc/contributing/quick-start.xml
  60. 207
      infra/libkookie/nixpkgs/unstable/doc/contributing/reviewing-contributions.chapter.md
  61. 488
      infra/libkookie/nixpkgs/unstable/doc/contributing/reviewing-contributions.xml
  62. 86
      infra/libkookie/nixpkgs/unstable/doc/contributing/submitting-changes.chapter.md
  63. 45
      infra/libkookie/nixpkgs/unstable/doc/contributing/vulnerability-roundup.chapter.md
  64. 7
      infra/libkookie/nixpkgs/unstable/doc/default.nix
  65. 1
      infra/libkookie/nixpkgs/unstable/doc/doc-support/lib-function-docs.nix
  66. 8
      infra/libkookie/nixpkgs/unstable/doc/functions.xml
  67. 5
      infra/libkookie/nixpkgs/unstable/doc/functions/debug.section.md
  68. 14
      infra/libkookie/nixpkgs/unstable/doc/functions/debug.xml
  69. 56
      infra/libkookie/nixpkgs/unstable/doc/functions/generators.section.md
  70. 74
      infra/libkookie/nixpkgs/unstable/doc/functions/generators.xml
  71. 2
      infra/libkookie/nixpkgs/unstable/doc/functions/library.xml
  72. 14
      infra/libkookie/nixpkgs/unstable/doc/functions/library/attrsets.xml
  73. 49
      infra/libkookie/nixpkgs/unstable/doc/functions/nix-gitignore.section.md
  74. 70
      infra/libkookie/nixpkgs/unstable/doc/functions/nix-gitignore.xml
  75. 17
      infra/libkookie/nixpkgs/unstable/doc/functions/prefer-remote-fetch.section.md
  76. 21
      infra/libkookie/nixpkgs/unstable/doc/functions/prefer-remote-fetch.xml
  77. 24
      infra/libkookie/nixpkgs/unstable/doc/labelless-link-is-xref.lua
  78. 146
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/agda.section.md
  79. 43
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/android.section.md
  80. 229
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/beam.section.md
  81. 2
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/bower.section.md
  82. 10
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/coq.section.md
  83. 4
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/crystal.section.md
  84. 432
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/dhall.section.md
  85. 22
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/dotnet.section.md
  86. 14
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/emscripten.section.md
  87. 28
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/gnome.section.md
  88. 23
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/go.section.md
  89. 31
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/hy.section.md
  90. 28
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/idris.section.md
  91. 2
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/index.xml
  92. 17
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/ios.section.md
  93. 60
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/lua.section.md
  94. 17
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/maven.section.md
  95. 73
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/ocaml.section.md
  96. 227
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/python.section.md
  97. 19
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/qt.section.md
  98. 10
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/r.section.md
  99. 26
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/ruby.section.md
  100. 252
      infra/libkookie/nixpkgs/unstable/doc/languages-frameworks/rust.section.md
  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
@ -46,6 +46,7 @@
/nixos/default.nix @nbp @infinisil
/nixos/lib/from-env.nix @nbp @infinisil
/nixos/lib/eval-config.nix @nbp @infinisil
/nixos/doc @ryantm
/nixos/doc/manual/configuration/abstractions.xml @nbp
/nixos/doc/manual/configuration/config-file.xml @nbp
/nixos/doc/manual/configuration/config-syntax.xml @nbp
@ -71,19 +72,23 @@
/pkgs/common-updater/scripts/update-source-version @jtojnar
# Python-related code and docs
/maintainers/scripts/update-python-libraries @FRidh
/pkgs/top-level/python-packages.nix @FRidh @jonringer
/pkgs/development/interpreters/python @FRidh
/pkgs/development/python-modules @FRidh @jonringer
/doc/languages-frameworks/python.section.md @FRidh
/pkgs/development/tools/poetry2nix @adisbladis
/maintainers/scripts/update-python-libraries @FRidh
/pkgs/top-level/python-packages.nix @FRidh @jonringer
/pkgs/development/interpreters/python @FRidh
/pkgs/development/python-modules @FRidh @jonringer
/doc/languages-frameworks/python.section.md @FRidh
/pkgs/development/tools/poetry2nix @adisbladis
/pkgs/development/interpreters/python/hooks @FRidh @jonringer @DavHau
/pkgs/development/interpreters/python/conda @DavHau
# 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
/doc/languages-frameworks/haskell.section.md @cdepillabout @sternenseemann @maralorn @expipiplus1
/maintainers/scripts/haskell @cdepillabout @sternenseemann @maralorn @expipiplus1
/pkgs/development/compilers/ghc @cdepillabout @sternenseemann @maralorn @expipiplus1
/pkgs/development/haskell-modules @cdepillabout @sternenseemann @maralorn @expipiplus1
/pkgs/test/haskell @cdepillabout @sternenseemann @maralorn @expipiplus1
/pkgs/top-level/release-haskell.nix @cdepillabout @sternenseemann @maralorn @expipiplus1
/pkgs/top-level/haskell-packages.nix @cdepillabout @sternenseemann @maralorn @expipiplus1
# Perl
/pkgs/development/interpreters/perl @volth @stigtsp
@ -95,8 +100,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 +131,6 @@
# Jetbrains
/pkgs/applications/editors/jetbrains @edwtjo
# Eclipse
/pkgs/applications/editors/eclipse @rycee
# Licenses
/lib/licenses.nix @alyssais
@ -139,7 +141,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
@ -180,8 +182,7 @@
/pkgs/top-level/emacs-packages.nix @adisbladis
# Neovim
/pkgs/applications/editors/neovim @jonringer
/pkgs/applications/editors/neovim @teto
/pkgs/applications/editors/neovim @jonringer @teto
# VimPlugins
/pkgs/misc/vim-plugins @jonringer @softinio
@ -195,12 +196,12 @@
/nixos/tests/prometheus-exporters.nix @WilliButz
# PHP interpreter, packages, extensions, tests and documentation
/doc/languages-frameworks/php.section.md @NixOS/php
/nixos/tests/php @NixOS/php
/pkgs/build-support/build-pecl.nix @NixOS/php
/pkgs/development/interpreters/php @NixOS/php
/pkgs/development/php-packages @NixOS/php
/pkgs/top-level/php-packages.nix @NixOS/php
/doc/languages-frameworks/php.section.md @NixOS/php @aanderse @etu @globin @ma27 @talyz
/nixos/tests/php @NixOS/php @aanderse @etu @globin @ma27 @talyz
/pkgs/build-support/build-pecl.nix @NixOS/php @aanderse @etu @globin @ma27 @talyz
/pkgs/development/interpreters/php @jtojnar @NixOS/php @aanderse @etu @globin @ma27 @talyz
/pkgs/development/php-packages @NixOS/php @aanderse @etu @globin @ma27 @talyz
/pkgs/top-level/php-packages.nix @jtojnar @NixOS/php @aanderse @etu @globin @ma27 @talyz
# Podman, CRI-O modules and related
/nixos/modules/virtualisation/containers.nix @NixOS/podman @zowoq

@ -7,33 +7,38 @@ assignees: ''
---
**Describe the bug**
### Describe the bug
A clear and concise description of what the bug is.
**To Reproduce**
### Steps To Reproduce
Steps to reproduce the behavior:
1. ...
2. ...
3. ...
**Expected behavior**
### Expected behavior
A clear and concise description of what you expected to happen.
**Screenshots**
### Screenshots
If applicable, add screenshots to help explain your problem.
**Additional context**
### Additional context
Add any other context about the problem here.
**Notify maintainers**
### Notify maintainers
<!--
Please @ people who are in the `meta.maintainers` list of the offending package or module.
If in doubt, check `git blame` for whoever last touched something.
-->
**Metadata**
### Metadata
Please run `nix-shell -p nix-info --run "nix-info -m"` and paste the result.
```console
[user@system:~]$ nix-shell -p nix-info --run "nix-info -m"
output here
```
Maintainer information:
```yaml
# a list of nixpkgs attributes affected by the problem

@ -23,6 +23,8 @@ Reviewing guidelines: https://nixos.org/manual/nixpkgs/unstable/#chap-reviewing-
- [ ] Tested via one or more NixOS test(s) if existing and applicable for the change (look inside [nixos/tests](https://github.com/NixOS/nixpkgs/blob/master/nixos/tests))
- [ ] Tested compilation of all pkgs that depend on this change using `nix-shell -p nixpkgs-review --run "nixpkgs-review wip"`
- [ ] Tested execution of all binary files (usually in `./result/bin/`)
- [ ] Determined the impact on package closure size (by running `nix path-info -S` before and after)
- [ ] Ensured that relevant documentation is up to date
- [ ] Fits [CONTRIBUTING.md](https://github.com/NixOS/nixpkgs/blob/master/.github/CONTRIBUTING.md).
- [21.11 Release Notes (or backporting 21.05 Relase notes)](https://github.com/NixOS/nixpkgs/blob/master/CONTRIBUTING.md#generating-2111-release-notes)
- [ ] (Package updates) Added a release notes entry if the change is major or breaking
- [ ] (Module updates) Added a release notes entry if the change is significant
- [ ] (Module addition) Added a release notes entry if adding a new NixOS module
- [ ] Fits [CONTRIBUTING.md](https://github.com/NixOS/nixpkgs/blob/master/CONTRIBUTING.md).

@ -3,7 +3,7 @@
- Thanks for your contribution!
- To remove the stale label, just leave a new comment.
- _How to find the right people to ping?_ &rarr; [`git blame`](https://git-scm.com/docs/git-blame) to the rescue! (or GitHub's history and blame buttons.)
- You can always ask for help on [our Discourse Forum](https://discourse.nixos.org/) or on the [#nixos IRC channel](https://webchat.freenode.net/#nixos).
- You can always ask for help on [our Discourse Forum](https://discourse.nixos.org/), [our Matrix room](https://matrix.to/#/#nix:nixos.org), or on the [#nixos IRC channel](https://web.libera.chat/#nixos).
## Suggestions for PRs

@ -0,0 +1,154 @@
"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/gnome/**/*
- nixos/modules/services/x11/desktop-managers/gnome.nix
- nixos/tests/gnome-xorg.nix
- nixos/tests/gnome.nix
- pkgs/desktops/gnome/**/*
"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
- maintainers/scripts/haskell/**/*
- pkgs/development/compilers/ghc/**/*
- pkgs/development/haskell-modules/**/*
- pkgs/development/tools/haskell/**/*
- pkgs/test/haskell/**/*
- pkgs/top-level/haskell-packages.nix
- pkgs/top-level/release-haskell.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: Backport
on:
pull_request_target:
types: [closed, labeled]
jobs:
backport:
name: Backport Pull Request
if: github.repository_owner == 'NixOS' && github.event.pull_request.merged == true && (github.event_name != 'labeled' || startsWith('backport', github.event.label.name))
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
# required to find all branches
fetch-depth: 0
ref: ${{ github.event.pull_request.head.sha }}
- name: Create backport PRs
# should be kept in sync with `version`
uses: zeebe-io/backport-action@2b994724142df0774855690db56bc6308fb99ffa
with:
# Config README: https://github.com/zeebe-io/backport-action#backport-action
github_token: ${{ secrets.GITHUB_TOKEN }}
github_workspace: ${{ github.workspace }}
# should be kept in sync with `uses`
version: 2b994724142df0774855690db56bc6308fb99ffa
pull_description: |-
Bot-based backport to `${target_branch}`, triggered by a label in #${pull_number}.
* [ ] Before merging, ensure that this backport complies with the [Criteria for Backporting](https://github.com/NixOS/nixpkgs/blob/master/CONTRIBUTING.md#criteria-for-backporting-changes).
* Even as a non-commiter, if you find that it does not comply, leave a comment.

@ -0,0 +1,20 @@
name: Basic evaluation checks
on:
pull_request:
branches:
- master
- release-**
push:
branches:
- master
- release-**
jobs:
tests:
runs-on: ubuntu-latest
# we don't limit this action to only NixOS repo since the checks are cheap and useful developer feedback
steps:
- uses: actions/checkout@v2
- uses: cachix/install-nix-action@v13
# explicit list of supportedSystems is needed until aarch64-darwin becomes part of the trunk jobset
- run: nix-build pkgs/top-level/release.nix -A tarball.nixpkgs-basic-release-checks --arg supportedSystems '[ "aarch64-darwin" "aarch64-linux" "x86_64-linux" "x86_64-darwin" ]'

@ -0,0 +1,32 @@
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"
# github events are eventually consistent, so wait until changes propagate to thier DB
- run: sleep 60
if: steps.ismerge.outputs.ismerge != 'true'
- 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:
@ -10,16 +12,17 @@ on:
jobs:
nixos:
runs-on: ubuntu-latest
if: github.repository_owner == 'NixOS'
steps:
- uses: actions/checkout@v2
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:
@ -10,16 +12,17 @@ on:
jobs:
nixpkgs:
runs-on: ubuntu-latest
if: github.repository_owner == 'NixOS'
steps:
- uses: actions/checkout@v2
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,39 +0,0 @@
name: "merge staging(-next)"
on:
schedule:
# * is a special character in YAML so you have to quote this string
# Merge every 6 hours
- cron: '0 */6 * * *'
jobs:
sync-branch:
if: github.repository == 'NixOS/nixpkgs'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Merge master into staging-next
uses: devmasx/merge-branch@v1.3.1
with:
type: now
from_branch: master
target_branch: staging-next
github_token: ${{ secrets.GITHUB_TOKEN }}
- name: Merge staging-next into staging
uses: devmasx/merge-branch@v1.3.1
with:
type: now
from_branch: staging-next
target_branch: staging
github_token: ${{ secrets.GITHUB_TOKEN }}
- name: Comment on failure
uses: peter-evans/create-or-update-comment@v1
if: ${{ failure() }}
with:
issue-number: 105153
body: |
An automatic merge [failed](https://github.com/NixOS/nixpkgs/actions/runs/${{ github.run_id }}).

@ -0,0 +1,26 @@
name: NixOS manual checks
permissions: read-all
on:
pull_request_target:
branches-ignore:
- 'release-**'
paths:
- 'nixos/**/*.xml'
- 'nixos/**/*.md'
jobs:
tests:
runs-on: ubuntu-latest
if: github.repository_owner == 'NixOS'
steps:
- uses: actions/checkout@v2
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
- name: Check DocBook files generated from Markdown are consistent
run: |
nixos/doc/manual/md-to-db.sh
git diff --exit-code

@ -0,0 +1,21 @@
name: "No channel PR"
on:
pull_request:
branches:
- 'nixos-**'
- 'nixpkgs-**'
jobs:
fail:
name: "This PR is is targeting a channel branch"
runs-on: ubuntu-latest
steps:
- run: |
cat <<EOF
The nixos-* and nixpkgs-* branches are pushed to by the channel
release script and should not be merged into directly.
Please target the equivalent release-* branch or master instead.
EOF
exit 1

@ -0,0 +1,49 @@
# This action periodically merges base branches into staging branches.
# This is done to
# * prevent conflicts or rather resolve them early
# * make all potential breakage happen on the staging branch
# * and make sure that all major rebuilds happen before the staging
# branch get’s merged back into its base branch.
name: "Periodic Merges (24h)"
on:
schedule:
# * is a special character in YAML so you have to quote this string
# Merge every 24 hours
- cron: '0 0 * * *'
jobs:
periodic-merge:
if: github.repository_owner == 'NixOS'
runs-on: ubuntu-latest
strategy:
# don't fail fast, so that all pairs are tried
fail-fast: false
# certain branches need to be merged in order, like master->staging-next->staging
# and disabling parallelism ensures the order of the pairs below.
max-parallel: 1
matrix:
pairs:
- from: master
into: haskell-updates
name: ${{ matrix.pairs.from }} → ${{ matrix.pairs.into }}
steps:
- uses: actions/checkout@v2
- name: ${{ matrix.pairs.from }} → ${{ matrix.pairs.into }}
uses: devmasx/merge-branch@v1.3.1
with:
type: now
from_branch: ${{ matrix.pairs.from }}
target_branch: ${{ matrix.pairs.into }}
github_token: ${{ secrets.GITHUB_TOKEN }}
- name: Comment on failure
uses: peter-evans/create-or-update-comment@v1
if: ${{ failure() }}
with:
issue-number: 105153
body: |
Periodic merge from `${{ matrix.pairs.from }}` into `${{ matrix.pairs.into }}` has [failed](https://github.com/NixOS/nixpkgs/actions/runs/${{ github.run_id }}).

@ -0,0 +1,55 @@
# This action periodically merges base branches into staging branches.
# This is done to
# * prevent conflicts or rather resolve them early
# * make all potential breakage happen on the staging branch
# * and make sure that all major rebuilds happen before the staging
# branch get’s merged back into its base branch.
name: "Periodic Merges (6h)"
on:
schedule:
# * is a special character in YAML so you have to quote this string
# Merge every 6 hours
- cron: '0 */6 * * *'
jobs:
periodic-merge:
if: github.repository_owner == 'NixOS'
runs-on: ubuntu-latest
strategy:
# don't fail fast, so that all pairs are tried
fail-fast: false
# certain branches need to be merged in order, like master->staging-next->staging
# and disabling parallelism ensures the order of the pairs below.
max-parallel: 1
matrix:
pairs:
- from: master
into: staging-next
- from: staging-next
into: staging
- from: release-21.05
into: staging-next-21.05
- from: staging-next-21.05
into: staging-21.05
name: ${{ matrix.pairs.from }} → ${{ matrix.pairs.into }}
steps:
- uses: actions/checkout@v2
- name: ${{ matrix.pairs.from }} → ${{ matrix.pairs.into }}
uses: devmasx/merge-branch@v1.3.1
with:
type: now
from_branch: ${{ matrix.pairs.from }}
target_branch: ${{ matrix.pairs.into }}
github_token: ${{ secrets.GITHUB_TOKEN }}
- name: Comment on failure
uses: peter-evans/create-or-update-comment@v1
if: ${{ failure() }}
with:
issue-number: 105153
body: |
Periodic merge from `${{ matrix.pairs.from }}` into `${{ matrix.pairs.into }}` has [failed](https://github.com/NixOS/nixpkgs/actions/runs/${{ github.run_id }}).

@ -1,134 +0,0 @@
on:
issue_comment:
types:
- created
# This action allows people with write access to the repo to rebase a PRs base branch
# by commenting `/rebase ${branch}` on the PR while avoiding CODEOWNER notifications.
jobs:
rebase:
runs-on: ubuntu-latest
if: github.repository_owner == 'NixOS' && github.event.issue.pull_request != '' && contains(github.event.comment.body, '/rebase')
steps:
- uses: peter-evans/create-or-update-comment@v1
with:
comment-id: ${{ github.event.comment.id }}
reactions: eyes
- uses: scherermichael-oss/action-has-permission@1.0.6
id: check-write-access
with:
required-permission: write
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: check permissions
run: |
echo "Commenter doesn't have write access to the repo"
exit 1
if: "! steps.check-write-access.outputs.has-permission"
- name: setup
run: |
curl "https://api.github.com/repos/${{ github.repository }}/pulls/${{ github.event.issue.number }}" 2>/dev/null >pr.json
cat <<EOF >>"$GITHUB_ENV"
CAN_MODIFY=$(jq -r '.maintainer_can_modify' pr.json)
COMMITS=$(jq -r '.commits' pr.json)
CURRENT_BASE=$(jq -r '.base.ref' pr.json)
PR_BRANCH=$(jq -r '.head.ref' pr.json)
COMMENT_BRANCH=$(echo ${{ github.event.comment.body }} | awk "/^\/rebase / {print \$2}")
PULL_REQUEST=${{ github.event.issue.number }}
EOF
rm pr.json
- name: check branch
env:
PERMANENT_BRANCHES: "haskell-updates|master|nixos|nixpkgs|python-unstable|release|staging"
VALID_BRANCHES: "haskell-updates|master|python-unstable|release-20.09|staging|staging-20.09|staging-next"
run: |
message() {
cat <<EOF
Can't rebase $PR_BRANCH from $CURRENT_BASE onto $COMMENT_BRANCH (PR:$PULL_REQUEST COMMITS:$COMMITS)
EOF
}
if ! [[ "$COMMENT_BRANCH" =~ ^($VALID_BRANCHES)$ ]]; then
cat <<EOF
Check that the branch from the comment is valid:
$(message)
This action can only rebase onto these branches:
$VALID_BRANCHES
\`/rebase \${branch}\` must be at the start of the line
EOF
exit 1
fi
if [[ "$COMMENT_BRANCH" == "$CURRENT_BASE" ]]; then
cat <<EOF
Check that the branch from the comment isn't the current base branch:
$(message)
EOF
exit 1
fi
if [[ "$COMMENT_BRANCH" == "$PR_BRANCH" ]]; then
cat <<EOF
Check that the branch from the comment isn't the current branch:
$(message)
EOF
exit 1
fi
if [[ "$PR_BRANCH" =~ ^($PERMANENT_BRANCHES) ]]; then
cat <<EOF
Check that the PR branch isn't a permanent branch:
$(message)
EOF
exit 1
fi
if [[ "$CAN_MODIFY" != "true" ]]; then
cat <<EOF
Check that maintainers can edit the PR branch:
$(message)
EOF
exit 1
fi
- uses: actions/checkout@v2
with:
fetch-depth: 0
- name: rebase pull request
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
git config --global user.name "github-actions[bot]"
git fetch origin
gh pr checkout "$PULL_REQUEST"
git rebase \
--onto="$(git merge-base origin/"$CURRENT_BASE" origin/"$COMMENT_BRANCH")" \
"HEAD~$COMMITS"
git push --force
curl \
-X POST \
-H "Accept: application/vnd.github.v3+json" \
-H "Authorization: token $GITHUB_TOKEN" \
-d "{ \"base\": \"$COMMENT_BRANCH\" }" \
"https://api.github.com/repos/${{ github.repository }}/pulls/$PULL_REQUEST"
curl \
-X PATCH \
-H "Accept: application/vnd.github.v3+json" \
-H "Authorization: token $GITHUB_TOKEN" \
-d '{ "state": "closed" }' \
"https://api.github.com/repos/${{ github.repository }}/pulls/$PULL_REQUEST"
- uses: peter-evans/create-or-update-comment@v1
with:
issue-number: ${{ github.event.issue.number }}
body: |
Rebased, please reopen the pull request to restart CI
- uses: peter-evans/create-or-update-comment@v1
if: failure()
with:
issue-number: ${{ github.event.issue.number }}
body: |
[Failed to rebase](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }})

@ -59,6 +59,27 @@ Follow these steps to backport a change into a release branch in compliance with
5. Push to GitHub and open a backport pull request. Make sure to select the release branch (e.g. `release-20.09`) as the target branch of the pull request, and link to the pull request in which the original change was comitted to `master`. The pull request title should be the commit title with the release version as prefix, e.g. `[20.09]`.
6. When the backport pull request is merged and you have the necessary privileges you can also replace the label `9.needs: port to stable` with `8.has: port to stable` on the original pull request. This way maintainers can keep track of missing backports easier.
## Criteria for Backporting changes
Anything that does not cause user or downstream dependency regressions can be backported. This includes:
- New Packages / Modules
- Security / Patch updates
- Version updates which include new functionality (but no breaking changes)
- Services which require a client to be up-to-date regardless. (E.g. `spotify`, `steam`, or `discord`)
- Security critical applications (E.g. `firefox`)
## Generating 21.11 Release Notes
(This section also applies to backporting 21.05 release notes: substitute "rl-2111" for "rl-2105".)
Documentation in nixpkgs is transitioning to a markdown-centric workflow. Release notes now require a translation step to convert from markdown to a compatible docbook document.
Steps for updating 21.11 Release notes:
1. Edit `nixos/doc/manual/release-notes/rl-2111.section.md` with the desired changes
2. Run `./nixos/doc/manual/md-to-db.sh` to render `nixos/doc/manual/from_md/release-notes/rl-2111.section.xml`
3. Include changes to `rl-2111.section.md` and `rl-2111.section.xml` in the same commit.
## Reviewing contributions
See the nixpkgs manual for more details on how to [Review contributions](https://nixos.org/nixpkgs/manual/#chap-reviewing-contributions).

@ -21,10 +21,10 @@
# Community
* [Discourse Forum](https://discourse.nixos.org/)
* [IRC - #nixos on freenode.net](irc://irc.freenode.net/#nixos)
* [Matrix Chat](https://matrix.to/#/#community:nixos.org)
* [NixOS Weekly](https://weekly.nixos.org/)
* [Community-maintained wiki](https://nixos.wiki/)
* [Community-maintained list of ways to get in touch](https://nixos.wiki/wiki/Get_In_Touch#Chat) (Discord, Matrix, Telegram, other IRC channels, etc.)
* [Community-maintained list of ways to get in touch](https://nixos.wiki/wiki/Get_In_Touch#Chat) (Discord, Telegram, IRC, etc.)
# Other Project Repositories
@ -46,9 +46,9 @@ Nixpkgs and NixOS are built and tested by our continuous integration
system, [Hydra](https://hydra.nixos.org/).
* [Continuous package builds for unstable/master](https://hydra.nixos.org/jobset/nixos/trunk-combined)
* [Continuous package builds for the NixOS 20.09 release](https://hydra.nixos.org/jobset/nixos/release-20.09)
* [Continuous package builds for the NixOS 21.05 release](https://hydra.nixos.org/jobset/nixos/release-21.05)
* [Tests for unstable/master](https://hydra.nixos.org/job/nixos/trunk-combined/tested#tabs-constituents)
* [Tests for the NixOS 20.09 release](https://hydra.nixos.org/job/nixos/release-20.09/tested#tabs-constituents)
* [Tests for the NixOS 21.05 release](https://hydra.nixos.org/job/nixos/release-21.05/tested#tabs-constituents)
Artifacts successfully built with Hydra are published to cache at
https://cache.nixos.org/. When successful build and test criteria are
@ -87,7 +87,7 @@ Most contributions are based on and merged into these branches:
deemed of sufficiently high quality
For more information about contributing to the project, please visit
the [contributing page](https://github.com/NixOS/nixpkgs/blob/master/.github/CONTRIBUTING.md).
the [contributing page](https://github.com/NixOS/nixpkgs/blob/master/CONTRIBUTING.md).
# Donations

@ -1,4 +1,15 @@
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)))
PANDOC ?= pandoc
pandoc_media_dir = media
# NOTE: Keep in sync with NixOS manual (/nixos/doc/manual/md-to-db.sh).
# TODO: Remove raw-attribute when we can get rid of DocBook altogether.
pandoc_commonmark_enabled_extensions = +attributes+fenced_divs+footnotes+bracketed_spans+definition_lists+pipe_tables+raw_attribute
pandoc_flags = --extract-media=$(pandoc_media_dir) \
--lua-filter=$(PANDOC_LUA_FILTERS_DIR)/diagram-generator.lua \
--lua-filter=labelless-link-is-xref.lua \
-f commonmark$(pandoc_commonmark_enabled_extensions)+smart
.PHONY: all
all: validate format out/html/index.html out/epub/manual.epub
@ -22,7 +33,7 @@ fix-misc-xml:
.PHONY: clean
clean:
rm -f ${MD_TARGETS} doc-support/result .version manual-full.xml functions/library/locations.xml functions/library/generated
rm -rf ./out/ ./highlightjs
rm -rf ./out/ ./highlightjs ./media
.PHONY: validate
validate: manual-full.xml doc-support/result
@ -39,7 +50,7 @@ out/html/index.html: doc-support/result manual-full.xml style.css highlightjs
mkdir -p out/html/highlightjs/
cp -r highlightjs out/html/
cp -r media out/html/
cp -r $(pandoc_media_dir) out/html/
cp ./overrides.css out/html/
cp ./style.css out/html/style.css
@ -54,7 +65,7 @@ out/epub/manual.epub: manual-full.xml
doc-support/result/epub.xsl \
./manual-full.xml
cp -r media out/epub/scratch/OEBPS
cp -r $(pandoc_media_dir) out/epub/scratch/OEBPS
cp ./overrides.css out/epub/scratch/OEBPS
cp ./style.css out/epub/scratch/OEBPS
mkdir -p out/epub/scratch/OEBPS/images/callouts/
@ -89,16 +100,12 @@ functions/library/generated: doc-support/result
ln -rfs ./doc-support/result/function-docs functions/library/generated
%.section.xml: %.section.md
pandoc $^ -t docbook \
--extract-media=media \
--lua-filter=$(PANDOC_LUA_FILTERS_DIR)/diagram-generator.lua \
-f markdown+smart \
| cat > $@
$(PANDOC) $^ -t docbook \
$(pandoc_flags) \
-o $@
%.chapter.xml: %.chapter.md
pandoc $^ -t docbook \
$(PANDOC) $^ -t docbook \
--top-level-division=chapter \
--extract-media=media \
--lua-filter=$(PANDOC_LUA_FILTERS_DIR)/diagram-generator.lua \
-f markdown+smart \
| cat > $@
$(pandoc_flags) \
-o $@

@ -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,57 +18,60 @@ 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`.
## `fetchsvn`
## `fetchsvn` {#fetchsvn}
Used with Subversion. Expects `url` to a Subversion directory, `rev`, and `sha256`.
## `fetchgit`
## `fetchgit` {#fetchgit}
Used with Git. Expects `url` to a Git repo, `rev`, and `sha256`. `rev` in this case can be full the git commit id (SHA1 hash) or a tag name like `refs/tags/v1.0`.
Additionally the following optional arguments can be given: `fetchSubmodules = true` makes `fetchgit` also fetch the submodules of a repository. If `deepClone` is set to true, the entire repository is cloned as opposing to just creating a shallow clone. `deepClone = true` also implies `leaveDotGit = true` which means that the `.git` directory of the clone won't be removed after checkout.
## `fetchfossil`
## `fetchfossil` {#fetchfossil}
Used with Fossil. Expects `url` to a Fossil archive, `rev`, and `sha256`.
## `fetchcvs`
## `fetchcvs` {#fetchcvs}
Used with CVS. Expects `cvsRoot`, `tag`, and `sha256`.
## `fetchhg`
## `fetchhg` {#fetchhg}
Used with Mercurial. Expects `url`, `rev`, and `sha256`.
A number of fetcher functions wrap part of `fetchurl` and `fetchzip`. They are mainly convenience functions intended for commonly used destinations of source code in Nixpkgs. These wrapper fetchers are listed below.
## `fetchFromGitHub`
## `fetchFromGitHub` {#fetchfromgithub}
`fetchFromGitHub` expects four arguments. `owner` is a string corresponding to the GitHub user or organization that controls this repository. `repo` corresponds to the name of the software repository. These are located at the top of every GitHub HTML page as `owner`/`repo`. `rev` corresponds to the Git commit hash or tag (e.g `v1.0`) that will be downloaded from Git. Finally, `sha256` corresponds to the hash of the extracted directory. Again, other hash algorithms are also available but `sha256` is currently preferred.
`fetchFromGitHub` uses `fetchzip` to download the source archive generated by GitHub for the specified revision. If `leaveDotGit`, `deepClone` or `fetchSubmodules` are set to `true`, `fetchFromGitHub` will use `fetchgit` instead. Refer to its section for documentation of these options.
## `fetchFromGitLab`
## `fetchFromGitLab` {#fetchfromgitlab}
This is used with GitLab repositories. The arguments expected are very similar to fetchFromGitHub above.
## `fetchFromGitiles`
## `fetchFromGitiles` {#fetchfromgitiles}
This is used with Gitiles repositories. The arguments expected are similar to fetchgit.
## `fetchFromBitbucket`
## `fetchFromBitbucket` {#fetchfrombitbucket}
This is used with BitBucket repositories. The arguments expected are very similar to fetchFromGitHub above.
## `fetchFromSavannah`
## `fetchFromSavannah` {#fetchfromsavannah}
This is used with Savannah repositories. The arguments expected are very similar to fetchFromGitHub above.
## `fetchFromRepoOrCz`
## `fetchFromRepoOrCz` {#fetchfromrepoorcz}
This is used with repo.or.cz repositories. The arguments expected are very similar to fetchFromGitHub above.
## `fetchFromSourcehut` {#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>

@ -1,6 +1,6 @@
# pkgs.dockerTools {#sec-pkgs-dockerTools}
`pkgs.dockerTools` is a set of functions for creating and manipulating Docker images according to the [ Docker Image Specification v1.2.0 ](https://github.com/moby/moby/blob/master/image/spec/v1.2.md#docker-image-specification-v120). Docker itself is not used to perform any of the operations done by these functions.
`pkgs.dockerTools` is a set of functions for creating and manipulating Docker images according to the [Docker Image Specification v1.2.0](https://github.com/moby/moby/blob/master/image/spec/v1.2.md#docker-image-specification-v120). Docker itself is not used to perform any of the operations done by these functions.
## buildImage {#ssec-pkgs-dockerTools-buildImage}
@ -38,21 +38,21 @@ 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`.
> **_NOTE:_** Using this parameter requires the `kvm` device to be available.
- `config` is used to specify the configuration of the containers that will be started off the built image in Docker. The available options are listed in the [ Docker Image Specification v1.2.0 ](https://github.com/moby/moby/blob/master/image/spec/v1.2.md#image-json-field-descriptions).
- `config` is used to specify the configuration of the containers that will be started off the built image in Docker. The available options are listed in the [Docker Image Specification v1.2.0](https://github.com/moby/moby/blob/master/image/spec/v1.2.md#image-json-field-descriptions).
After the new layer has been created, its closure (to which `contents`, `config` and `runAsRoot` contribute) will be copied in the layer itself. Only new dependencies that are not already in the existing layers will be copied.
@ -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>

@ -1,6 +1,6 @@
# Cataclysm: Dark Days Ahead {#cataclysm-dark-days-ahead}
## How to install Cataclysm DDA
## How to install Cataclysm DDA {#how-to-install-cataclysm-dda}
To install the latest stable release of Cataclysm DDA to your profile, execute
`nix-env -f "<nixpkgs>" -iA cataclysm-dda`. For the curses build (build
@ -34,7 +34,42 @@ cataclysm-dda.override {
}
```
## Customizing with mods
## Important note for overriding packages {#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 {#customizing-with-mods}
To install Cataclysm DDA with mods of your choice, you can use `withMods`
attribute:

@ -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>

@ -6,6 +6,6 @@ To start a development environment do
nix-shell -p elmPackages.elm elmPackages.elm-format
```
To update the Elm compiler, see <filename>nixpkgs/pkgs/development/compilers/elm/README.md</filename>.
To update the Elm compiler, see `nixpkgs/pkgs/development/compilers/elm/README.md`.
To package Elm applications, [read about elm2nix](https://github.com/hercules-ci/elm2nix#elm2nix).

@ -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

@ -1,6 +1,6 @@
# Firefox {#sec-firefox}
## Build wrapped Firefox with extensions and policies
## Build wrapped Firefox with extensions and policies {#build-wrapped-firefox-with-extensions-and-policies}
The `wrapFirefox` function allows to pass policies, preferences and extension that are available to firefox. With the help of `fetchFirefoxAddon` this allows build a firefox version that already comes with addons pre-installed:

@ -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" />

@ -4,11 +4,11 @@ OpenGL support varies depending on which hardware is used and which drivers are
Broadly, we support both GL vendors: Mesa and NVIDIA.
## NixOS Desktop
## NixOS Desktop {#nixos-desktop}
The NixOS desktop or other non-headless configurations are the primary target for OpenGL libraries and applications. The current solution for discovering which drivers are available is based on [libglvnd](https://gitlab.freedesktop.org/glvnd/libglvnd). `libglvnd` performs "vendor-neutral dispatch", trying a variety of techniques to find the system's GL implementation. In practice, this will be either via standard GLX for X11 users or EGL for Wayland users, and supporting either NVIDIA or Mesa extensions.
## Nix on GNU/Linux
## Nix on GNU/Linux {#nix-on-gnulinux}
If you are using a non-NixOS GNU/Linux/X11 desktop with free software video drivers, consider launching OpenGL-dependent programs from Nixpkgs with Nixpkgs versions of `libglvnd` and `mesa.drivers` in `LD_LIBRARY_PATH`. For Mesa drivers, the Linux kernel version doesn't have to match nixpkgs.

@ -20,6 +20,7 @@ Use `programs.steam.enable = true;` if you want to add steam to systemPackages a
## Troubleshooting {#sec-steam-troub}
- **Steam fails to start. What do I do?**
Try to run
```ShellSession
@ -32,37 +33,30 @@ Use `programs.steam.enable = true;` if you want to add steam to systemPackages a
- The `newStdcpp` parameter was removed since NixOS 17.09 and should not be needed anymore.
- Steam ships statically linked with a version of libcrypto that conflics with the one dynamically loaded by radeonsi_dri.so. If you get the error
```
steam.sh: line 713: 7842 Segmentation fault (core dumped)
```
have a look at [this pull request](https://github.com/NixOS/nixpkgs/pull/20269).
- **Java**
1. There is no java in steam chrootenv by default. If you get a message like
```
/home/foo/.local/share/Steam/SteamApps/common/towns/towns.sh: line 1: java: command not found
```
```
/home/foo/.local/share/Steam/SteamApps/common/towns/towns.sh: line 1: java: command not found
```
You need to add
you need to add
```nix
steam.override { withJava = true; };
```
```nix
steam.override { withJava = true; };
```
## steam-run {#sec-steam-run}
The FHS-compatible chroot used for steam can also be used to run other linux games that expect a FHS environment. To do it, add
```nix
pkgs.steam.override ({
nativeOnly = true;
newStdcpp = true;
}).run
```
to your configuration, rebuild, and run the game with
The FHS-compatible chroot used for Steam can also be used to run other Linux games that expect a FHS environment. To use it, install the `steam-run-native` package and run the game with
```
steam-run ./foo

@ -41,7 +41,7 @@ weechat.override {
configure = { availablePlugins, ... }: {
init = ''
/set foo bar
/server add freenode chat.freenode.org
/server add libera irc.libera.chat
'';
};
}

@ -2,7 +2,7 @@
The Nix expressions for the X.org packages reside in `pkgs/servers/x11/xorg/default.nix`. This file is automatically generated from lists of tarballs in an X.org release. As such it should not be modified directly; rather, you should modify the lists, the generator script or the file `pkgs/servers/x11/xorg/overrides.nix`, in which you can override or add to the derivations produced by the generator.
## Katamari Tarballs
## Katamari Tarballs {#katamari-tarballs}
X.org upstream releases used to include [katamari](https://en.wiktionary.org/wiki/%E3%81%8B%E3%81%9F%E3%81%BE%E3%82%8A) releases, which included a holistic recommended version for each tarball, up until 7.7. To create a list of tarballs in a katamari release:
@ -14,11 +14,11 @@ cat $(PRINT_PATH=1 nix-prefetch-url $url | tail -n 1) \
| sort > "tarballs-$release.list"
```
## Individual Tarballs
## Individual Tarballs {#individual-tarballs}
The upstream release process for [X11R7.8](https://x.org/wiki/Releases/7.8/) does not include a planned katamari. Instead, each component of X.org is released as its own tarball. We maintain `pkgs/servers/x11/xorg/tarballs.list` as a list of tarballs for each individual package. This list includes X.org core libraries and protocol descriptions, extra newer X11 interface libraries, like `xorg.libxcb`, and classic utilities which are largely unused but still available if needed, like `xorg.imake`.
## Generating Nix Expressions
## Generating Nix Expressions {#generating-nix-expressions}
The generator is invoked as follows:
@ -29,6 +29,6 @@ cd pkgs/servers/x11/xorg
For each of the tarballs in the `.list` files, the script downloads it, unpacks it, and searches its `configure.ac` and `*.pc.in` files for dependencies. This information is used to generate `default.nix`. The generator caches downloaded tarballs between runs. Pay close attention to the `NOT FOUND: $NAME` messages at the end of the run, since they may indicate missing dependencies. (Some might be optional dependencies, however.)
## Overriding the Generator
## Overriding the Generator {#overriding-the-generator}
If the expression for a package requires derivation attributes that the generator cannot figure out automatically (say, `patches` or a `postInstall` hook), you should modify `pkgs/servers/x11/xorg/overrides.nix`.

@ -18,6 +18,8 @@
Additional commands to be executed for finalizing the derivation with runner script.
- `runScript`
A command that would be executed inside the sandbox and passed all the command line arguments. It defaults to `bash`.
- `profile`
Optional script for `/etc/profile` within the sandbox.
One can create a simple environment using a `shell.nix` like that:
@ -28,7 +30,7 @@ One can create a simple environment using a `shell.nix` like that:
name = "simple-x11-env";
targetPkgs = pkgs: (with pkgs;
[ udev
alsaLib
alsa-lib
]) ++ (with pkgs.xorg;
[ libX11
libXcursor
@ -36,7 +38,7 @@ One can create a simple environment using a `shell.nix` like that:
]);
multiPkgs = pkgs: (with pkgs;
[ udev
alsaLib
alsa-lib
]);
runScript = "bash";
}).env

@ -1,15 +1,17 @@
# pkgs.mkShell {#sec-pkgs-mkShell}
`pkgs.mkShell` is a special kind of derivation that is only useful when using it combined with `nix-shell`. It will in fact fail to instantiate when invoked with `nix-build`.
`pkgs.mkShell` is a special kind of derivation that is only useful when using
it combined with `nix-shell`. It will in fact fail to instantiate when invoked
with `nix-build`.
## Usage {#sec-pkgs-mkShell-usage}
```nix
{ pkgs ? import <nixpkgs> {} }:
pkgs.mkShell {
# this will make all the build inputs from hello and gnutar
# available to the shell environment
# specify which packages to add to the shell environment
packages = [ pkgs.gnumake ];
# add all the dependencies, of the given packages, to the shell environment
inputsFrom = with pkgs; [ hello gnutar ];
buildInputs = [ pkgs.gnumake ];
}
```

@ -37,7 +37,7 @@ This works just like `runCommand`. The only difference is that it also provides
Variant of `runCommand` that forces the derivation to be built locally, it is not substituted. This is intended for very cheap commands (<1s execution time). It saves on the network roundrip and can speed up a build.
::: note
::: {.note}
This sets [`allowSubstitutes` to `false`](https://nixos.org/nix/manual/#adv-attr-allowSubstitutes), so only use `runCommandLocal` if you are certain the user will always have a builder for the `system` of the derivation. This should be true for most trivial use cases (e.g. just copying some files to a different location or adding symlinks), because there the `system` is usually the same as `builtins.currentSystem`.
:::
@ -50,3 +50,50 @@ Many more commands wrap `writeTextFile` including `writeText`, `writeTextDir`, `
## `symlinkJoin` {#trivial-builder-symlinkJoin}
This can be used to put many derivations into the same directory structure. It works by creating a new derivation and adding symlinks to each of the paths listed. It expects two arguments, `name`, and `paths`. `name` is the name used in the Nix store path for the created derivation. `paths` is a list of paths that will be symlinked. These paths can be to Nix store derivations or any other subdirectory contained within.
## `writeReferencesToFile` {#trivial-builder-writeReferencesToFile}
Writes the closure of transitive dependencies to a file.
This produces the equivalent of `nix-store -q --requisites`.
For example,
```nix
writeReferencesToFile (writeScriptBin "hi" ''${hello}/bin/hello'')
```
produces an output path `/nix/store/<hash>-runtime-deps` containing
```nix
/nix/store/<hash>-hello-2.10
/nix/store/<hash>-hi
/nix/store/<hash>-libidn2-2.3.0
/nix/store/<hash>-libunistring-0.9.10
/nix/store/<hash>-glibc-2.32-40
```
You can see that this includes `hi`, the original input path,
`hello`, which is a direct reference, but also
the other paths that are indirectly required to run `hello`.
## `writeDirectReferencesToFile` {#trivial-builder-writeDirectReferencesToFile}
Writes the set of references to the output file, that is, their immediate dependencies.
This produces the equivalent of `nix-store -q --references`.
For example,
```nix
writeDirectReferencesToFile (writeScriptBin "hi" ''${hello}/bin/hello'')
```
produces an output path `/nix/store/<hash>-runtime-references` containing
```nix
/nix/store/<hash>-hello-2.10
```
but none of `hello`'s dependencies, because those are not referenced directly
by `hi`'s output.

@ -0,0 +1,604 @@
# 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 [](#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 "" ...
})
```
- Unnecessary string conversions should be avoided. Do
```nix
rev = version;
```
instead of
```nix
rev = "${version}";
```
- Arguments should be listed in the order they are used, with the exception of `lib`, which always goes first.
## 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 [](#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
```
If a patch is available online but does not cleanly apply, it can be modified in some fixed ways by using additional optional arguments for `fetchpatch`:
- `stripLen`: Remove the first `stripLen` components of pathnames in the patch.
- `extraPrefix`: Prefix pathnames by this string.
- `excludes`: Exclude files matching this pattern.
- `includes`: Include only files matching this pattern.
- `revert`: Revert the patch.
Note that because the checksum is computed after applying these effects, using or modifying these arguments will have no effect unless the `sha256` argument is changed as well.
## 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,99 @@
# Contributing to this documentation {#chap-contributing}
The sources of the Nixpkgs manual are in the [doc](https://github.com/NixOS/nixpkgs/tree/master/doc) subdirectory of the Nixpkgs repository. The manual is still partially written in DocBook but it is progressively being converted to [Markdown](#sec-contributing-markup).
You can quickly check your edits with `make`:
```ShellSession
$ cd /path/to/nixpkgs/doc
$ nix-shell
[nix-shell]$ make
```
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`.
## Syntax {#sec-contributing-markup}
As per [RFC 0072](https://github.com/NixOS/rfcs/pull/72), all new documentation content should be written in [CommonMark](https://commonmark.org/) Markdown dialect.
Additionally, the following syntax extensions are currently used:
- []{#ssec-contributing-markup-anchors}
Explicitly defined **anchors** on headings, to allow linking to sections. These should be always used, to ensure the anchors can be linked even when the heading text changes, and to prevent conflicts between [automatically assigned identifiers](https://github.com/jgm/commonmark-hs/blob/master/commonmark-extensions/test/auto_identifiers.md).
It uses the widely compatible [header attributes](https://github.com/jgm/commonmark-hs/blob/master/commonmark-extensions/test/attributes.md) syntax:
```markdown
## Syntax {#sec-contributing-markup}
```
- []{#ssec-contributing-markup-anchors-inline}
**Inline anchors**, which allow linking arbitrary place in the text (e.g. individual list items, sentences…).
They are defined using a hybrid of the link syntax with the attributes syntax known from headings, called [bracketed spans](https://github.com/jgm/commonmark-hs/blob/master/commonmark-extensions/test/bracketed_spans.md):
```markdown
- []{#ssec-gnome-hooks-glib} `glib` setup hook will populate `GSETTINGS_SCHEMAS_PATH` and then `wrapGAppsHook` will prepend it to `XDG_DATA_DIRS`.
```
- []{#ssec-contributing-markup-automatic-links}
If you **omit a link text** for a link pointing to a section, the text will be substituted automatically. For example, `[](#chap-contributing)` will result in [](#chap-contributing).
This syntax is taken from [MyST](https://myst-parser.readthedocs.io/en/latest/using/syntax.html#targets-and-cross-referencing).
- []{#ssec-contributing-markup-admonitions}
**Admonitions**, set off from the text to bring attention to something.
It uses pandoc’s [fenced `div`s syntax](https://github.com/jgm/commonmark-hs/blob/master/commonmark-extensions/test/fenced_divs.md):
```markdown
::: {.warning}
This is a warning
:::
```
which renders as
> ::: {.warning}
> This is a warning.
> :::
The following are supported:
- [`caution`](https://tdg.docbook.org/tdg/5.0/caution.html)
- [`important`](https://tdg.docbook.org/tdg/5.0/important.html)
- [`note`](https://tdg.docbook.org/tdg/5.0/note.html)
- [`tip`](https://tdg.docbook.org/tdg/5.0/tip.html)
- [`warning`](https://tdg.docbook.org/tdg/5.0/warning.html)
- []{#ssec-contributing-markup-definition-lists}
[**Definition lists**](https://github.com/jgm/commonmark-hs/blob/master/commonmark-extensions/test/definition_lists.md), for defining a group of terms:
```markdown
pear
: green or yellow bulbous fruit
watermelon
: green fruit with red flesh
```
which renders as
> pear
> : green or yellow bulbous fruit
>
> watermelon
> : green fruit with red flesh
For contributing to the legacy parts, please see [DocBook: The Definitive Guide](https://tdg.docbook.org/) or the [DocBook rocks! primer](https://web.archive.org/web/20200816233747/https://docbook.rocks/).

@ -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 [](#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,207 @@
# 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>

@ -62,26 +62,75 @@
- Push your changes to your fork of nixpkgs.
- Create the pull request
- Follow [the contribution guidelines](https://github.com/NixOS/nixpkgs/blob/master/.github/CONTRIBUTING.md#submitting-changes).
- Follow [the contribution guidelines](https://github.com/NixOS/nixpkgs/blob/master/CONTRIBUTING.md#submitting-changes).
## Submitting security fixes {#submitting-changes-submitting-security-fixes}
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.:
- 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";
})
```
```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 {#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 +163,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}
@ -144,7 +193,7 @@ It’s important to test any executables generated by a build when you change or
### Meets Nixpkgs contribution standards {#submitting-changes-contribution-standards}
The last checkbox is fits [CONTRIBUTING.md](https://github.com/NixOS/nixpkgs/blob/master/.github/CONTRIBUTING.md). The contributing document has detailed information on standards the Nix community has for commit messages, reviews, licensing of contributions you make to the project, etc\... Everyone should read and understand the standards the community has for contributing before submitting a pull request.
The last checkbox is fits [CONTRIBUTING.md](https://github.com/NixOS/nixpkgs/blob/master/CONTRIBUTING.md). The contributing document has detailed information on standards the Nix community has for commit messages, reviews, licensing of contributions you make to the project, etc\... Everyone should read and understand the standards the community has for contributing before submitting a pull request.
## Hotfixing pull requests {#submitting-changes-hotfixing-pull-requests}
@ -191,7 +240,7 @@ The `staging` branch is a development branch where mass-rebuilds go. It should o
### Staging-next branch {#submitting-changes-staging-next-branch}
The `staging-next` branch is for stabilizing mass-rebuilds submitted to the `staging` branch prior to merging them into `master`. Mass-rebuilds should go via the `staging` branch. It should only see non-breaking commits that are fixing issues blocking it from being merged into the `master ` branch.
The `staging-next` branch is for stabilizing mass-rebuilds submitted to the `staging` branch prior to merging them into `master`. Mass-rebuilds must go via the `staging` branch. It must only see non-breaking commits that are fixing issues blocking it from being merged into the `master ` branch.
If the branch is already in a broken state, please refrain from adding extra new breakages. Stabilize it for a few days and then merge into master.
@ -201,6 +250,8 @@ For cherry-picking a commit to a stable release branch (“backporting”), use
Add a reason for the backport by using `git cherry-pick -xe <original commit>` instead when it is not obvious from the original commit message. It is not needed when it's a minor version update that includes security and bug fixes but don't add new features or when the commit fixes an otherwise broken package.
For backporting Pull Requests to stable branches, assign label `backport <branch>` to the original Pull Requests and automation should take care of the rest once the Pull Requests is merged.
Here is an example of a cherry-picked commit message with good reason description:
```
@ -218,3 +269,14 @@ Other examples of reasons are:
- Previously the build would fail due to, e.g., `getaddrinfo` not being defined
- The previous download links were all broken
- Crash when starting on some X11 systems
#### Acceptable backport criteria
The stable branch does have some changes which cannot be backported. Most notable are breaking changes. The desire is to have stable users be uninterrupted when updating packages.
However, many changes are able to be backported, including:
- New Packages / Modules
- Security / Patch updates
- Version updates which include new functionality (but no breaking changes)
- Services which require a client to be up-to-date regardless. (E.g. `spotify`, `steam`, or `discord`)
- Security critical applications (E.g. `firefox`)

@ -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).

@ -17,10 +17,6 @@ in pkgs.stdenv.mkDerivation {
src = lib.cleanSource ./.;
makeFlags = [
"PANDOC_LUA_FILTERS_DIR=${pkgs.pandoc-lua-filters}/share/pandoc/filters"
];
postPatch = ''
ln -s ${doc-support} ./doc-support/result
'';
@ -37,4 +33,7 @@ in pkgs.stdenv.mkDerivation {
echo "doc manual $dest manual.html" >> $out/nix-support/hydra-build-products
echo "doc manual $dest nixpkgs-manual.epub" >> $out/nix-support/hydra-build-products
'';
# Environment variables
PANDOC_LUA_FILTERS_DIR = "${pkgs.pandoc-lua-filters}/share/pandoc/filters";
}

@ -22,5 +22,6 @@ with pkgs; stdenv.mkDerivation {
docgen lists 'List manipulation functions'
docgen debug 'Debugging functions'
docgen options 'NixOS / nixpkgs option handling'
docgen sources 'Source filtering functions'
'';
}

@ -7,8 +7,8 @@
The nixpkgs repository has several utility functions to manipulate Nix expressions.
</para>
<xi:include href="functions/library.xml" />
<xi:include href="functions/generators.xml" />
<xi:include href="functions/debug.xml" />
<xi:include href="functions/prefer-remote-fetch.xml" />
<xi:include href="functions/nix-gitignore.xml" />
<xi:include href="functions/generators.section.xml" />
<xi:include href="functions/debug.section.xml" />
<xi:include href="functions/prefer-remote-fetch.section.xml" />
<xi:include href="functions/nix-gitignore.section.xml" />
</chapter>

@ -0,0 +1,5 @@
# Debugging Nix Expressions {#sec-debug}
Nix is a unityped, dynamic language, this means every value can potentially appear anywhere. Since it is also non-strict, evaluation order and what ultimately is evaluated might surprise you. Therefore it is important to be able to debug nix expressions.
In the `lib/debug.nix` file you will find a number of functions that help (pretty-)printing values while evaluation is running. You can even specify how deep these values should be printed recursively, and transform them on the fly. Please consult the docstrings in `lib/debug.nix` for usage information.

@ -1,14 +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-debug">
<title>Debugging Nix Expressions</title>
<para>
Nix is a unityped, dynamic language, this means every value can potentially appear anywhere. Since it is also non-strict, evaluation order and what ultimately is evaluated might surprise you. Therefore it is important to be able to debug nix expressions.
</para>
<para>
In the <literal>lib/debug.nix</literal> file you will find a number of functions that help (pretty-)printing values while evaluation is runnnig. You can even specify how deep these values should be printed recursively, and transform them on the fly. Please consult the docstrings in <literal>lib/debug.nix</literal> for usage information.
</para>
</section>

@ -0,0 +1,56 @@
# Generators {#sec-generators}
Generators are functions that create file formats from nix data structures, e.g. for configuration files. There are generators available for: `INI`, `JSON` and `YAML`
All generators follow a similar call interface: `generatorName configFunctions data`, where `configFunctions` is an attrset of user-defined functions that format nested parts of the content. They each have common defaults, so often they do not need to be set manually. An example is `mkSectionName ? (name: libStr.escape [ "[" "]" ] name)` from the `INI` generator. It receives the name of a section and sanitizes it. The default `mkSectionName` escapes `[` and `]` with a backslash.
Generators can be fine-tuned to produce exactly the file format required by your application/service. One example is an INI-file format which uses `: ` as separator, the strings `"yes"`/`"no"` as boolean values and requires all string values to be quoted:
```nix
with lib;
let
customToINI = generators.toINI {
# specifies how to format a key/value pair
mkKeyValue = generators.mkKeyValueDefault {
# specifies the generated string for a subset of nix values
mkValueString = v:
if v == true then ''"yes"''
else if v == false then ''"no"''
else if isString v then ''"${v}"''
# and delegats all other values to the default generator
else generators.mkValueStringDefault {} v;
} ":";
};
# the INI file can now be given as plain old nix values
in customToINI {
main = {
pushinfo = true;
autopush = false;
host = "localhost";
port = 42;
};
mergetool = {
merge = "diff3";
};
}
```
This will produce the following INI file as nix string:
```INI
[main]
autopush:"no"
host:"localhost"
port:42
pushinfo:"yes"
str\:ange:"very::strange"
[mergetool]
merge:"diff3"
```
::: {.note}
Nix store paths can be converted to strings by enclosing a derivation attribute like so: `"${drv}"`.
:::
Detailed documentation for each generator can be found in `lib/generators.nix`.

@ -1,74 +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-generators">
<title>Generators</title>
<para>
Generators are functions that create file formats from nix data structures, e.g. for configuration files. There are generators available for: <literal>INI</literal>, <literal>JSON</literal> and <literal>YAML</literal>
</para>
<para>
All generators follow a similar call interface: <code>generatorName configFunctions data</code>, where <literal>configFunctions</literal> is an attrset of user-defined functions that format nested parts of the content. They each have common defaults, so often they do not need to be set manually. An example is <code>mkSectionName ? (name: libStr.escape [ "[" "]" ] name)</code> from the <literal>INI</literal> generator. It receives the name of a section and sanitizes it. The default <literal>mkSectionName</literal> escapes <literal>[</literal> and <literal>]</literal> with a backslash.
</para>
<para>
Generators can be fine-tuned to produce exactly the file format required by your application/service. One example is an INI-file format which uses <literal>: </literal> as separator, the strings <literal>"yes"</literal>/<literal>"no"</literal> as boolean values and requires all string values to be quoted:
</para>
<programlisting>
with lib;
let
customToINI = generators.toINI {
# specifies how to format a key/value pair
mkKeyValue = generators.mkKeyValueDefault {
# specifies the generated string for a subset of nix values
mkValueString = v:
if v == true then ''"yes"''
else if v == false then ''"no"''
else if isString v then ''"${v}"''
# and delegats all other values to the default generator
else generators.mkValueStringDefault {} v;
} ":";
};
# the INI file can now be given as plain old nix values
in customToINI {
main = {
pushinfo = true;
autopush = false;
host = "localhost";
port = 42;
};
mergetool = {
merge = "diff3";
};
}
</programlisting>
<para>
This will produce the following INI file as nix string:
</para>
<programlisting>
[main]
autopush:"no"
host:"localhost"
port:42
pushinfo:"yes"
str\:ange:"very::strange"
[mergetool]
merge:"diff3"
</programlisting>
<note>
<para>
Nix store paths can be converted to strings by enclosing a derivation attribute like so: <code>"${drv}"</code>.
</para>
</note>
<para>
Detailed documentation for each generator can be found in <literal>lib/generators.nix</literal>.
</para>
</section>

@ -25,4 +25,6 @@
<xi:include href="./library/generated/debug.xml" />
<xi:include href="./library/generated/options.xml" />
<xi:include href="./library/generated/sources.xml" />
</section>

@ -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" />
@ -166,7 +166,7 @@ lib.attrsets.setAttrByPath [ "a" "b" ] 3
<xi:include href="./locations.xml" xpointer="lib.attrsets.getAttrFromPath" />
<para>
Like <xref linkend="function-library-lib.attrsets.attrByPath" /> except without a default, and it will throw if the value doesn't exist.
Like [](#function-library-lib.attrsets.attrByPath) except without a default, and it will throw if the value doesn't exist.
</para>
<variablelist>
@ -855,7 +855,7 @@ lib.attrsets.mapAttrs' (name: value: lib.attrsets.nameValuePair ("foo_" + name)
<title><function>lib.attrsets.mapAttrsToList</function></title>
<subtitle><literal>mapAttrsToList :: (String -> Any -> Any) ->
AttrSet -> Any</literal>
AttrSet -> [Any]</literal>
</subtitle>
<xi:include href="./locations.xml" xpointer="lib.attrsets.mapAttrsToList" />
@ -1480,7 +1480,7 @@ lib.attrsets.zipAttrsWith
<xi:include href="./locations.xml" xpointer="lib.attrsets.zipAttrs" />
<para>
Merge sets of attributes and combine each attribute value in to a list. Similar to <xref linkend="function-library-lib.attrsets.zipAttrsWith" /> where the merge function returns a list of all values.
Merge sets of attributes and combine each attribute value in to a list. Similar to [](#function-library-lib.attrsets.zipAttrsWith) where the merge function returns a list of all values.
</para>
<variablelist>
@ -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>

@ -0,0 +1,49 @@
# pkgs.nix-gitignore {#sec-pkgs-nix-gitignore}
`pkgs.nix-gitignore` is a function that acts similarly to `builtins.filterSource` but also allows filtering with the help of the gitignore format.
## Usage {#sec-pkgs-nix-gitignore-usage}
`pkgs.nix-gitignore` exports a number of functions, but you\'ll most likely need either `gitignoreSource` or `gitignoreSourcePure`. As their first argument, they both accept either 1. a file with gitignore lines or 2. a string with gitignore lines, or 3. a list of either of the two. They will be concatenated into a single big string.
```nix
{ pkgs ? import <nixpkgs> {} }:
nix-gitignore.gitignoreSource [] ./source
# Simplest version
nix-gitignore.gitignoreSource "supplemental-ignores\n" ./source
# This one reads the ./source/.gitignore and concats the auxiliary ignores
nix-gitignore.gitignoreSourcePure "ignore-this\nignore-that\n" ./source
# Use this string as gitignore, don't read ./source/.gitignore.
nix-gitignore.gitignoreSourcePure ["ignore-this\nignore-that\n", ~/.gitignore] ./source
# It also accepts a list (of strings and paths) that will be concatenated
# once the paths are turned to strings via readFile.
```
These functions are derived from the `Filter` functions by setting the first filter argument to `(_: _: true)`:
```nix
gitignoreSourcePure = gitignoreFilterSourcePure (_: _: true);
gitignoreSource = gitignoreFilterSource (_: _: true);
```
Those filter functions accept the same arguments the `builtins.filterSource` function would pass to its filters, thus `fn: gitignoreFilterSourcePure fn ""` should be extensionally equivalent to `filterSource`. The file is blacklisted if it\'s blacklisted by either your filter or the gitignoreFilter.
If you want to make your own filter from scratch, you may use
```nix
gitignoreFilter = ign: root: filterPattern (gitignoreToPatterns ign) root;
```
## gitignore files in subdirectories {#sec-pkgs-nix-gitignore-usage-recursive}
If you wish to use a filter that would search for .gitignore files in subdirectories, just like git does by default, use this function:
```nix
gitignoreFilterRecursiveSource = filter: patterns: root:
# OR
gitignoreRecursiveSource = gitignoreFilterSourcePure (_: _: true);
```

@ -1,70 +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-nix-gitignore">
<title>pkgs.nix-gitignore</title>
<para>
<function>pkgs.nix-gitignore</function> is a function that acts similarly to <literal>builtins.filterSource</literal> but also allows filtering with the help of the gitignore format.
</para>
<section xml:id="sec-pkgs-nix-gitignore-usage">
<title>Usage</title>
<para>
<literal>pkgs.nix-gitignore</literal> exports a number of functions, but you'll most likely need either <literal>gitignoreSource</literal> or <literal>gitignoreSourcePure</literal>. As their first argument, they both accept either 1. a file with gitignore lines or 2. a string with gitignore lines, or 3. a list of either of the two. They will be concatenated into a single big string.
</para>
<programlisting><![CDATA[
{ pkgs ? import <nixpkgs> {} }:
nix-gitignore.gitignoreSource [] ./source
# Simplest version
nix-gitignore.gitignoreSource "supplemental-ignores\n" ./source
# This one reads the ./source/.gitignore and concats the auxiliary ignores
nix-gitignore.gitignoreSourcePure "ignore-this\nignore-that\n" ./source
# Use this string as gitignore, don't read ./source/.gitignore.
nix-gitignore.gitignoreSourcePure ["ignore-this\nignore-that\n", ~/.gitignore] ./source
# It also accepts a list (of strings and paths) that will be concatenated
# once the paths are turned to strings via readFile.
]]></programlisting>
<para>
These functions are derived from the <literal>Filter</literal> functions by setting the first filter argument to <literal>(_: _: true)</literal>:
</para>
<programlisting><![CDATA[
gitignoreSourcePure = gitignoreFilterSourcePure (_: _: true);
gitignoreSource = gitignoreFilterSource (_: _: true);
]]></programlisting>
<para>
Those filter functions accept the same arguments the <literal>builtins.filterSource</literal> function would pass to its filters, thus <literal>fn: gitignoreFilterSourcePure fn ""</literal> should be extensionally equivalent to <literal>filterSource</literal>. The file is blacklisted iff it's blacklisted by either your filter or the gitignoreFilter.
</para>
<para>
If you want to make your own filter from scratch, you may use
</para>
<programlisting><![CDATA[
gitignoreFilter = ign: root: filterPattern (gitignoreToPatterns ign) root;
]]></programlisting>
</section>
<section xml:id="sec-pkgs-nix-gitignore-usage-recursive">
<title>gitignore files in subdirectories</title>
<para>
If you wish to use a filter that would search for .gitignore files in subdirectories, just like git does by default, use this function:
</para>
<programlisting><![CDATA[
gitignoreFilterRecursiveSource = filter: patterns: root:
# OR
gitignoreRecursiveSource = gitignoreFilterSourcePure (_: _: true);
]]></programlisting>
</section>
</section>

@ -0,0 +1,17 @@
# prefer-remote-fetch overlay {#sec-prefer-remote-fetch}
`prefer-remote-fetch` is an overlay that download sources on remote builder. This is useful when the evaluating machine has a slow upload while the builder can fetch faster directly from the source. To use it, put the following snippet as a new overlay:
```nix
self: super:
(super.prefer-remote-fetch self super)
```
A full configuration example for that sets the overlay up for your own account, could look like this
```ShellSession
$ mkdir ~/.config/nixpkgs/overlays/
$ cat > ~/.config/nixpkgs/overlays/prefer-remote-fetch.nix <<EOF
self: super: super.prefer-remote-fetch self super
EOF
```

@ -1,21 +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-prefer-remote-fetch">
<title>prefer-remote-fetch overlay</title>
<para>
<function>prefer-remote-fetch</function> is an overlay that download sources on remote builder. This is useful when the evaluating machine has a slow upload while the builder can fetch faster directly from the source. To use it, put the following snippet as a new overlay:
<programlisting>
self: super:
(super.prefer-remote-fetch self super)
</programlisting>
A full configuration example for that sets the overlay up for your own account, could look like this
<screen>
<prompt>$ </prompt>mkdir ~/.config/nixpkgs/overlays/
<prompt>$ </prompt>cat &gt; ~/.config/nixpkgs/overlays/prefer-remote-fetch.nix &lt;&lt;EOF
self: super: super.prefer-remote-fetch self super
EOF
</screen>
</para>
</section>

@ -0,0 +1,24 @@
local function starts_with(start, str)
return str:sub(1, #start) == start
end
local function escape_xml_arg(arg)
amps = arg:gsub('&', '&amp;')
amps_quotes = amps:gsub('"', '&quot;')
amps_quotes_lt = amps_quotes:gsub('<', '&lt;')
return amps_quotes_lt
end
function Link(elem)
has_no_content = #elem.content == 0
targets_anchor = starts_with('#', elem.target)
has_no_attributes = elem.title == '' and elem.identifier == '' and #elem.classes == 0 and #elem.attributes == 0
if has_no_content and targets_anchor and has_no_attributes then
-- xref expects idref without the pound-sign
target_without_hash = elem.target:sub(2, #elem.target)
return pandoc.RawInline('docbook', '<xref linkend="' .. escape_xml_arg(target_without_hash) .. '" />')
end
end

@ -1,62 +1,126 @@
# Agda {#agda}
## How to use Agda
## How to use Agda {#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:
```
$ agda -l standard-library -i . MyFile.agda
```
```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:
```
name: my-library
include: .
depend: standard-library
```
```
name: my-library
include: .
depend: standard-library
```
* Create the file `~/.agda/defaults` and add any libraries you want to use by default.
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.
## Compiling Agda {#compiling-agda}
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;
}
```
## Writing Agda packages
## Writing Agda packages {#writing-agda-packages}
To write a nix derivation for an Agda library, first check that the library has a `*.agda-lib` file.
A derivation can then be written using `agdaPackages.mkDerivation`. This has similar arguments to `stdenv.mkDerivation` with the following additions:
@ -65,27 +129,50 @@ 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`.
### Building Agda packages
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 {#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.
Additionally, a `preBuild` or `configurePhase` can be used if there are steps that need to be done prior to checking the `Everything.agda` file.
`agda` and the Agda libraries contained in `buildInputs` are made available during the build phase.
### Installing Agda packages
### Installing Agda packages {#installing-agda-packages}
The default install phase copies Agda source files, Agda interface files (`*.agdai`) and `*.agda-lib` files to the output directory.
This can be overridden.
By default, Agda sources are files ending on `.agda`, or literate Agda files ending on `.lagda`, `.lagda.tex`, `.lagda.org`, `.lagda.md`, `.lagda.rst`. The list of recognised Agda source extensions can be extended by setting the `extraExtensions` config variable.
## Adding Agda packages to Nixpkgs
## Adding Agda packages to Nixpkgs {#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";
@ -101,6 +188,7 @@ mkDerivation {
'';
}
```
This library has a file called `.agda-lib`, and so we give an empty string to `libraryFile` as nothing precedes `.agda-lib` in the filename. This file contains `name: IAL-1.3`, and so we let `libraryName = "IAL-1.3"`. This library does not use an `Everything.agda` file and instead has a Makefile, so there is no need to set `everythingFile` and we set a custom `buildPhase`.
When writing an Agda package it is essential to make sure that no `.agda-lib` file gets added to the store as a single file (for example by using `writeText`). This causes Agda to think that the nix store is a Agda library and it will attempt to write to it whenever it typechecks something. See [https://github.com/agda/agda/issues/4613](https://github.com/agda/agda/issues/4613).

@ -3,8 +3,8 @@
The Android build environment provides three major features and a number of
supporting features.
Deploying an Android SDK installation with plugins
--------------------------------------------------
## Deploying an Android SDK installation with plugins {#deploying-an-android-sdk-installation-with-plugins}
The first use case is deploying the SDK with a desired set of plugins or subsets
of an SDK.
@ -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
@ -132,8 +136,8 @@ in
androidComposition.platform-tools
```
Using predefined Android package compositions
---------------------------------------------
## Using predefined Android package compositions {#using-predefined-android-package-compositions}
In addition to composing an Android package set manually, it is also possible
to use a predefined composition that contains all basic packages for a specific
Android version, such as version 9.0 (API-level 28).
@ -155,12 +159,13 @@ with import <nixpkgs> {};
androidenv.androidPkgs_9_0.platform-tools
```
Building an Android application
-------------------------------
## Building an Android application {#building-an-android-application}
In addition to the SDK, it is also possible to build an Ant-based Android
project and automatically deploy all the Android plugins that a project
requires.
```nix
with import <nixpkgs> {};
@ -195,8 +200,8 @@ to build Android apps. An Android APK gets exposed as a build product and can be
installed on any Android device with a web browser by navigating to the build
result page.
Spawning emulator instances
---------------------------
## Spawning emulator instances {#spawning-emulator-instances}
For testing purposes, it can also be quite convenient to automatically generate
scripts that spawn emulator instances with all desired configuration settings.
@ -237,8 +242,8 @@ androidenv.emulateApp {
In addition to prebuilt APKs, you can also bind the APK parameter to a
`buildApp {}` function invocation shown in the previous example.
Notes on environment variables in Android projects
--------------------------------------------------
## Notes on environment variables in Android projects {#notes-on-environment-variables-in-android-projects}
* `ANDROID_SDK_ROOT` should point to the Android SDK. In your Nix expressions, this should be
`${androidComposition.androidsdk}/libexec/android-sdk`. Note that `ANDROID_HOME` is deprecated,
but if you rely on tools that need it, you can export it too.
@ -296,8 +301,8 @@ This shell.nix includes a shell hook that overwrites local.properties with the c
sdk.dir and ndk.dir values. This will ensure that the SDK and NDK directories will
both be correct when you run Android Studio inside nix-shell.
Notes on improving build.gradle compatibility
---------------------------------------------
## Notes on improving build.gradle compatibility {#notes-on-improving-build.gradle-compatibility}
Ensure that your buildToolsVersion and ndkVersion match what is declared in androidenv.
If you are using cmake, make sure its declared version is correct too.
@ -317,8 +322,8 @@ android {
```
Querying the available versions of each plugin
----------------------------------------------
## Querying the available versions of each plugin {#querying-the-available-versions-of-each-plugin}
repo.json provides all the options in one file now.
A shell script in the `pkgs/development/mobile/androidenv/` subdirectory can be used to retrieve all
@ -330,8 +335,8 @@ possible options:
The above command-line instruction queries all package versions in repo.json.
Updating the generated expressions
----------------------------------
## Updating the generated expressions {#updating-the-generated-expressions}
repo.json is generated from XML files that the Android Studio package manager uses.
To update the expressions run the `generate.sh` script that is stored in the
`pkgs/development/mobile/androidenv/` subdirectory:

@ -2,15 +2,21 @@
## 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.
## Available versions and deprecations schedule {#available-versions-and-deprecations-schedule}
### Elixir {#elixir}
nixpkgs follows the [official elixir deprecation schedule](https://hexdocs.pm/elixir/compatibility-and-deprecations.html) and keeps the last 5 released versions of Elixir available.
## 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.erlangR22`, 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.erlang22`.
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`.
@ -24,9 +30,17 @@ Many Erlang/OTP distributions available in `beam.interpreters` have versions wit
We provide a version of Rebar3, under `rebar3`. We also provide a helper to fetch Rebar3 dependencies from a lockfile under `fetchRebar3Deps`.
We also provide a version on Rebar3 with plugins included, under `rebar3WithPlugins`. This package is a function which takes two arguments: `plugins`, a list of nix derivations to include as plugins (loaded only when specified in `rebar.config`), and `globalPlugins`, which should always be loaded by rebar3. Example: `rebar3WithPlugins { globalPlugins = [beamPackages.pc]; }`.
When adding a new plugin it is important that the `packageName` attribute is the same as the atom used by rebar3 to refer to the plugin.
### 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.
There is also a `buildMix` helper, whose behavior is closer to that of `buildErlangMk` and `buildRebar3`. The primary difference is that mixRelease makes a release, while buildMix only builds the package, making it useful for libraries and other dependencies.
## How to Install BEAM Packages {#how-to-install-beam-packages}
@ -52,15 +66,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 {#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";
mixFodDeps = 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 mixFodDeps;
# 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 {#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 +228,68 @@ mkShell {
}
```
#### Building in a Shell (for Mix Projects) {#building-in-a-shell}
#### Elixir - Phoenix project {#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
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`

@ -149,7 +149,7 @@ A few notes about [Full example — `default.nix`](#ex-buildBowerComponentsDefau
## Troubleshooting {#ssec-bower2nix-troubleshooting}
### ENOCACHE errors from buildBowerComponents
### ENOCACHE errors from buildBowerComponents {#enocache-errors-from-buildbowercomponents}
This means that Bower was looking for a package version which doesn't exist in the generated `bower-packages.nix`.

@ -1,6 +1,6 @@
# Coq and coq packages {#sec-language-coq}
## Coq derivation: `coq`
## Coq derivation: `coq` {#coq-derivation-coq}
The Coq derivation is overridable through the `coq.override overrides`, where overrides is an attribute set which contains the arguments to override. We recommend overriding either of the following
@ -8,7 +8,7 @@ The Coq derivation is overridable through the `coq.override overrides`, where ov
* `customOCamlPackage` (optional, defaults to `null`, which lets Coq choose a version automatically), which can be set to any of the ocaml packages attribute of `ocaml-ng` (such as `ocaml-ng.ocamlPackages_4_10` which is the default for Coq 8.11 for example).
* `coq-version` (optional, defaults to the short version e.g. "8.10"), is a version number of the form "x.y" that indicates which Coq's version build behavior to mimic when using a source which is not a release. E.g. `coq.override { version = "d370a9d1328a4e1cdb9d02ee032f605a9d94ec7a"; coq-version = "8.10"; }`.
## Coq packages attribute sets: `coqPackages`
## Coq packages attribute sets: `coqPackages` {#coq-packages-attribute-sets-coqpackages}
The recommended way of defining a derivation for a Coq library, is to use the `coqPackages.mkCoqDerivation` function, which is essentially a specialization of `mkDerivation` taking into account most of the specifics of Coq libraries. The following attributes are supported:
@ -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`,

@ -1,10 +1,11 @@
# Crystal {#crystal}
## Building a Crystal package
## Building a Crystal package {#building-a-crystal-package}
This section uses [Mint](https://github.com/mint-lang/mint) as an example for how to build a Crystal package.
If the Crystal project has any dependencies, the first step is to get a `shards.nix` file encoding those. Get a copy of the project and go to its root directory such that its `shard.lock` file is in the current directory, then run `crystal2nix` in it
```bash
$ git clone https://github.com/mint-lang/mint
$ cd mint
@ -15,6 +16,7 @@ $ nix-shell -p crystal2nix --run crystal2nix
This should have generated a `shards.nix` file.
Next create a Nix file for your derivation and use `pkgs.crystal.buildCrystalPackage` as follows:
```nix
with import <nixpkgs> {};
crystal.buildCrystalPackage rec {

@ -0,0 +1,432 @@
# Dhall {#sec-language-dhall}
The Nixpkgs support for Dhall assumes some familiarity with Dhall's language
support for importing Dhall expressions, which is documented here:
* [`dhall-lang.org` - Installing packages](https://docs.dhall-lang.org/tutorials/Language-Tour.html#installing-packages)
## Remote imports {#ssec-dhall-remote-imports}
Nixpkgs bypasses Dhall's support for remote imports using Dhall's
semantic integrity checks. Specifically, any Dhall import can be protected by
an integrity check like:
```dhall
https://prelude.dhall-lang.org/v20.1.0/package.dhall
sha256:26b0ef498663d269e4dc6a82b0ee289ec565d683ef4c00d0ebdd25333a5a3c98
```
… and if the import is cached then the interpreter will load the import from
cache instead of fetching the URL.
Nixpkgs uses this trick to add all of a Dhall expression's dependencies into the
cache so that the Dhall interpreter never needs to resolve any remote URLs. In
fact, Nixpkgs uses a Dhall interpreter with remote imports disabled when
packaging Dhall expressions to enforce that the interpreter never resolves a
remote import. This means that Nixpkgs only supports building Dhall expressions
if all of their remote imports are protected by semantic integrity checks.
Instead of remote imports, Nixpkgs uses Nix to fetch remote Dhall code. For
example, the Prelude Dhall package uses `pkgs.fetchFromGitHub` to fetch the
`dhall-lang` repository containing the Prelude. Relying exclusively on Nix
to fetch Dhall code ensures that Dhall packages built using Nix remain pure and
also behave well when built within a sandbox.
## Packaging a Dhall expression from scratch {#ssec-dhall-packaging-expression}
We can illustrate how Nixpkgs integrates Dhall by beginning from the following
trivial Dhall expression with one dependency (the Prelude):
```dhall
-- ./true.dhall
let Prelude = https://prelude.dhall-lang.org/v20.1.0/package.dhall
in Prelude.Bool.not False
```
As written, this expression cannot be built using Nixpkgs because the
expression does not protect the Prelude import with a semantic integrity
check, so the first step is to freeze the expression using `dhall freeze`,
like this:
```bash
$ dhall freeze --inplace ./true.dhall
```
… which gives us:
```dhall
-- ./true.dhall
let Prelude =
https://prelude.dhall-lang.org/v20.1.0/package.dhall
sha256:26b0ef498663d269e4dc6a82b0ee289ec565d683ef4c00d0ebdd25333a5a3c98
in Prelude.Bool.not False
```
To package that expression, we create a `./true.nix` file containing the
following specification for the Dhall package:
```nix
# ./true.nix
{ buildDhallPackage, Prelude }:
buildDhallPackage {
name = "true";
code = ./true.dhall;
dependencies = [ Prelude ];
source = true;
}
```
… and we complete the build by incorporating that Dhall package into the
`pkgs.dhallPackages` hierarchy using an overlay, like this:
```nix
# ./example.nix
let
nixpkgs = builtins.fetchTarball {
url = "https://github.com/NixOS/nixpkgs/archive/94b2848559b12a8ed1fe433084686b2a81123c99.tar.gz";
sha256 = "1pbl4c2dsaz2lximgd31m96jwbps6apn3anx8cvvhk1gl9rkg107";
};
dhallOverlay = self: super: {
true = self.callPackage ./true.nix { };
};
overlay = self: super: {
dhallPackages = super.dhallPackages.override (old: {
overrides =
self.lib.composeExtensions (old.overrides or (_: _: {})) dhallOverlay;
});
};
pkgs = import nixpkgs { config = {}; overlays = [ overlay ]; };
in
pkgs
```
… which we can then build using this command:
```bash
$ nix build --file ./example.nix dhallPackages.true
```
## Contents of a Dhall package {#ssec-dhall-package-contents}
The above package produces the following directory tree:
```bash
$ tree -a ./result
result
├── .cache
   └── dhall
   └── 122027abdeddfe8503496adeb623466caa47da5f63abd2bc6fa19f6cfcb73ecfed70
├── binary.dhall
└── source.dhall
```
… where:
* `source.dhall` contains the result of interpreting our Dhall package:
```bash
$ cat ./result/source.dhall
True
```
* The `.cache` subdirectory contains one binary cache product encoding the
same result as `source.dhall`:
```bash
$ dhall decode < ./result/.cache/dhall/122027abdeddfe8503496adeb623466caa47da5f63abd2bc6fa19f6cfcb73ecfed70
True
```
* `binary.dhall` contains a Dhall expression which handles fetching and decoding
the same cache product:
```bash
$ cat ./result/binary.dhall
missing sha256:27abdeddfe8503496adeb623466caa47da5f63abd2bc6fa19f6cfcb73ecfed70
$ cp -r ./result/.cache .cache
$ chmod -R u+w .cache
$ XDG_CACHE_HOME=.cache dhall --file ./result/binary.dhall
True
```
The `source.dhall` file is only present for packages that specify
`source = true;`. By default, Dhall packages omit the `source.dhall` in order
to conserve disk space when they are used exclusively as dependencies. For
example, if we build the Prelude package it will only contain the binary
encoding of the expression:
```bash
$ nix build --file ./example.nix dhallPackages.Prelude
$ tree -a result
result
├── .cache
   └── dhall
   └── 122026b0ef498663d269e4dc6a82b0ee289ec565d683ef4c00d0ebdd25333a5a3c98
└── binary.dhall
2 directories, 2 files
```
Typically, you only specify `source = true;` for the top-level Dhall expression
of interest (such as our example `true.nix` Dhall package). However, if you
wish to specify `source = true` for all Dhall packages, then you can amend the
Dhall overlay like this:
```nix
dhallOverrides = self: super: {
# Enable source for all Dhall packages
buildDhallPackage =
args: super.buildDhallPackage (args // { source = true; });
true = self.callPackage ./true.nix { };
};
```
… and now the Prelude will contain the fully decoded result of interpreting
the Prelude:
```bash
$ nix build --file ./example.nix dhallPackages.Prelude
$ tree -a result
result
├── .cache
   └── dhall
   └── 122026b0ef498663d269e4dc6a82b0ee289ec565d683ef4c00d0ebdd25333a5a3c98
├── binary.dhall
└── source.dhall
$ cat ./result/source.dhall
{ Bool =
{ and =
\(_ : List Bool) ->
List/fold Bool _ Bool (\(_ : Bool) -> \(_ : Bool) -> _@1 && _) True
, build = \(_ : Type -> _ -> _@1 -> _@2) -> _ Bool True False
, even =
\(_ : List Bool) ->
List/fold Bool _ Bool (\(_ : Bool) -> \(_ : Bool) -> _@1 == _) True
, fold =
\(_ : Bool) ->
```
## Packaging functions {#ssec-dhall-packaging-functions}
We already saw an example of using `buildDhallPackage` to create a Dhall
package from a single file, but most Dhall packages consist of more than one
file and there are two derived utilities that you may find more useful when
packaging multiple files:
* `buildDhallDirectoryPackage` - build a Dhall package from a local directory
* `buildDhallGitHubPackage` - build a Dhall package from a GitHub repository
The `buildDhallPackage` is the lowest-level function and accepts the following
arguments:
* `name`: The name of the derivation
* `dependencies`: Dhall dependencies to build and cache ahead of time
* `code`: The top-level expression to build for this package
Note that the `code` field accepts an arbitrary Dhall expression. You're
not limited to just a file.
* `source`: Set to `true` to include the decoded result as `source.dhall` in the
build product, at the expense of requiring more disk space
* `documentationRoot`: Set to the root directory of the package if you want
`dhall-docs` to generate documentation underneath the `docs` subdirectory of
the build product
The `buildDhallDirectoryPackage` is a higher-level function implemented in terms
of `buildDhallPackage` that accepts the following arguments:
* `name`: Same as `buildDhallPackage`
* `dependencies`: Same as `buildDhallPackage`
* `source`: Same as `buildDhallPackage`
* `src`: The directory containing Dhall code that you want to turn into a Dhall
package
* `file`: The top-level file (`package.dhall` by default) that is the entrypoint
to the rest of the package
* `document`: Set to `true` to generate documentation for the package
The `buildDhallGitHubPackage` is another higher-level function implemented in
terms of `buildDhallPackage` that accepts the following arguments:
* `name`: Same as `buildDhallPackage`
* `dependencies`: Same as `buildDhallPackage`
* `source`: Same as `buildDhallPackage`
* `owner`: The owner of the repository
* `repo`: The repository name
* `rev`: The desired revision (or branch, or tag)
* `directory`: The subdirectory of the Git repository to package (if a
directory other than the root of the repository)
* `file`: The top-level file (`${directory}/package.dhall` by default) that is
the entrypoint to the rest of the package
* `document`: Set to `true` to generate documentation for the package
Additionally, `buildDhallGitHubPackage` accepts the same arguments as
`fetchFromGitHub`, such as `sha256` or `fetchSubmodules`.
## `dhall-to-nixpkgs` {#ssec-dhall-dhall-to-nixpkgs}
You can use the `dhall-to-nixpkgs` command-line utility to automate
packaging Dhall code. For example:
```bash
$ nix-env --install --attr haskellPackages.dhall-nixpkgs
$ nix-env --install --attr nix-prefetch-git # Used by dhall-to-nixpkgs
$ dhall-to-nixpkgs github https://github.com/Gabriel439/dhall-semver.git
{ buildDhallGitHubPackage, Prelude }:
buildDhallGitHubPackage {
name = "dhall-semver";
githubBase = "github.com";
owner = "Gabriel439";
repo = "dhall-semver";
rev = "2d44ae605302ce5dc6c657a1216887fbb96392a4";
fetchSubmodules = false;
sha256 = "0y8shvp8srzbjjpmnsvz9c12ciihnx1szs0yzyi9ashmrjvd0jcz";
directory = "";
file = "package.dhall";
source = false;
document = false;
dependencies = [ (Prelude.overridePackage { file = "package.dhall"; }) ];
}
```
The utility takes care of automatically detecting remote imports and converting
them to package dependencies. You can also use the utility on local
Dhall directories, too:
```bash
$ dhall-to-nixpkgs directory ~/proj/dhall-semver
{ buildDhallDirectoryPackage, Prelude }:
buildDhallDirectoryPackage {
name = "proj";
src = /Users/gabriel/proj/dhall-semver;
file = "package.dhall";
source = false;
document = false;
dependencies = [ (Prelude.overridePackage { file = "package.dhall"; }) ];
}
```
## Overriding dependency versions {#ssec-dhall-overriding-dependency-versions}
Suppose that we change our `true.dhall` example expression to depend on an older
version of the Prelude (19.0.0):
```dhall
-- ./true.dhall
let Prelude =
https://prelude.dhall-lang.org/v19.0.0/package.dhall
sha256:eb693342eb769f782174157eba9b5924cf8ac6793897fc36a31ccbd6f56dafe2
in Prelude.Bool.not False
```
If we try to rebuild that expression the build will fail:
```
$ nix build --file ./example.nix dhallPackages.true
builder for '/nix/store/0f1hla7ff1wiaqyk1r2ky4wnhnw114fi-true.drv' failed with exit code 1; last 10 log lines:
Dhall was compiled without the 'with-http' flag.
The requested URL was: https://prelude.dhall-lang.org/v19.0.0/package.dhall
4│ https://prelude.dhall-lang.org/v19.0.0/package.dhall
5│ sha256:eb693342eb769f782174157eba9b5924cf8ac6793897fc36a31ccbd6f56dafe2
/nix/store/rsab4y99h14912h4zplqx2iizr5n4rc2-true.dhall:4:7
[1 built (1 failed), 0.0 MiB DL]
error: build of '/nix/store/0f1hla7ff1wiaqyk1r2ky4wnhnw114fi-true.drv' failed
```
… because the default Prelude selected by Nixpkgs revision
`94b2848559b12a8ed1fe433084686b2a81123c99is` is version 20.1.0, which doesn't
have the same integrity check as version 19.0.0. This means that version
19.0.0 is not cached and the interpreter is not allowed to fall back to
importing the URL.
However, we can override the default Prelude version by using `dhall-to-nixpkgs`
to create a Dhall package for our desired Prelude:
```bash
$ dhall-to-nixpkgs github https://github.com/dhall-lang/dhall-lang.git \
--name Prelude \
--directory Prelude \
--rev v19.0.0 \
> Prelude.nix
```
… and then referencing that package in our Dhall overlay, by either overriding
the Prelude globally for all packages, like this:
```bash
dhallOverrides = self: super: {
true = self.callPackage ./true.nix { };
Prelude = self.callPackage ./Prelude.nix { };
};
```
… or selectively overriding the Prelude dependency for just the `true` package,
like this:
```bash
dhallOverrides = self: super: {
true = self.callPackage ./true.nix {
Prelude = self.callPackage ./Prelude.nix { };
};
};
```
## Overrides {#ssec-dhall-overrides}
You can override any of the arguments to `buildDhallGitHubPackage` or
`buildDhallDirectoryPackage` using the `overridePackage` attribute of a package.
For example, suppose we wanted to selectively enable `source = true` just for the Prelude. We can do that like this:
```nix
dhallOverrides = self: super: {
Prelude = super.Prelude.overridePackage { source = true; };
};
```
[semantic-integrity-checks]: https://docs.dhall-lang.org/tutorials/Language-Tour.html#installing-packages

@ -1,31 +1,31 @@
# Dotnet
# Dotnet {#dotnet}
## Local Development Workflow
## Local Development Workflow {#local-development-workflow}
For local development, it's recommended to use nix-shell to create a dotnet environment:
```
```nix
# shell.nix
with import <nixpkgs> {};
mkShell {
name = "dotnet-env";
buildInputs = [
packages = [
dotnet-sdk_3
];
}
```
### Using many sdks in a workflow
### Using many sdks in a workflow {#using-many-sdks-in-a-workflow}
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 {
name = "dotnet-env";
buildInputs = [
packages = [
(with dotnetCorePackages; combinePackages [
sdk_3_1
sdk_3_0
@ -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:
```
```ShellSession
$ dotnet --info
.NET Core SDK (reflecting any global.json):
Version: 3.1.101
@ -60,15 +60,15 @@ $ dotnet --info
Microsoft.NETCore.App 3.1.1 [/nix/store/iiv98i2jdi226dgh4jzkkj2ww7f8jgpd-dotnet-core-combined/shared/Microsoft.NETCore.App]
```
## dotnet-sdk vs dotnetCorePackages.sdk
## dotnet-sdk vs dotnetCorePackages.sdk {#dotnet-sdk-vs-dotnetcorepackages.sdk}
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 {#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.
## Packaging a Dotnet Application
## Packaging a Dotnet Application {#packaging-a-dotnet-application}
Ideally, we would like to build against the sdk, then only have the dotnet runtime available in the runtime closure.

@ -27,16 +27,14 @@ Modes of use of `emscripten`:
* dev-shell for zlib implementation hacking:
* `nix-shell -A emscriptenPackages.zlib`
## Imperative usage
## Imperative usage {#imperative-usage}
A few things to note:
* `export EMCC_DEBUG=2` is nice for debugging
* `~/.emscripten`, the build artifact cache sometimes creates issues and needs to be removed from time to time
## Declarative usage
## Declarative usage {#declarative-usage}
Let's see two different examples from `pkgs/top-level/emscripten-packages.nix`:
@ -50,7 +48,7 @@ A special requirement of the `pkgs.buildEmscriptenPackage` is the `doCheck = tru
* Use `export EMCC_DEBUG=2` from within a emscriptenPackage's `phase` to get more detailed debug output what is going wrong.
* ~/.emscripten cache is requiring us to set `HOME=$TMPDIR` in individual phases. This makes compilation slower but also makes it more deterministic.
### Usage 1: pkgs.zlib.override
### Usage 1: pkgs.zlib.override {#usage-1-pkgs.zlib.override}
This example uses `zlib` from nixpkgs but instead of compiling **C** to **ELF** it compiles **C** to **JS** since we were using `pkgs.zlib.override` and changed stdenv to `pkgs.emscriptenStdenv`. A few adaptions and hacks were set in place to make it working. One advantage is that when `pkgs.zlib` is updated, it will automatically update this package as well. However, this can also be the downside...
@ -110,7 +108,7 @@ See the `zlib` example:
'';
});
### Usage 2: pkgs.buildEmscriptenPackage
### Usage 2: pkgs.buildEmscriptenPackage {#usage-2-pkgs.buildemscriptenpackage}
This `xmlmirror` example features a emscriptenPackage which is defined completely from this context and no `pkgs.zlib.override` is used.
@ -165,7 +163,7 @@ This `xmlmirror` example features a emscriptenPackage which is defined completel
'';
};
### Declarative debugging
### Declarative debugging {#declarative-debugging}
Use `nix-shell -I nixpkgs=/some/dir/nixpkgs -A emscriptenPackages.libz` and from there you can go trough the individual steps. This makes it easy to build a good `unit test` or list the files of the project.
@ -177,7 +175,7 @@ Use `nix-shell -I nixpkgs=/some/dir/nixpkgs -A emscriptenPackages.libz` and from
6. `buildPhase`
7. ... happy hacking...
## Summary
## Summary {#summary}
Using this toolchain makes it easy to leverage `nix` from NixOS, MacOSX or even Windows (WSL+ubuntu+nix). This toolchain is reproducible, behaves like the rest of the packages from nixpkgs and contains a set of well working examples to learn and adapt from.

@ -8,12 +8,30 @@ Programs in the GNOME universe are written in various languages but they all use
[GSettings](https://developer.gnome.org/gio/stable/GSettings.html) API is often used for storing settings. GSettings schemas are required, to know the type and other metadata of the stored values. GLib looks for `glib-2.0/schemas/gschemas.compiled` files inside the directories of `XDG_DATA_DIRS`.
On Linux, GSettings API is implemented using [dconf](https://wiki.gnome.org/Projects/dconf) backend. You will need to add `dconf` GIO module to `GIO_EXTRA_MODULES` variable, otherwise the `memory` backend will be used and the saved settings will not be persistent.
On Linux, GSettings API is implemented using [dconf](https://wiki.gnome.org/Projects/dconf) backend. You will need to add `dconf` [GIO module](#ssec-gnome-gio-modules) to `GIO_EXTRA_MODULES` variable, otherwise the `memory` backend will be used and the saved settings will not be persistent.
Last you will need the dconf database D-Bus service itself. You can enable it using `programs.dconf.enable`.
Some applications will also require `gsettings-desktop-schemas` for things like reading proxy configuration or user interface customization. This dependency is often not mentioned by upstream, you should grep for `org.gnome.desktop` and `org.gnome.system` to see if the schemas are needed.
### GIO modules {#ssec-gnome-gio-modules}
GLib’s [GIO](https://developer.gnome.org/gio/stable/ch01.html) library supports several [extension points](https://developer.gnome.org/gio/stable/extending-gio.html). Notably, they allow:
* implementing settings backends (already [mentioned](#ssec-gnome-settings))
* adding TLS support
* proxy settings
* virtual file systems
The modules are typically installed to `lib/gio/modules/` directory of a package and you need to add them to `GIO_EXTRA_MODULES` if you need any of those features.
In particular, we recommend:
* adding `dconf.lib` for any software on Linux that reads [GSettings](#ssec-gnome-settings) (even transitivily through e.g. GTK’s file manager)
* adding `glib-networking` for any software that accesses network using GIO or libsoup – glib-networking contains a module that implements TLS support and loads system-wide proxy settings
To allow software to use various virtual file systems, `gvfs` package can be also added. But that is usually an optional feature so we typically use `gvfs` from the system (e.g. installed globally using NixOS module).
### GdkPixbuf loaders {#ssec-gnome-gdk-pixbuf-loaders}
GTK applications typically use [GdkPixbuf](https://developer.gnome.org/gdk-pixbuf/stable/) to load images. But `gdk-pixbuf` package only supports basic bitmap formats like JPEG, PNG or TIFF, requiring to use third-party loader modules for other formats. This is especially painful since GTK itself includes SVG icons, which cannot be rendered without a loader provided by `librsvg`.
@ -68,7 +86,7 @@ preFixup = ''
Fortunately, there is [`wrapGAppsHook`]{#ssec-gnome-hooks-wrapgappshook}. It works in conjunction with other setup hooks that populate environment variables, and it will then wrap all executables in `bin` and `libexec` directories using said variables.
For convenience, it also adds `dconf.lib` for a GIO module implementing a GSettings backend using `dconf`, `gtk3` for GSettings schemas, and `librsvg` for GdkPixbuf loader to the closure. In case you are packaging a program without a graphical interface, you might want to use [`wrapGAppsNoGuiHook`]{#ssec-gnome-hooks-wrapgappsnoguihook}, which runs the same script as `wrapGAppsHook` but does not bring `gtk3` and `librsvg` into the closure.
For convenience, it also adds `dconf.lib` for a GIO module implementing a GSettings backend using `dconf`, `gtk3` for GSettings schemas, and `librsvg` for GdkPixbuf loader to the closure. There is also [`wrapGAppsHook4`]{#ssec-gnome-hooks-wrapgappshook4}, which replaces GTK 3 with GTK 4. And in case you are packaging a program without a graphical interface, you might want to use [`wrapGAppsNoGuiHook`]{#ssec-gnome-hooks-wrapgappsnoguihook}, which runs the same script as `wrapGAppsHook` but does not bring `gtk3` and `librsvg` into the closure.
- `wrapGAppsHook` itself will add the package’s `share` directory to `XDG_DATA_DIRS`.
@ -84,11 +102,11 @@ For convenience, it also adds `dconf.lib` for a GIO module implementing a GSetti
- []{#ssec-gnome-hooks-gobject-introspection} `gobject-introspection` setup hook populates `GI_TYPELIB_PATH` variable with `lib/girepository-1.0` directories of dependencies, which is then added to wrapper by `wrapGAppsHook`. It also adds `share` directories of dependencies to `XDG_DATA_DIRS`, which is intended to promote GIR files but it also [pollutes the closures](https://github.com/NixOS/nixpkgs/issues/32790) of packages using `wrapGAppsHook`.
::: warning
::: {.warning}
The setup hook [currently](https://github.com/NixOS/nixpkgs/issues/56943) does not work in expressions with `strictDeps` enabled, like Python packages. In those cases, you will need to disable it with `strictDeps = false;`.
:::
- []{#ssec-gnome-hooks-gst-grl-plugins} Setup hooks of `gst_all_1.gstreamer` and `gnome3.grilo` will populate the `GST_PLUGIN_SYSTEM_PATH_1_0` and `GRL_PLUGIN_PATH` variables, respectively, which will then be added to the wrapper by `wrapGAppsHook`.
- []{#ssec-gnome-hooks-gst-grl-plugins} Setup hooks of `gst_all_1.gstreamer` and `grilo` will populate the `GST_PLUGIN_SYSTEM_PATH_1_0` and `GRL_PLUGIN_PATH` variables, respectively, which will then be added to the wrapper by `wrapGAppsHook`.
You can also pass additional arguments to `makeWrapper` using `gappsWrapperArgs` in `preFixup` hook:
@ -105,7 +123,7 @@ preFixup = ''
## Updating GNOME packages {#ssec-gnome-updating}
Most GNOME package offer [`updateScript`](#var-passthru-updateScript), it is therefore possible to update to latest source tarball by running `nix-shell maintainers/scripts/update.nix --argstr package gnome3.nautilus` or even en masse with `nix-shell maintainers/scripts/update.nix --argstr path gnome3`. Read the package’s `NEWS` file to see what changed.
Most GNOME package offer [`updateScript`](#var-passthru-updateScript), it is therefore possible to update to latest source tarball by running `nix-shell maintainers/scripts/update.nix --argstr package gnome.nautilus` or even en masse with `nix-shell maintainers/scripts/update.nix --argstr path gnome`. Read the package’s `NEWS` file to see what changed.
## Frequently encountered issues {#ssec-gnome-common-issues}

@ -44,7 +44,7 @@ pet = buildGoModule rec {
The function `buildGoPackage` builds legacy Go programs, not supporting Go modules.
### Example for `buildGoPackage`
### Example for `buildGoPackage` {#example-for-buildgopackage}
In the following is an example expression using buildGoPackage, the following arguments are of special significance to the function:
@ -114,21 +114,24 @@ Both `buildGoModule` and `buildGoPackage` can be tweaked to behave slightly diff
### `buildFlagsArray` and `buildFlags`: {#ex-goBuildFlags-noarray}
These attributes set build flags supported by `go build`. We recommend using `buildFlagsArray`. The most common use case of these attributes is to make the resulting executable aware of its own version. For example:
These attributes set build flags supported by `go build`. We recommend using `buildFlagsArray`.
```nix
buildFlagsArray = [
# Note: single quotes are not needed.
"-ldflags=-X main.Version=${version} -X main.Commit=${version}"
"-tags=release"
];
```
### `ldflags` {#var-go-ldflags}
Arguments to pass to the Go linker tool via the `-ldflags` argument of `go build`. The most common use case for this argument is to make the resulting executable aware of its own version. For example:
```nix
buildFlagsArray = ''
-ldflags=
-X main.Version=${version}
-X main.Commit=${version}
'';
ldflags = [
"-s" "-w"
"-X main.Version=${version}"
"-X main.Commit=${version}"
];
```
### `deleteVendor` {#var-go-deleteVendor}
@ -137,4 +140,4 @@ Removes the pre-existing vendor directory. This should only be used if the depen
### `subPackages` {#var-go-subPackages}
Limits the builder from building child packages that have not been listed. If <varname>subPackages</varname> is not specified, all child packages will be built.
Limits the builder from building child packages that have not been listed. If `subPackages` is not specified, all child packages will be built.

@ -0,0 +1,31 @@
# Hy {#sec-language-hy}
## Installation {#ssec-hy-installation}
### Installation without packages {#installation-without-packages}
You can install `hy` via nix-env or by adding it to `configuration.nix` by reffering to it as a `hy` attribute. This kind of installation adds `hy` to your environment and it succesfully works with `python3`.
::: {.caution}
Packages that are installed with your python derivation, are not accesible by `hy` this way.
:::
### Installation with packages {#installation-with-packages}
Creating `hy` derivation with custom `python` packages is really simple and similar to the way that python does it. Attribute `hy` provides function `withPackages` that creates custom `hy` derivation with specified packages.
For example if you want to create shell with `matplotlib` and `numpy`, you can do it like so:
```ShellSession
$ nix-shell -p "hy.withPackages (ps: with ps; [ numpy matplotlib ])"
```
Or if you want to extend your `configuration.nix`:
```nix
{ # ...
environment.systemPackages = with pkgs; [
(hy.withPackages (py-packages: with py-packages; [ numpy matplotlib ]))
];
}
```

@ -1,10 +1,10 @@
# Idris {#idris}
## Installing Idris
## Installing Idris {#installing-idris}
The easiest way to get a working idris version is to install the `idris` attribute:
```
```ShellSession
$ # On NixOS
$ nix-env -i nixos.idris
$ # On non-NixOS
@ -21,7 +21,7 @@ self: super: {
And then:
```
```ShellSession
$ # On NixOS
$ nix-env -iA nixos.myIdris
$ # On non-NixOS
@ -29,7 +29,8 @@ $ nix-env -iA nixpkgs.myIdris
```
To see all available Idris packages:
```
```ShellSession
$ # On NixOS
$ nix-env -qaPA nixos.idrisPackages
$ # On non-NixOS
@ -37,22 +38,23 @@ $ nix-env -qaPA nixpkgs.idrisPackages
```
Similarly, entering a `nix-shell`:
```
```ShellSession
$ nix-shell -p 'idrisPackages.with-packages (with idrisPackages; [ contrib pruviloj ])'
```
## Starting Idris with library support
## Starting Idris with library support {#starting-idris-with-library-support}
To have access to these libraries in idris, call it with an argument `-p <library name>` for each library:
```
```ShellSession
$ 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`:
```
```ShellSession
$ idris --listlibs
00prelude-idx.ibc
pruviloj
@ -64,7 +66,7 @@ prelude
00contrib-idx.ibc
```
## Building an Idris project with Nix
## Building an Idris project with Nix {#building-an-idris-project-with-nix}
As an example of how a Nix expression for an Idris package can be created, here is the one for `idrisPackages.yaml`:
@ -105,7 +107,7 @@ build-idris-package {
Assuming this file is saved as `yaml.nix`, it's buildable using
```
```ShellSession
$ nix-build -E '(import <nixpkgs> {}).idrisPackages.callPackage ./yaml.nix {}'
```
@ -121,11 +123,11 @@ with import <nixpkgs> {};
in another file (say `default.nix`) to be able to build it with
```
```ShellSession
$ nix-build -A yaml
```
## Passing options to `idris` commands
## Passing options to `idris` commands {#passing-options-to-idris-commands}
The `build-idris-package` function provides also optional input values to set additional options for the used `idris` commands.
@ -133,7 +135,7 @@ Specifically, you can set `idrisBuildOptions`, `idrisTestOptions`, `idrisInstall
For example you could set
```
```nix
build-idris-package {
idrisBuildOptions = [ "--log" "1" "--verbose" ]

@ -11,10 +11,12 @@
<xi:include href="bower.section.xml" />
<xi:include href="coq.section.xml" />
<xi:include href="crystal.section.xml" />
<xi:include href="dhall.section.xml" />
<xi:include href="emscripten.section.xml" />
<xi:include href="gnome.section.xml" />
<xi:include href="go.section.xml" />
<xi:include href="haskell.section.xml" />
<xi:include href="hy.section.xml" />
<xi:include href="idris.section.xml" />
<xi:include href="ios.section.xml" />
<xi:include href="java.section.xml" />

@ -20,8 +20,8 @@ Hydra.
The Xcode build environment implements a number of features.
Deploying a proxy component wrapper exposing Xcode
--------------------------------------------------
## Deploying a proxy component wrapper exposing Xcode {#deploying-a-proxy-component-wrapper-exposing-xcode}
The first use case is deploying a Nix package that provides symlinks to the Xcode
installation on the host system. This package can be used as a build input to
any build function implemented in the Nix expression language that requires
@ -55,8 +55,8 @@ lrwxr-xr-x 1 sander staff 61 1 jan 1970 xcodebuild -> /Applications/Xcode.a
lrwxr-xr-x 1 sander staff 14 1 jan 1970 xcrun -> /usr/bin/xcrun
```
Building an iOS application
---------------------------
## Building an iOS application {#building-an-ios-application}
We can build an iOS app executable for the simulator, or an IPA/xcarchive file
for release purposes, e.g. ad-hoc, enterprise or store installations, by
executing the `xcodeenv.buildApp {}` function:
@ -99,6 +99,7 @@ xcodeenv.buildApp {
```
The above function takes a variety of parameters:
* The `name` and `src` parameters are mandatory and specify the name of the app
and the location where the source code resides
* `sdkVersion` specifies which version of the iOS SDK to use.
@ -151,8 +152,8 @@ the `xcodeenv.composeXcodeWrapper {}` function takes. For example, the
`xcodeBaseDir` parameter can be overridden to refer to a different Xcode
version.
Spawning simulator instances
----------------------------
## Spawning simulator instances {#spawning-simulator-instances}
In addition to building iOS apps, we can also automatically spawn simulator
instances:
@ -213,8 +214,8 @@ xcode.simulateApp {
By providing the result of an `xcode.buildApp {}` function and configuring the
app bundle id, the app gets deployed automatically and started.
Troubleshooting
---------------
## Troubleshooting {#troubleshooting}
In some rare cases, it may happen that after a failure, changes are not picked
up. Most likely, this is caused by a derived data cache that Xcode maintains.
To wipe it you can run:

@ -1,8 +1,8 @@
# User's Guide to Lua Infrastructure {#users-guide-to-lua-infrastructure}
# Users Guide to Lua Infrastructure {#users-guide-to-lua-infrastructure}
## Using Lua
## Using Lua {#using-lua}
### Overview of Lua
### Overview of Lua {#overview-of-lua}
Several versions of the Lua interpreter are available: luajit, lua 5.1, 5.2, 5.3.
The attribute `lua` refers to the default interpreter, it is also possible to refer to specific versions, e.g. `lua5_2` refers to Lua 5.2.
@ -17,27 +17,31 @@ The main package set contains aliases to these package sets, e.g.
`luaPackages` refers to `lua5_1.pkgs` and `lua52Packages` to
`lua5_2.pkgs`.
### Installing Lua and packages
### Installing Lua and packages {#installing-lua-and-packages}
#### Lua environment defined in separate `.nix` file
#### Lua environment defined in separate `.nix` file {#lua-environment-defined-in-separate-.nix-file}
Create a file, e.g. `build.nix`, with the following expression
```nix
with import <nixpkgs> {};
lua5_2.withPackages (ps: with ps; [ busted luafilesystem ])
```
and install it in your profile with
```shell
nix-env -if build.nix
```
Now you can use the Lua interpreter, as well as the extra packages (`busted`,
`luafilesystem`) that you added to the environment.
#### Lua environment defined in `~/.config/nixpkgs/config.nix`
#### Lua environment defined in `~/.config/nixpkgs/config.nix` {#lua-environment-defined-in-.confignixpkgsconfig.nix}
If you prefer to, you could also add the environment as a package override to the Nixpkgs set, e.g.
using `config.nix`,
```nix
{ # ...
@ -46,14 +50,16 @@ using `config.nix`,
};
}
```
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`
#### Lua environment defined in `/etc/nixos/configuration.nix` {#lua-environment-defined-in-etcnixosconfiguration.nix}
For the sake of completeness, here's another example how to install the environment system-wide.
@ -66,7 +72,7 @@ For the sake of completeness, here's another example how to install the environm
}
```
### How to override a Lua package using overlays?
### How to override a Lua package using overlays? {#how-to-override-a-lua-package-using-overlays}
Use the following overlay template:
@ -87,18 +93,22 @@ final: prev:
}
```
### Temporary Lua environment with `nix-shell`
### Temporary Lua environment with `nix-shell` {#temporary-lua-environment-with-nix-shell}
There are two methods for loading a shell with Lua packages. The first and recommended method
is to create an environment with `lua.buildEnv` or `lua.withPackages` and load that. E.g.
```sh
$ nix-shell -p 'lua.withPackages(ps: with ps; [ busted luafilesystem ])'
```
opens a shell from which you can launch the interpreter
```sh
[nix-shell:~] lua
```
The other method, which is not recommended, does not create an environment and requires you to list the packages directly,
```sh
@ -108,7 +118,7 @@ Again, it is possible to launch the interpreter from the shell.
The Lua interpreter has the attribute `pkgs` which contains all Lua libraries for that specific interpreter.
## Developing with Lua
## Developing with Lua {#developing-with-lua}
Now that you know how to get a working Lua environment with Nix, it is time
to go forward and start actually developing with Lua. There are two ways to
@ -116,7 +126,7 @@ package lua software, either it is on luarocks and most of it can be taken care
of by the luarocks2nix converter or the packaging has to be done manually.
Let's present the luarocks way first and the manual one in a second time.
### Packaging a library on luarocks
### Packaging a library on luarocks {#packaging-a-library-on-luarocks}
[Luarocks.org](www.luarocks.org) is the main repository of lua packages.
The site proposes two types of packages, the rockspec and the src.rock
@ -129,16 +139,17 @@ 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:
`luarocks make --deps-mode=none --tree $out`
#### Packaging a library manually
#### Packaging a library manually {#packaging-a-library-manually}
You can develop your package as you usually would, just don't forget to wrap it
within a `toLuaModule` call, for instance
```nix
mynewlib = toLuaModule ( stdenv.mkDerivation { ... });
```
@ -146,16 +157,15 @@ mynewlib = toLuaModule ( stdenv.mkDerivation { ... });
There is also the `buildLuaPackage` function that can be used when lua modules
are not packaged for luarocks. You can see a few examples at `pkgs/top-level/lua-packages.nix`.
## Lua Reference
## Lua Reference {#lua-reference}
### Lua interpreters
### Lua interpreters {#lua-interpreters}
Versions 5.1, 5.2 and 5.3 of the lua interpreter are available as
respectively `lua5_1`, `lua5_2` and `lua5_3`. Luajit is available too.
The Nix expressions for the interpreters can be found in `pkgs/development/interpreters/lua-5`.
#### Attributes on lua interpreters packages
#### Attributes on lua interpreters packages {#attributes-on-lua-interpreters-packages}
Each interpreter has the following attributes:
@ -164,8 +174,7 @@ Each interpreter has the following attributes:
- `withPackages`. Simpler interface to `buildEnv`.
- `pkgs`. Set of Lua packages for that specific interpreter. The package set can be modified by overriding the interpreter and passing `packageOverrides`.
#### `buildLuarocksPackage` function
#### `buildLuarocksPackage` function {#buildluarockspackage-function}
The `buildLuarocksPackage` function is implemented in `pkgs/development/interpreters/lua-5/build-lua-package.nix`
The following is an example:
@ -205,16 +214,17 @@ install the package
By default `meta.platforms` is set to the same value as the interpreter unless overridden otherwise.
#### `buildLuaApplication` function
#### `buildLuaApplication` function {#buildluaapplication-function}
The `buildLuaApplication` function is practically the same as `buildLuaPackage`.
The difference is that `buildLuaPackage` by default prefixes the names of the packages with the version of the interpreter.
Because with an application we're not interested in multiple version the prefix is dropped.
#### lua.withPackages function
#### lua.withPackages function {#lua.withpackages-function}
The `lua.withPackages` takes a function as an argument that is passed the set of lua packages and returns the list of packages to be included in the environment.
Using the `withPackages` function, the previous example for the luafilesystem environment can be written like this:
```nix
with import <nixpkgs> {};
@ -223,6 +233,7 @@ lua.withPackages (ps: [ps.luafilesystem])
`withPackages` passes the correct package set for the specific interpreter version as an argument to the function. In the above example, `ps` equals `luaPackages`.
But you can also easily switch to using `lua5_2`:
```nix
with import <nixpkgs> {};
@ -231,13 +242,12 @@ lua5_2.withPackages (ps: [ps.lua])
Now, `ps` is set to `lua52Packages`, matching the version of the interpreter.
### Possible Todos
### Possible Todos {#possible-todos}
* export/use version specific variables such as `LUA_PATH_5_2`/`LUAROCKS_CONFIG_5_2`
* let luarocks check for dependencies via exporting the different rocktrees in temporary config
### Lua Contributing guidelines
### Lua Contributing guidelines {#lua-contributing-guidelines}
Following rules should be respected:

@ -43,9 +43,9 @@ public class Main {
You find this demo project at https://github.com/fzakaria/nixos-maven-example
## Solving for dependencies
## Solving for dependencies {#solving-for-dependencies}
### buildMaven with NixOS/mvn2nix-maven-plugin
### buildMaven with NixOS/mvn2nix-maven-plugin {#buildmaven-with-nixosmvn2nix-maven-plugin}
> ⚠ Although `buildMaven` is the "blessed" way within nixpkgs, as of 2020, it hasn't seen much activity in quite a while.
@ -82,6 +82,7 @@ This file is then given to the `buildMaven` function, and it returns 2 attribute
A simple derivation that runs through `mvn compile` & `mvn package` to build the JAR. You may use this as inspiration for more complicated derivations.
Here is an [example](https://github.com/fzakaria/nixos-maven-example/blob/main/build-maven-repository.nix) of building the Maven repository
```nix
{ pkgs ? import <nixpkgs> { } }:
with pkgs;
@ -103,7 +104,8 @@ The benefit over the _double invocation_ as we will see below, is that the _/nix
   └── 4.1.3
   ├── avalon-framework-4.1.3.jar -> /nix/store/iv5fp3955w3nq28ff9xfz86wvxbiw6n9-avalon-framework-4.1.3.jar
```
### Double Invocation
### Double Invocation {#double-invocation}
> ⚠ This pattern is the simplest but may cause unnecessary rebuilds due to the output hash changing.
@ -163,7 +165,7 @@ The build will fail, and tell you the expected `outputHash` to place. When you'v
If your package uses _SNAPSHOT_ dependencies or _version ranges_; there is a strong likelihood that over-time your output hash will change since the resolved dependencies may change. Hence this method is less recommended then using `buildMaven`.
## Building a JAR
## Building a JAR {#building-a-jar}
Regardless of which strategy is chosen above, the step to build the derivation is the same.
@ -201,7 +203,7 @@ in stdenv.mkDerivation rec {
2 directories, 1 file
```
## Runnable JAR
## Runnable JAR {#runnable-jar}
The previous example builds a `jar` file but that's not a file one can run.
@ -213,7 +215,7 @@ We will use the same repository we built above (either _double invocation_ or _b
The following two methods are more suited to Nix then building an [UberJar](https://imagej.net/Uber-JAR) which may be the more traditional approach.
### CLASSPATH
### CLASSPATH {#classpath}
> This is ideal if you are providing a derivation for _nixpkgs_ and don't want to patch the project's `pom.xml`.
@ -252,11 +254,12 @@ in stdenv.mkDerivation rec {
}
```
### MANIFEST file via Maven Plugin
### MANIFEST file via Maven Plugin {#manifest-file-via-maven-plugin}
> This is ideal if you are the project owner and want to change your `pom.xml` to set the CLASSPATH within it.
Augment the `pom.xml` to create a JAR with the following manifest:
```xml
<build>
<plugins>

@ -4,60 +4,83 @@ OCaml libraries should be installed in `$(out)/lib/ocaml/${ocaml.version}/site-l
Given that most of the OCaml ecosystem is now built with dune, nixpkgs includes a convenience build support function called `buildDunePackage` that will build an OCaml package using dune, OCaml and findlib and any additional dependencies provided as `buildInputs` or `propagatedBuildInputs`.
Here is a simple package example. It defines an (optional) attribute `minimumOCamlVersion` that will be used to throw a descriptive evaluation error if building with an older OCaml is attempted. It uses the `fetchFromGitHub` fetcher to get its source. It sets the `doCheck` (optional) attribute to `true` which means that tests will be run with `dune runtest -p angstrom` after the build (`dune build -p angstrom`) is complete. It uses `alcotest` as a build input (because it is needed to run the tests) and `bigstringaf` and `result` as propagated build inputs (thus they will also be available to libraries depending on this library). The library will be installed using the `angstrom.install` file that dune generates.
Here is a simple package example.
- It defines an (optional) attribute `minimalOCamlVersion` that will be used to
throw a descriptive evaluation error if building with an older OCaml is
attempted.
- It uses the `fetchFromGitHub` fetcher to get its source.
- `useDune2 = true` ensures that the latest version of Dune is used for the
build (this may become the default value in a future release).
- It sets the optional `doCheck` attribute such that tests will be run with
`dune runtest -p angstrom` after the build (`dune build -p angstrom`) is
complete, but only if the Ocaml version is at at least `"4.05"`.
- It uses the package `ocaml-syntax-shims` as a build input, `alcotest` and
`ppx_let` as check inputs (because they are needed to run the tests), and
`bigstringaf` and `result` as propagated build inputs (thus they will also be
available to libraries depending on this library).
- The library will be installed using the `angstrom.install` file that dune
generates.
```nix
{ lib
, fetchFromGitHub
, buildDunePackage
, alcotest
, result
, bigstringaf
}:
{ lib,
fetchFromGitHub,
buildDunePackage,
ocaml,
ocaml-syntax-shims,
alcotest,
result,
bigstringaf,
ppx_let }:
buildDunePackage rec {
pname = "angstrom";
version = "0.10.0";
version = "0.15.0";
useDune2 = true;
minimumOCamlVersion = "4.03";
minimalOCamlVersion = "4.04";
src = fetchFromGitHub {
owner = "inhabitedtype";
repo = pname;
rev = version;
sha256 = "0lh6024yf9ds0nh9i93r9m6p5psi8nvrqxl5x7jwl13zb0r9xfpw";
sha256 = "1hmrkdcdlkwy7rxhngf3cv3sa61cznnd9p5lmqhx20664gx2ibrh";
};
buildInputs = [ alcotest ];
checkInputs = [ alcotest ppx_let ];
buildInputs = [ ocaml-syntax-shims ];
propagatedBuildInputs = [ bigstringaf result ];
doCheck = true;
doCheck = lib.versionAtLeast ocaml.version "4.05";
meta = with lib; {
meta = {
homepage = "https://github.com/inhabitedtype/angstrom";
description = "OCaml parser combinators built for speed and memory efficiency";
license = licenses.bsd3;
maintainers = with maintainers; [ sternenseemann ];
license = lib.licenses.bsd3;
maintainers = with lib.maintainers; [ sternenseemann ];
};
}
```
Here is a second example, this time using a source archive generated with `dune-release`. It is a good idea to use this archive when it is available as it will usually contain substituted variables such as a `%%VERSION%%` field. This library does not depend on any other OCaml library and no tests are run after building it.
```nix
{ lib
, fetchurl
, buildDunePackage
}:
{ lib, fetchurl, buildDunePackage }:
buildDunePackage rec {
pname = "wtf8";
version = "1.0.1";
version = "1.0.2";
useDune2 = true;
minimumOCamlVersion = "4.01";
minimalOCamlVersion = "4.02";
src = fetchurl {
url = "https://github.com/flowtype/ocaml-${pname}/releases/download/v${version}/${pname}-${version}.tbz";
sha256 = "1msg3vycd3k8qqj61sc23qks541cxpb97vrnrvrhjnqxsqnh6ygq";
url = "https://github.com/flowtype/ocaml-${pname}/releases/download/v${version}/${pname}-v${version}.tbz";
sha256 = "09ygcxxd5warkdzz17rgpidrd0pg14cy2svvnvy1hna080lzg7vp";
};
meta = with lib; {

@ -1,14 +1,15 @@
# Python {#python}
## User Guide
## User Guide {#user-guide}
### Using Python
### Using Python {#using-python}
#### Overview
#### Overview {#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.9. 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.
@ -30,7 +31,7 @@ The main package set contains aliases to these package sets, e.g.
`pythonPackages` refers to `python.pkgs` and `python38Packages` to
`python38.pkgs`.
#### Installing Python and packages
#### Installing Python and packages {#installing-python-and-packages}
The Nix and NixOS manuals explain how packages are generally installed. In the
case of Python and Nix, it is important to make a distinction between whether the
@ -61,7 +62,7 @@ Philosphically, this should be familiar to users who are used to a `venv` style
of development: individual projects create their own Python environments without
impacting the global environment or each other.
#### Ad-hoc temporary Python environment with `nix-shell`
#### Ad-hoc temporary Python environment with `nix-shell` {#ad-hoc-temporary-python-environment-with-nix-shell}
The simplest way to start playing with the way nix wraps and sets up Python
environments is with `nix-shell` at the cmdline. These environments create a
@ -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>
@ -130,7 +131,7 @@ arbitrary dependencies. This is a good way to get a feel for how the Python
interpreter and dependencies work in Nix and NixOS, but to do some actual
development, we'll want to make it a bit more persistent.
##### Running Python scripts and using `nix-shell` as shebang
##### Running Python scripts and using `nix-shell` as shebang {#running-python-scripts-and-using-nix-shell-as-shebang}
Sometimes, we have a script whose header looks like this:
@ -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'
```ShellSession
$ nix-shell -p 'python38.withPackages(ps: with ps; [ numpy ])' --run 'python3 foo.py'
The dot product of [1 2] and [3 4] is: 11
```
@ -202,7 +203,7 @@ of the package versions.
This is also a great way to ensure the script executes identically on different
servers.
##### Load environment from `.nix` expression
##### Load environment from `.nix` expression {#load-environment-from-.nix-expression}
We've now seen how to create an ad-hoc temporary shell session, and how to
create a single script with Python dependencies, but in the course of normal
@ -244,7 +245,7 @@ let
ps.toolz
]);
in mkShell {
buildInputs = [
packages = [
pythonEnv
black
@ -261,7 +262,7 @@ and its Python dependencies, but also tools like `black` or `mypy` and libraries
like `libffi` the `openssl` in scope. This is generic and can span any number of
tools or languages across the Nixpkgs ecosystem.
##### Installing environments globally on the system
##### Installing environments globally on the system {#installing-environments-globally-on-the-system}
Up to now, we've been creating environments scoped to an ad-hoc shell session,
or a single script, or a single project. This is generally advisable, as it
@ -314,7 +315,7 @@ If you get a conflict or prefer to keep the setup clean, you can have `nix-env`
atomically *uninstall* all other imperatively installed packages and replace
your profile with just `myEnv` by using the `--replace` flag.
##### Environment defined in `/etc/nixos/configuration.nix`
##### Environment defined in `/etc/nixos/configuration.nix` {#environment-defined-in-etcnixosconfiguration.nix}
For the sake of completeness, here's how to install the environment system-wide
on NixOS.
@ -328,16 +329,16 @@ on NixOS.
}
```
### Developing with Python
### Developing with Python {#developing-with-python}
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
#### Python library packages in Nixpkgs {#python-library-packages-in-nixpkgs}
With Nix all packages are built by functions. The main function in Nix for
building Python libraries is `buildPythonPackage`. Let's see how we can build the
@ -424,7 +425,7 @@ of `withPackages` we used a `let` expression. You can see that we used
`toolz` from the Nixpkgs package set this time, but instead took our own version
that we introduced with the `let` expression.
#### Handling dependencies
#### Handling dependencies {#handling-dependencies}
Our example, `toolz`, does not have any dependencies on other Python packages or
system libraries. According to the manual, `buildPythonPackage` uses the
@ -438,7 +439,7 @@ The following example shows which arguments are given to `buildPythonPackage` in
order to build [`datashape`](https://github.com/blaze/datashape).
```nix
{ lib, buildPythonPackage, fetchPypi, numpy, multipledispatch, dateutil, pytest }:
{ lib, buildPythonPackage, fetchPypi, numpy, multipledispatch, python-dateutil, pytest }:
buildPythonPackage rec {
pname = "datashape";
@ -450,7 +451,7 @@ buildPythonPackage rec {
};
checkInputs = [ pytest ];
propagatedBuildInputs = [ numpy multipledispatch dateutil ];
propagatedBuildInputs = [ numpy multipledispatch python-dateutil ];
meta = with lib; {
homepage = "https://github.com/ContinuumIO/datashape";
@ -462,7 +463,7 @@ buildPythonPackage rec {
```
We can see several runtime dependencies, `numpy`, `multipledispatch`, and
`dateutil`. Furthermore, we have one `checkInputs`, i.e. `pytest`. `pytest` is a
`python-dateutil`. Furthermore, we have one `checkInputs`, i.e. `pytest`. `pytest` is a
test runner and is only used during the `checkPhase` and is therefore not added
to `propagatedBuildInputs`.
@ -536,9 +537,10 @@ buildPythonPackage rec {
};
}
```
Note also the line `doCheck = false;`, we explicitly disabled running the test-suite.
#### Testing Python Packages
#### Testing Python Packages {#testing-python-packages}
It is highly encouraged to have testing as part of the package build. This
helps to avoid situations where the package was able to build and install,
@ -558,10 +560,11 @@ thus can cause issues when a test suite asserts on that behavior.
as many tests should be enabled as possible. Failing tests can still be
a good indication that the package is not in a valid state.
#### Using pytest
#### Using pytest {#using-pytest}
Pytest is the most common test runner for python repositories. A trivial
test run would be:
```
checkInputs = [ pytest ];
checkPhase = "pytest";
@ -571,6 +574,7 @@ However, many repositories' test suites do not translate well to nix's build
sandbox, and will generally need many tests to be disabled.
To filter tests using pytest, one can do the following:
```
checkInputs = [ pytest ];
# avoid tests which need additional data or touch network
@ -586,19 +590,20 @@ easier than having to create a new package.
`-k` is used to define a predicate for test names. In this example, we are
filtering out tests which contain `download` or `update` in their test case name.
Only one `-k` argument is allows, and thus a long predicate should be concatenated
with "\" and wrapped to the next line.
Only one `-k` argument is allowed, and thus a long predicate should be concatenated
with “\\” and wrapped to the next line.
*NOTE:* In pytest==6.0.1, the use of "\" to continue a line (e.g. `-k 'not download \'`) has
*NOTE:* In pytest==6.0.1, the use of “\\” to continue a line (e.g. `-k 'not download \'`) has
been removed, in this case, it's recommended to use `pytestCheckHook`.
#### Using pytestCheckHook
#### Using pytestCheckHook {#using-pytestcheckhook}
`pytestCheckHook` is a convenient hook which will substitute the setuptools
`test` command for a checkPhase which runs `pytest`. This is also beneficial
when a package may need many items disabled to run the test suite.
Using the example above, the analagous pytestCheckHook usage would be:
```
checkInputs = [ pytestCheckHook ];
@ -636,9 +641,9 @@ Trying to concatenate the related strings to disable tests in a regular checkPha
would be much harder to read. This also enables us to comment on why specific tests
are disabled.
#### Using pythonImportsCheck
#### Using pythonImportsCheck {#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.
@ -658,7 +663,7 @@ However, this is done in it's own phase, and not dependent on whether `doCheck =
This can also be useful in verifying that the package doesn't assume commonly
present packages (e.g. `setuptools`)
### Develop local package
### Develop local package {#develop-local-package}
As a Python developer you're likely aware of [development mode](http://setuptools.readthedocs.io/en/latest/setuptools.html#development-mode)
(`python setup.py develop`); instead of installing the package this command
@ -693,7 +698,7 @@ buildPythonPackage rec {
It is important to note that due to how development mode is implemented on Nix
it is not possible to have multiple packages simultaneously in development mode.
### Organising your packages
### Organising your packages {#organising-your-packages}
So far we discussed how you can use Python on Nix, and how you can develop with
it. We've looked at how you write expressions to package Python packages, and we
@ -705,7 +710,7 @@ like to be able to use in different projects. In order to minimise unnecessary
duplication we now look at how you can maintain a repository with your
own packages. The important functions here are `import` and `callPackage`.
### Including a derivation using `callPackage`
### Including a derivation using `callPackage` {#including-a-derivation-using-callpackage}
Earlier we created a Python environment using `withPackages`, and included the
`toolz` package via a `let` expression.
@ -755,28 +760,28 @@ don't explicitly define which `python` derivation should be used. In the above
example we use `buildPythonPackage` that is part of the set `python38Packages`,
and in this case the `python38` interpreter is automatically used.
## Reference
## Reference {#reference}
### Interpreters
### Interpreters {#interpreters}
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
`out/{python.sitePackages}` to `$PYTHONPATH` if such directory
exists.
#### Missing `tkinter` module standard library
#### Missing `tkinter` module standard library {#missing-tkinter-module-standard-library}
To reduce closure size the `Tkinter`/`tkinter` is available as a separate package, `pythonPackages.tkinter`.
#### Attributes on interpreters packages
#### Attributes on interpreters packages {#attributes-on-interpreters-packages}
Each interpreter has the following attributes:
@ -788,7 +793,24 @@ 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`.
### Building packages and applications
### Optimizations {#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 {#building-packages-and-applications}
Python libraries and applications that use `setuptools` or
`distutils` are typically built with respectively the `buildPythonPackage` and
@ -817,10 +839,10 @@ sets are
and the aliases
* `pkgs.python2Packages` pointing to `pkgs.python27Packages`
* `pkgs.python3Packages` pointing to `pkgs.python38Packages`
* `pkgs.python3Packages` pointing to `pkgs.python39Packages`
* `pkgs.pythonPackages` pointing to `pkgs.python2Packages`
#### `buildPythonPackage` function
#### `buildPythonPackage` function {#buildpythonpackage-function}
The `buildPythonPackage` function is implemented in
`pkgs/development/interpreters/python/mk-python-derivation`
@ -829,7 +851,7 @@ using setup hooks.
The following is an example:
```nix
{ lib, buildPythonPackage, fetchPypi, hypothesis, setuptools_scm, attrs, py, setuptools, six, pluggy }:
{ lib, buildPythonPackage, fetchPypi, hypothesis, setuptools-scm, attrs, py, setuptools, six, pluggy }:
buildPythonPackage rec {
pname = "pytest";
@ -846,7 +868,7 @@ buildPythonPackage rec {
'';
checkInputs = [ hypothesis ];
nativeBuildInputs = [ setuptools_scm ];
nativeBuildInputs = [ setuptools-scm ];
propagatedBuildInputs = [ attrs py setuptools six pluggy ];
meta = with lib; {
@ -872,7 +894,7 @@ e.g. the test runner, should be added to `checkInputs`.
By default `meta.platforms` is set to the same value
as the interpreter unless overridden otherwise.
##### `buildPythonPackage` parameters
##### `buildPythonPackage` parameters {#buildpythonpackage-parameters}
All parameters from `stdenv.mkDerivation` function are still supported. The
following are specific to `buildPythonPackage`:
@ -918,7 +940,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
@ -928,7 +950,7 @@ because their behaviour is different:
`buildPythonPackage` also injects code into and wraps executables with the
paths included in this list. Items listed in `install_requires` go here.
##### Overriding Python packages
##### Overriding Python packages {#overriding-python-packages}
The `buildPythonPackage` function has a `overridePythonAttrs` method that can be
used to override the package. In the following example we create an environment
@ -956,7 +978,7 @@ with import <nixpkgs> {};
in python.withPackages(ps: [ps.blaze])).env
```
#### `buildPythonApplication` function
#### `buildPythonApplication` function {#buildpythonapplication-function}
The `buildPythonApplication` function is practically the same as
`buildPythonPackage`. The main purpose of this function is to build a Python
@ -1001,7 +1023,7 @@ luigi = callPackage ../applications/networking/cluster/luigi { };
Since the package is an application, a consumer doesn't need to care about
Python versions or modules, which is why they don't go in `pythonPackages`.
#### `toPythonApplication` function
#### `toPythonApplication` function {#topythonapplication-function}
A distinction is made between applications and libraries, however, sometimes a
package is used as both. In this case the package is added as a library to
@ -1013,11 +1035,12 @@ The Nix expression shall use `buildPythonPackage` and be called from
`python-packages.nix`. A reference shall be created from `all-packages.nix` to
the attribute in `python-packages.nix`, and the `toPythonApplication` shall be
applied to the reference:
```nix
youtube-dl = with pythonPackages; toPythonApplication youtube-dl;
```
#### `toPythonModule` function
#### `toPythonModule` function {#topythonmodule-function}
In some cases, such as bindings, a package is created using
`stdenv.mkDerivation` and added as attribute in `all-packages.nix`. The Python
@ -1034,7 +1057,7 @@ opencv = toPythonModule (pkgs.opencv.override {
Do pay attention to passing in the right Python version!
#### `python.buildEnv` function
#### `python.buildEnv` function {#python.buildenv-function}
Python environments can be created using the low-level `pkgs.buildEnv` function.
This example shows how to create an environment that has the Pyramid Web Framework.
@ -1072,8 +1095,8 @@ with import <nixpkgs> {};
will drop you into a shell where Python will have the
specified packages in its path.
##### `python.buildEnv` arguments {#python.buildenv-arguments}
##### `python.buildEnv` arguments
* `extraLibs`: List of packages installed inside the environment.
* `postBuild`: Shell command executed after the build of environment.
@ -1081,7 +1104,7 @@ specified packages in its path.
* `permitUserSite`: Skip setting the `PYTHONNOUSERSITE` environment variable in
wrapped binaries in the environment.
#### `python.withPackages` function
#### `python.withPackages` function {#python.withpackages-function}
The `python.withPackages` function provides a simpler interface to the `python.buildEnv` functionality.
It takes a function as an argument that is passed the set of python packages and returns the list
@ -1123,7 +1146,7 @@ need them, you have to use `python.buildEnv`.
Python 2 namespace packages may provide `__init__.py` that collide. In that case
`python.buildEnv` should be used with `ignoreCollisions = true`.
#### Setup hooks
#### Setup hooks {#setup-hooks}
The following are setup hooks specifically for Python packages. Most of these
are used in `buildPythonPackage`.
@ -1148,7 +1171,7 @@ are used in `buildPythonPackage`.
- `wheelUnpackHook` to move a wheel to the correct folder so it can be installed
with the `pipInstallHook`.
### Development mode
### Development mode {#development-mode}
Development or editable mode is supported. To develop Python packages
`buildPythonPackage` has additional logic inside `shellPhase` to run `pip
@ -1157,6 +1180,7 @@ install -e . --prefix $TMPDIR/`for the package.
Warning: `shellPhase` is executed only if `setup.py` exists.
Given a `default.nix`:
```nix
with import <nixpkgs> {};
@ -1179,7 +1203,7 @@ nix-shell -p pythonPackages.pyramid zlib libjpeg git
Note: There is a boolean value `lib.inNixShell` set to `true` if nix-shell is invoked.
### Tools
### Tools {#tools}
Packages inside nixpkgs are written by hand. However many tools exist in
community to help save time. No tool is preferred at the moment.
@ -1188,9 +1212,10 @@ 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
### Deterministic builds {#deterministic-builds}
The Python interpreters are now built deterministically. Minor modifications had
to be made to the interpreters in order to generate deterministic bytecode. This
@ -1202,7 +1227,7 @@ have timestamp 1. The `buildPythonPackage` function sets `DETERMINISTIC_BUILD=1`
and [PYTHONHASHSEED=0](https://docs.python.org/3.8/using/cmdline.html#envvar-PYTHONHASHSEED).
Both are also exported in `nix-shell`.
### Automatic tests
### Automatic tests {#automatic-tests}
It is recommended to test packages as part of the build process.
Source distributions (`sdist`) often include test files, but not always.
@ -1211,7 +1236,7 @@ By default the command `python setup.py test` is run as part of the
`checkPhase`, but often it is necessary to pass a custom `checkPhase`. An
example of such a situation is when `py.test` is used.
#### Common issues
#### Common issues {#common-issues}
* Non-working tests can often be deselected. By default `buildPythonPackage`
runs `python setup.py test`. Most Python modules follows the standard test
@ -1228,18 +1253,19 @@ example of such a situation is when `py.test` is used.
'';
}
```
* Tests that attempt to access `$HOME` can be fixed by using the following
work-around before running tests (e.g. `preCheck`): `export HOME=$(mktemp -d)`
## FAQ
## FAQ {#faq}
### How to solve circular dependencies?
### How to solve circular dependencies? {#how-to-solve-circular-dependencies}
Consider the packages `A` and `B` that depend on each other. When packaging `B`,
a solution is to override package `A` not to depend on `B` as an input. The same
should also be done when packaging `A`.
### How to override a Python package?
### How to override a Python package? {#how-to-override-a-python-package}
We can override the interpreter and pass `packageOverrides`. In the following
example we rename the `pandas` package and build it.
@ -1297,7 +1323,7 @@ let
in newpkgs.inkscape
```
### `python setup.py bdist_wheel` cannot create .whl
### `python setup.py bdist_wheel` cannot create .whl {#python-setup.py-bdist_wheel-cannot-create-.whl}
Executing `python setup.py bdist_wheel` in a `nix-shell `fails with
```
@ -1330,7 +1356,7 @@ or unset `SOURCE_DATE_EPOCH`:
nix-shell --run "unset SOURCE_DATE_EPOCH; python3 setup.py bdist_wheel"
```
### `install_data` / `data_files` problems
### `install_data` / `data_files` problems {#install_data-data_files-problems}
If you get the following error:
@ -1350,7 +1376,7 @@ ${python.interpreter} setup.py install_data --install-dir=$out --root=$out
sed -i '/ = data\_files/d' setup.py
```
### Rationale of non-existent global site-packages
### Rationale of non-existent global site-packages {#rationale-of-non-existent-global-site-packages}
On most operating systems a global `site-packages` is maintained. This however
becomes problematic if you want to run multiple Python versions or have multiple
@ -1365,7 +1391,7 @@ If you want to create a Python environment for development, then the recommended
method is to use `nix-shell`, either with or without the `python.buildEnv`
function.
### How to consume Python modules using pip in a virtual environment like I am used to on other Operating Systems?
### How to consume Python modules using pip in a virtual environment like I am used to on other Operating Systems? {#how-to-consume-python-modules-using-pip-in-a-virtual-environment-like-i-am-used-to-on-other-operating-systems}
While this approach is not very idiomatic from Nix perspective, it can still be
useful when dealing with pre-existing projects or in situations where it's not
@ -1478,7 +1504,7 @@ is executed it will attempt to download the Python modules listed in
requirements.txt. However these will be cached locally within the `virtualenv`
folder and not downloaded again.
### How to override a Python package from `configuration.nix`?
### How to override a Python package from `configuration.nix`? {#how-to-override-a-python-package-from-configuration.nix}
If you need to change a package's attribute(s) from `configuration.nix` you could do:
@ -1486,11 +1512,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 +1525,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,12 +1537,12 @@ this snippet:
```nix
myPythonPackages = pythonPackages.override {
overrides = self: super: {
zerobin = ...;
twisted = ...;
};
}
```
### How to override a Python package using overlays?
### How to override a Python package using overlays? {#how-to-override-a-python-package-using-overlays}
Use the following overlay template:
@ -1521,11 +1550,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";
};
});
};
@ -1533,12 +1563,12 @@ self: super: {
}
```
### How to use Intel's MKL with numpy and scipy?
### How to use Intel’s MKL with numpy and scipy? {#how-to-use-intels-mkl-with-numpy-and-scipy}
MKL can be configured using an overlay. See the section "[Using overlays to
configure alternatives](#sec-overlays-alternatives-blas-lapack)".
### What inputs do `setup_requires`, `install_requires` and `tests_require` map to?
### What inputs do `setup_requires`, `install_requires` and `tests_require` map to? {#what-inputs-do-setup_requires-install_requires-and-tests_require-map-to}
In a `setup.py` or `setup.cfg` it is common to declare dependencies:
@ -1546,17 +1576,15 @@ In a `setup.py` or `setup.cfg` it is common to declare dependencies:
* `install_requires` corresponds to `propagatedBuildInputs`
* `tests_require` corresponds to `checkInputs`
## Contributing
## Contributing {#contributing}
### Contributing guidelines
### Contributing guidelines {#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 +1594,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.

@ -90,20 +90,22 @@ stdenv.mkDerivation {
}
```
::: note
::: {.note}
`wrapQtAppsHook` ignores files that are non-ELF executables.
This means that scripts won't be automatically wrapped so you'll need to manually wrap them as previously mentioned.
An example of when you'd always need to do this is with Python applications that use PyQt.
:::
## Adding a library to Nixpkgs
## Adding a library to Nixpkgs {#adding-a-library-to-nixpkgs}
Add Qt libraries to `qt5-packages.nix` to make them available for every
supported Qt version.
### Example adding a Qt library {#qt-library-all-packages-nix}
The following represents the contents of `qt5-packages.nix`.
```
```nix
{
# ...
@ -121,19 +123,21 @@ 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";
}
```
## Adding an application to Nixpkgs
## Adding an application to Nixpkgs {#adding-an-application-to-nixpkgs}
Add Qt applications to `qt5-packages.nix`. Add an alias to `all-packages.nix`
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 +148,8 @@ The following represents the contents of `qt5-packages.nix`.
```
The following represents the contents of `all-packages.nix`.
```
```nix
{
# ...

@ -1,6 +1,6 @@
# R {#r}
## Installation
## Installation {#installation}
Define an environment for R that contains all the libraries that you'd like to
use by adding the following snippet to your $HOME/.config/nixpkgs/config.nix file:
@ -31,6 +31,7 @@ output is the name that has to be passed to rWrapper in the code snipped above.
However, if you'd like to add a file to your project source to make the
environment available for other contributors, you can create a `default.nix`
file like so:
```nix
with import <nixpkgs> {};
{
@ -50,7 +51,7 @@ with import <nixpkgs> {};
and then run `nix-shell .` to be dropped into a shell with those packages
available.
## RStudio
## RStudio {#rstudio}
RStudio uses a standard set of packages and ignores any custom R
environments or installed packages you may have. To create a custom
@ -93,7 +94,7 @@ Executing `nix-shell` will then drop you into an environment equivalent to the
one above. If you need additional packages just add them to the list and
re-enter the shell.
## Updating the package set
## Updating the package set {#updating-the-package-set}
```bash
nix-shell generate-shell.nix
@ -113,8 +114,7 @@ mv bioc-experiment-packages.nix.new bioc-experiment-packages.nix
`generate-r-packages.R <repo>` reads `<repo>-packages.nix`, therefor the renaming.
## Testing if the Nix-expression could be evaluated
## Testing if the Nix-expression could be evaluated {#testing-if-the-nix-expression-could-be-evaluated}
```bash
nix-build test-evaluation.nix --dry-run

@ -1,6 +1,6 @@
# Ruby {#sec-language-ruby}
## Using Ruby
## Using Ruby {#using-ruby}
Several versions of Ruby interpreters are available on Nix, as well as over 250 gems and many applications written in Ruby. The attribute `ruby` refers to the default Ruby interpreter, which is currently MRI 2.6. It's also possible to refer to specific versions, e.g. `ruby_2_y`, `jruby`, or `mruby`.
@ -12,7 +12,7 @@ The interpreters have common attributes, namely `gems`, and `withPackages`. So y
Since not all gems have executables like `nokogiri`, it's usually more convenient to use the `withPackages` function like this: `ruby.withPackages (p: with p; [ nokogiri ])`. This will also make sure that the Ruby in your environment will be able to find the gem and it can be used in your Ruby code (for example via `ruby` or `irb` executables) via `require "nokogiri"` as usual.
### Temporary Ruby environment with `nix-shell`
### Temporary Ruby environment with `nix-shell` {#temporary-ruby-environment-with-nix-shell}
Rather than having a single Ruby environment shared by all Ruby development projects on a system, Nix allows you to create separate environments per project. `nix-shell` gives you the possibility to temporarily load another environment akin to a combined `chruby` or `rvm` and `bundle exec`.
@ -30,7 +30,7 @@ $ nix-shell -p ruby.gems.nokogiri ruby.gems.pry
Again, it's possible to launch the interpreter from the shell. The Ruby interpreter has the attribute `gems` which contains all Ruby gems for that specific interpreter.
#### Load Ruby environment from `.nix` expression
#### Load Ruby environment from `.nix` expression {#load-ruby-environment-from-.nix-expression}
As explained in the Nix manual, `nix-shell` can also load an expression from a `.nix` file. Say we want to have Ruby 2.6, `nokogori`, and `pry`. Consider a `shell.nix` file with:
@ -45,7 +45,7 @@ What's happening here?
2. Then we create a Ruby environment with the `withPackages` function.
3. The `withPackages` function expects us to provide a function as an argument that takes the set of all ruby gems and returns a list of packages to include in the environment. Here, we select the packages `nokogiri` and `pry` from the package set.
#### Execute command with `--run`
#### Execute command with `--run` {#execute-command-with---run}
A convenient flag for `nix-shell` is `--run`. It executes a command in the `nix-shell`. We can e.g. directly open a `pry` REPL:
@ -65,7 +65,7 @@ Or run a script using this environment:
$ nix-shell -p "ruby.withPackages (ps: with ps; [ nokogiri pry ])" --run "ruby example.rb"
```
#### Using `nix-shell` as shebang
#### Using `nix-shell` as shebang {#using-nix-shell-as-shebang}
In fact, for the last case, there is a more convenient method. You can add a [shebang](<https://en.wikipedia.org/wiki/Shebang_(Unix)>) to your script specifying which dependencies `nix-shell` needs. With the following shebang, you can just execute `./example.rb`, and it will run with all dependencies.
@ -80,9 +80,9 @@ body = RestClient.get('http://example.com').body
puts Nokogiri::HTML(body).at('h1').text
```
## Developing with Ruby
## Developing with Ruby {#developing-with-ruby}
### Using an existing Gemfile
### Using an existing Gemfile {#using-an-existing-gemfile}
In most cases, you'll already have a `Gemfile.lock` listing all your dependencies. This can be used to generate a `gemset.nix` which is used to fetch the gems and combine them into a single environment. The reason why you need to have a separate file for this, is that Nix requires you to have a checksum for each input to your build. Since the `Gemfile.lock` that `bundler` generates doesn't provide us with checksums, we have to first download each gem, calculate its SHA256, and store it in this separate file.
@ -106,7 +106,7 @@ let
name = "gems-for-some-project";
gemdir = ./.;
};
in mkShell { buildInputs = [ gems gems.wrappedRuby ]; }
in mkShell { packages = [ gems gems.wrappedRuby ]; }
```
With this file in your directory, you can run `nix-shell` to build and use the gems. The important parts here are `bundlerEnv` and `wrappedRuby`.
@ -120,7 +120,7 @@ One common issue that you might have is that you have Ruby 2.6, but also `bundle
mkShell { buildInputs = [ gems (lowPrio gems.wrappedRuby) ]; }
```
### Gem-specific configurations and workarounds
### Gem-specific configurations and workarounds {#gem-specific-configurations-and-workarounds}
In some cases, especially if the gem has native extensions, you might need to modify the way the gem is built.
@ -201,7 +201,7 @@ $ nix-shell --run 'ruby -rpg -e "puts PG.library_version"'
Of course for this use-case one could also use overlays since the configuration for `pg` depends on the `postgresql` alias, but for demonstration purposes this has to suffice.
### Adding a gem to the default gemset
### Adding a gem to the default gemset {#adding-a-gem-to-the-default-gemset}
Now that you know how to get a working Ruby environment with Nix, it's time to go forward and start actually developing with Ruby. We will first have a look at how Ruby gems are packaged on Nix. Then, we will look at how you can use development mode with your code.
@ -215,7 +215,7 @@ To test that it works, you can then try using the gem with:
NIX_PATH=nixpkgs=$PWD nix-shell -p "ruby.withPackages (ps: with ps; [ name-of-your-gem ])"
```
### Packaging applications
### Packaging applications {#packaging-applications}
A common task is to add a ruby executable to nixpkgs, popular examples would be `chef`, `jekyll`, or `sass`. A good way to do that is to use the `bundlerApp` function, that allows you to make a package that only exposes the listed executables, otherwise the package may cause conflicts through common paths like `bin/rake` or `bin/bundler` that aren't meant to be used.
@ -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 }:
@ -243,7 +243,7 @@ bundlerApp {
All that's left to do is to generate the corresponding `Gemfile.lock` and `gemset.nix` as described above in the `Using an existing Gemfile` section.
#### Packaging executables that require wrapping
#### Packaging executables that require wrapping {#packaging-executables-that-require-wrapping}
Sometimes your app will depend on other executables at runtime, and tries to find it through the `PATH` environment variable.

@ -2,23 +2,24 @@
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),
or use Mozilla's [Rust nightlies overlay](#using-the-rust-nightlies-overlay).
## Compiling Rust applications with Cargo
## Compiling Rust applications with Cargo {#compiling-rust-applications-with-cargo}
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`
@ -106,8 +107,56 @@ rustPlatform.buildRustPackage rec {
}
```
### Importing a `Cargo.lock` file {#importing-a-cargo.lock-file}
Using `cargoSha256` or `cargoHash` is tedious when using
`buildRustPackage` within a project, since it requires that the hash
is updated after every change to `Cargo.lock`. Therefore,
`buildRustPackage` also supports vendoring dependencies directly from
a `Cargo.lock` file using the `cargoLock` argument. For example:
```nix
rustPlatform.buildRustPackage rec {
pname = "myproject";
version = "1.0.0";
cargoLock = {
lockFile = ./Cargo.lock;
}
# ...
}
```
This will retrieve the dependencies using fixed-output derivations from
the specified lockfile.
The output hash of each dependency that uses a git source must be
specified in the `outputHashes` attribute. For example:
```nix
rustPlatform.buildRustPackage rec {
pname = "myproject";
version = "1.0.0";
cargoLock = {
lockFile = ./Cargo.lock;
outputHashes = {
"finalfusion-0.14.0" = "17f4bsdzpcshwh74w5z119xjy2if6l2wgyjy56v621skr2r8y904";
};
}
# ...
}
```
If you do not specify an output hash for a git dependency, building
the package will fail and inform you of which crate needs to be
added. To find the correct hash, you can first use `lib.fakeSha256` or
`lib.fakeHash` as a stub hash. Building the package (and thus the
vendored dependencies) will then inform you of the correct hash.
### Cross compilation
### Cross compilation {#cross-compilation}
By default, Rust packages are compiled for the host platform, just like any
other package is. The `--target` passed to rust tools is computed from this.
@ -119,6 +168,7 @@ where they are known to differ. But there are ways to customize the argument:
name will be used instead.
For example:
```nix
import <nixpkgs> {
crossSystem = (import <nixpkgs/lib>).systems.examples.armhf-embedded // {
@ -126,7 +176,9 @@ where they are known to differ. But there are ways to customize the argument:
};
}
```
will result in:
```shell
--target thumbv7em-none-eabi
```
@ -139,6 +191,7 @@ where they are known to differ. But there are ways to customize the argument:
will be used instead.
For example:
```nix
import <nixpkgs> {
crossSystem = (import <nixpkgs/lib>).systems.examples.armhf-embedded // {
@ -147,7 +200,9 @@ where they are known to differ. But there are ways to customize the argument:
};
}
```
will result in:
```shell
--target /nix/store/asdfasdfsadf-thumb-crazy.json # contains {"foo":"","bar":""}
```
@ -157,7 +212,7 @@ path) can be passed directly to `buildRustPackage`:
```nix
pkgs.rustPlatform.buildRustPackage {
(...)
/* ... */
target = "x86_64-fortanix-unknown-sgx";
}
```
@ -171,7 +226,7 @@ ad-hoc escape hatch to `buildRustPackage` can be removed.
Note that currently custom targets aren't compiled with `std`, so `cargo test`
will fail. This can be ignored by adding `doCheck = false;` to your derivation.
### Running package tests
### Running package tests {#running-package-tests}
When using `buildRustPackage`, the `checkPhase` is enabled by default and runs
`cargo test` on the package to build. To make sure that we don't compile the
@ -192,7 +247,14 @@ 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`.
#### Tests relying on the structure of the `target/` directory
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 {#tests-relying-on-the-structure-of-the-target-directory}
Some tests may rely on the structure of the `target/` directory. Those tests
are likely to fail because we use `cargo --target` during the build. This means that
@ -202,7 +264,7 @@ rather than in `target/release/`.
This can only be worked around by patching the affected tests accordingly.
#### Disabling package-tests
#### Disabling package-tests {#disabling-package-tests}
In some instances, it may be necessary to disable testing altogether (with `doCheck = false;`):
@ -216,7 +278,7 @@ The above are just guidelines, and exceptions may be granted on a case-by-case b
However, please check if it's possible to disable a problematic subset of the
test suite and leave a comment explaining your reasoning.
#### Setting `test-threads`
#### Setting `test-threads` {#setting-test-threads}
`buildRustPackage` will use parallel test threads by default,
sometimes it may be necessary to disable this so the tests run consecutively.
@ -228,7 +290,7 @@ rustPlatform.buildRustPackage {
}
```
### Building a package in `debug` mode
### Building a package in `debug` mode {#building-a-package-in-debug-mode}
By default, `buildRustPackage` will use `release` mode for builds. If a package
should be built in `debug` mode, it can be configured like so:
@ -242,20 +304,20 @@ rustPlatform.buildRustPackage {
In this scenario, the `checkPhase` will be ran in `debug` mode as well.
### Custom `build`/`install`-procedures
### Custom `build`/`install`-procedures {#custom-buildinstall-procedures}
Some packages may use custom scripts for building/installing, e.g. with a `Makefile`.
In these cases, it's recommended to override the `buildPhase`/`installPhase`/`checkPhase`.
Otherwise, some steps may fail because of the modified directory structure of `target/`.
### Building a crate with an absent or out-of-date Cargo.lock file
### Building a crate with an absent or out-of-date Cargo.lock file {#building-a-crate-with-an-absent-or-out-of-date-cargo.lock-file}
`buildRustPackage` needs a `Cargo.lock` file to get all dependencies in the
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 = [
@ -265,13 +327,13 @@ rustPlatform.buildRustPackage rec {
}
```
## Compiling non-Rust packages that include Rust code
## Compiling non-Rust packages that include Rust code {#compiling-non-rust-packages-that-include-rust-code}
Several non-Rust packages incorporate Rust code for performance- or
security-sensitive parts. `rustPlatform` exposes several functions and
hooks that can be used to integrate Cargo in non-Rust packages.
### Vendoring of dependencies
### Vendoring of dependencies {#vendoring-of-dependencies}
Since network access is not allowed in sandboxed builds, Rust crate
dependencies need to be retrieved using a fetcher. `rustPlatform`
@ -300,7 +362,38 @@ attributes can also be used:
the `Cargo.lock`/`Cargo.toml` files need to be patched before
vendoring.
### Hooks
If a `Cargo.lock` file is available, you can alternatively use the
`importCargoLock` function. In contrast to `fetchCargoTarball`, this
function does not require a hash (unless git dependencies are used)
and fetches every dependency as a separate fixed-output derivation.
`importCargoLock` can be used as follows:
```
cargoDeps = rustPlatform.importCargoLock {
lockFile = ./Cargo.lock;
};
```
If the `Cargo.lock` file includes git dependencies, then their output
hashes need to be specified since they are not available through the
lock file. For example:
```
cargoDeps = rustPlatform.importCargoLock {
lockFile = ./Cargo.lock;
outputHashes = {
"rand-0.8.3" = "0ya2hia3cn31qa8894s3av2s8j5bjwb6yq92k0jsnlx7jid0jwqa";
};
};
```
If you do not specify an output hash for a git dependency, building
`cargoDeps` will fail and inform you of which crate needs to be
added. To find the correct hash, you can first use `lib.fakeSha256` or
`lib.fakeHash` as a stub hash. Building `cargoDeps` will then inform
you of the correct hash.
### Hooks {#hooks}
`rustPlatform` provides the following hooks to automate Cargo builds:
@ -321,16 +414,17 @@ 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`.
### Examples
### Examples {#examples}
#### Python package using `setuptools-rust`
#### Python package using `setuptools-rust` {#python-package-using-setuptools-rust}
For Python packages using `setuptools-rust`, you can use
`fetchCargoTarball` and `cargoSetupHook` to retrieve and set up Cargo
@ -416,7 +510,7 @@ buildPythonPackage rec {
}
```
#### Python package using `maturin`
#### Python package using `maturin` {#python-package-using-maturin}
Python packages that use [Maturin](https://github.com/PyO3/maturin)
can be built with `fetchCargoTarball`, `cargoSetupHook`, and
@ -457,9 +551,9 @@ buildPythonPackage rec {
}
```
## Compiling Rust crates using Nix instead of Cargo
## Compiling Rust crates using Nix instead of Cargo {#compiling-rust-crates-using-nix-instead-of-cargo}
### Simple operation
### Simple operation {#simple-operation}
When run, `cargo build` produces a file called `Cargo.lock`,
containing pinned versions of all dependencies. Nixpkgs contains a
@ -470,18 +564,19 @@ That Nix expression calls `rustc` directly (hence bypassing Cargo),
and can be used to compile a crate and all its dependencies. Here is
an example for a minimal `hello` crate:
$ cargo new hello
$ cd hello
$ cargo build
```ShellSession
$ cargo new hello
$ cd hello
$ cargo build
Compiling hello v0.1.0 (file:///tmp/hello)
Finished dev [unoptimized + debuginfo] target(s) in 0.20 secs
$ carnix -o hello.nix --src ./. Cargo.lock --standalone
$ nix-build hello.nix -A hello_0_1_0
Finished dev [unoptimized + debuginfo] target(s) in 0.20 secs
$ carnix -o hello.nix --src ./. Cargo.lock --standalone
$ nix-build hello.nix -A hello_0_1_0
```
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 +605,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;
@ -556,7 +651,7 @@ Here, the `libc` crate has no `src` attribute, so `buildRustCrate`
will fetch it from [crates.io](https://crates.io). A `sha256`
attribute is still needed for Nix purity.
### Handling external dependencies
### Handling external dependencies {#handling-external-dependencies}
Some crates require external libraries. For crates from
[crates.io](https://crates.io), such libraries can be specified in
@ -565,7 +660,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 +680,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 +701,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 // {
@ -615,34 +710,34 @@ with import <nixpkgs> {};
}
```
### Options and phases configuration
### Options and phases configuration {#options-and-phases-configuration}
Actually, the overrides introduced in the previous section are more
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 +749,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"
@ -662,13 +757,13 @@ general. A number of other parameters can be overridden:
};
```
### Features
### Features {#features}
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;
@ -677,21 +772,22 @@ features, we would write:
Where `diesel.nix` is the file generated by Carnix, as explained above.
## Setting Up `nix-shell` {#setting-up-nix-shell}
## Setting Up `nix-shell`
Oftentimes you want to develop code from within `nix-shell`. Unfortunately
`buildRustCrate` does not support common `nix-shell` operations directly
(see [this issue](https://github.com/NixOS/nixpkgs/issues/37945))
so we will use `stdenv.mkDerivation` instead.
Using the example `hello` project above, we want to do the following:
- Have access to `cargo` and `rustc`
- Have the `openssl` library available to a crate through it's _normal_
compilation mechanism (`pkg-config`).
A typical `shell.nix` might look like:
```
```nix
with import <nixpkgs> {};
stdenv.mkDerivation {
@ -713,17 +809,19 @@ stdenv.mkDerivation {
```
You should now be able to run the following:
```
```ShellSession
$ nix-shell --pure
$ cargo build
$ cargo test
```
### Controlling Rust Version Inside `nix-shell`
### Controlling Rust Version Inside `nix-shell` {#controlling-rust-version-inside-nix-shell}
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 +836,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,42 +849,44 @@ stdenv.mkDerivation {
```
Now run:
```
```ShellSession
$ rustc --version
rustc 1.26.0-nightly (188e693b3 2018-03-26)
```
To see that you are using nightly.
## Using the Rust nightlies overlay
## Using the Rust nightlies overlay {#using-the-rust-nightlies-overlay}
Mozilla provides an overlay for nixpkgs to bring a nightly version of Rust into scope.
This overlay can _also_ be used to install recent unstable or stable versions
of Rust, if desired.
### Rust overlay installation
### Rust overlay installation {#rust-overlay-installation}
You can use this overlay by either changing your local nixpkgs configuration,
or by adding the overlay declaratively in a nix expression, e.g. in `configuration.nix`.
For more information see [#sec-overlays-install](the manual on installing overlays).
For more information see [the manual on installing overlays](#sec-overlays-install).
#### Imperative rust overlay installation
#### Imperative rust overlay installation {#imperative-rust-overlay-installation}
Clone [nixpkgs-mozilla](https://github.com/mozilla/nixpkgs-mozilla),
and create a symbolic link to the file
[rust-overlay.nix](https://github.com/mozilla/nixpkgs-mozilla/blob/master/rust-overlay.nix)
in the `~/.config/nixpkgs/overlays` directory.
$ git clone https://github.com/mozilla/nixpkgs-mozilla.git
$ mkdir -p ~/.config/nixpkgs/overlays
$ ln -s $(pwd)/nixpkgs-mozilla/rust-overlay.nix ~/.config/nixpkgs/overlays/rust-overlay.nix
```ShellSession
$ git clone https://github.com/mozilla/nixpkgs-mozilla.git
$ mkdir -p ~/.config/nixpkgs/overlays
$ ln -s $(pwd)/nixpkgs-mozilla/rust-overlay.nix ~/.config/nixpkgs/overlays/rust-overlay.nix
```
### Declarative rust overlay installation
### Declarative rust overlay installation {#declarative-rust-overlay-installation}
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))
@ -798,7 +898,7 @@ Add the following to your `configuration.nix`, `home-configuration.nix`, `shell.
Note that this will fetch the latest overlay version when rebuilding your system.
### Rust overlay usage
### Rust overlay usage {#rust-overlay-usage}
The overlay contains attribute sets corresponding to different versions of the rust toolchain, such as:
@ -812,11 +912,15 @@ For example, you might want to add `latest.rustChannels.stable.rust` to the list
Imperatively, the latest stable version can be installed with the following command:
$ nix-env -Ai nixpkgs.latest.rustChannels.stable.rust
```ShellSession
$ nix-env -Ai nixpkgs.latest.rustChannels.stable.rust
```
Or using the attribute with nix-shell:
$ nix-shell -p nixpkgs.latest.rustChannels.stable.rust
```ShellSession
$ nix-shell -p nixpkgs.latest.rustChannels.stable.rust
```
Substitute the `nixpkgs` prefix with `nixos` on NixOS.
To install the beta or nightly channel, "stable" should be substituted by

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

Loading…
Cancel
Save