Clone of https://github.com/NixOS/nixpkgs.git (to stress-test knotserver)
1# Contributing to Nixpkgs packages 2 3This document is for people wanting to contribute specifically to the package collection in Nixpkgs. 4See the [CONTRIBUTING.md](../CONTRIBUTING.md) document for more general information. 5 6## Overview 7 8- [`top-level`](./top-level): Entrypoints, package set aggregations 9 - [`impure.nix`](./top-level/impure.nix), [`default.nix`](./top-level/default.nix), [`config.nix`](./top-level/config.nix): Definitions for the evaluation entry point of `import <nixpkgs>` 10 - [`stage.nix`](./top-level/stage.nix), [`all-packages.nix`](./top-level/all-packages.nix), [`by-name-overlay.nix`](./top-level/by-name-overlay.nix), [`splice.nix`](./top-level/splice.nix): Definitions for the top-level attribute set made available through `import <nixpkgs> {…}` 11 - `*-packages.nix`, [`linux-kernels.nix`](./top-level/linux-kernels.nix), [`unixtools.nix`](./top-level/unixtools.nix): Aggregations of nested package sets defined in `development` 12 - [`aliases.nix`](./top-level/aliases.nix), [`python-aliases.nix`](./top-level/python-aliases.nix): Aliases for package definitions that have been renamed or removed 13 - `release*.nix`, [`make-tarball.nix`](./top-level/make-tarball.nix), [`packages-config.nix`](./top-level/packages-config.nix), [`metrics.nix`](./top-level/metrics.nix), [`nixpkgs-basic-release-checks.nix`](./top-level/nixpkgs-basic-release-checks.nix): Entry-points and utilities used by Hydra for continuous integration 14- [`development`](./development) 15 - `*-modules`, `*-packages`, `*-pkgs`: Package definitions for nested package sets 16 - All other directories loosely categorise top-level package definitions, see [category hierarchy][categories] 17- [`build-support`](./build-support): [Builders](https://nixos.org/manual/nixpkgs/stable/#part-builders) 18 - `fetch*`: [Fetchers](https://nixos.org/manual/nixpkgs/stable/#chap-pkgs-fetchers) 19- [`stdenv`](./stdenv): [Standard environment](https://nixos.org/manual/nixpkgs/stable/#part-stdenv) 20- [`pkgs-lib`](./pkgs-lib): Definitions for utilities that need packages but are not needed for packages 21- [`test`](./test): Tests not directly associated with any specific packages 22- [`by-name`](./by-name): Top-level packages organised by name ([docs](./by-name/README.md)) 23- All other directories loosely categorise top-level packages definitions, see [category hierarchy][categories] 24 25## Quick Start to Adding a Package 26 27We welcome new contributors of new packages to Nixpkgs, arguably the greatest software database known. However, each new package comes with a cost for the maintainers, Continuous Integration, caching servers and users downloading Nixpkgs. 28 29Before adding a new package, please consider the following questions: 30 31* Is the package ready for general use? We don't want to include projects that are too immature or are going to be abandoned immediately. In case of doubt, check with upstream. 32* Does the project have a clear license statement? Remember that software is unfree by default (all rights reserved), and merely providing access to the source code does not imply its redistribution. In case of doubt, ask upstream. 33* How realistic is it that it will be used by other people? It's good that nixpkgs caters to various niches, but if it's a niche of 5 people it's probably too small. 34* Are you willing to maintain the package? You should care enough about the package to be willing to keep it up and running for at least one complete Nixpkgs' release life-cycle. 35 * In case you are not able to maintain the package you wrote, you can seek someone to fill that role, effectively adopting the package. 36 37If any of these questions' answer is no, then you should probably not add the package. 38 39This section describes a general framework of understanding and exceptions might apply. 40 41Luckily it's pretty easy to maintain your own package set with Nix, which can then be added to the [Nix User Repository](https://github.com/nix-community/nur) project. 42 43--- 44 45Now that this is out of the way. To add a package to Nixpkgs: 46 471. Checkout the Nixpkgs source tree: 48 49 ```ShellSession 50 $ git clone https://github.com/NixOS/nixpkgs 51 $ cd nixpkgs 52 ``` 53 542. Create a package directory `pkgs/by-name/so/some-package` where `some-package` is the package name and `so` is the lowercased 2-letter prefix of the package name: 55 56 ```ShellSession 57 $ mkdir -p pkgs/by-name/so/some-package 58 ``` 59 60 For more detailed information, see [here](./by-name/README.md). 61 623. Create a `package.nix` file in the package directory, containing 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. 63 64 ```ShellSession 65 $ emacs pkgs/by-name/so/some-package/package.nix 66 $ git add pkgs/by-name/so/some-package/package.nix 67 ``` 68 69 If the package is written in a language other than C, you should use [the corresponding language framework](https://nixos.org/manual/nixpkgs/stable/#chap-language-support). 70 71 You can have a look at the existing Nix expressions under `pkgs/` to see how it’s done, some of which are also using the [category hierarchy](#category-hierarchy). 72 Here are some good ones: 73 74 - GNU Hello: [`pkgs/by-name/he/hello/package.nix`](./by-name/he/hello/package.nix). Trivial package, which specifies some `meta` attributes which is good practice. 75 76 - GNU cpio: [`pkgs/by-name/cp/cpio/package.nix`](./by-name/cp/cpio/package.nix). Also a simple package. The generic builder in `stdenv` does everything for you. It has no dependencies beyond `stdenv`. 77 78 - GNU Multiple Precision arithmetic library (GMP): [`pkgs/development/libraries/gmp`](development/libraries/gmp). Also done by the generic builder, but has a dependency on `m4`. 79 80 - Pan, a GTK-based newsreader: [`pkgs/by-name/pa/pan/package.nix`](./by-name/pa/pan/package.nix). Has an optional dependency on `gtkspell`, which is only built if `spellCheck` is `true`. 81 82 - Apache HTTPD: [`pkgs/servers/http/apache-httpd/2.4.nix`](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. 83 84 - buildMozillaMach: [`pkgs/applications/networking/browser/firefox/common.nix`](applications/networking/browsers/firefox/common.nix). A reusable build function for Firefox, Thunderbird and Librewolf. 85 86 - JDiskReport, a Java utility: [`pkgs/by-name/jd/jdiskreport/package.nix`](./by-name/jd/jdiskreport/package.nix). Nixpkgs doesn’t have a decent `stdenv` for Java yet so this is pretty ad-hoc. 87 88 - XML::Simple, a Perl module: [`pkgs/top-level/perl-packages.nix`](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. 89 90 - Adobe Reader: [`pkgs/applications/misc/adobe-reader/default.nix`](applications/misc/adobe-reader/default.nix). Shows how binary-only packages can be supported. In particular the `postFixup` phase uses `patchelf` to set the RUNPATH and ELF interpreter of the executables so that the right libraries are found at runtime. 91 92 Some notes: 93 94 - Add yourself as the maintainer of the package. 95 96 - All other [`meta`](https://nixos.org/manual/nixpkgs/stable/#chap-meta) attributes are optional, but it’s still a good idea to provide at least the `description`, `homepage` and [`license`](https://nixos.org/manual/nixpkgs/stable/#sec-meta-license). 97 98 - The exact syntax and semantics of the Nix expression language, including the built-in functions, are [Nix language reference](https://nixos.org/manual/nix/stable/language/). 99 1005. To test whether the package builds, run the following command from the root of the nixpkgs source tree: 101 102 ```ShellSession 103 $ nix-build -A some-package 104 ``` 105 106 where `some-package` should be the package name. 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. 107 1086. If you want to install the package into your profile (optional), do 109 110 ```ShellSession 111 $ nix-env -f . -iA libfoo 112 ``` 113 1147. 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. 115 116## Commit conventions 117 118- Make sure you read about the [commit conventions](../CONTRIBUTING.md#commit-conventions) common to Nixpkgs as a whole. 119 120- Format the commit messages in the following way: 121 122 ``` 123 (pkg-name): (from -> to | init at version | refactor | etc) 124 125 (Motivation for change. Link to release notes. Additional information.) 126 ``` 127 128 Examples: 129 130 * nginx: init at 2.0.1 131 * firefox: 54.0.1 -> 55.0 132 133 https://www.mozilla.org/en-US/firefox/55.0/releasenotes/ 134 135(using "→" instead of "->" is also accepted) 136 137## Category Hierarchy 138[categories]: #category-hierarchy 139 140Most top-level packages are organised in a loosely-categorised directory hierarchy in this directory. 141See the [overview](#overview) for which directories are part of this. 142 143This category hierarchy is partially deprecated and will be migrated away over time. 144The new `pkgs/by-name` directory ([docs](./by-name/README.md)) should be preferred instead. 145The category hierarchy may still be used for packages that should be imported using an alternate `callPackage`, such as `python3Packages.callPackage` or `libsForQt5.callPackage`. 146 147If that is the case for a new package, here are some rules for picking the right category. 148Many packages fall under several categories; what matters is the _primary_ purpose of a package. 149For example, the `libxml2` package builds both a library and some tools; but it’s a library foremost, so it goes under `pkgs/development/libraries`. 150 151<details> 152<summary>Categories</summary> 153 154**If it’s used to support _software development_:** 155 156- **If it’s a _library_ used by other packages:** 157 158 - `development/libraries` (e.g. `libxml2`) 159 160- **If it’s a _compiler_:** 161 162 - `development/compilers` (e.g. `gcc`) 163 164- **If it’s an _interpreter_:** 165 166 - `development/interpreters` (e.g. `guile`) 167 168- **If it’s a (set of) development _tool(s)_:** 169 170 - **If it’s a _parser generator_ (including lexers):** 171 172 - `development/tools/parsing` (e.g. `bison`, `flex`) 173 174 - **If it’s a _build manager_:** 175 176 - `development/tools/build-managers` (e.g. `gnumake`) 177 178 - **If it’s a _language server_:** 179 180 - `development/tools/language-servers` (e.g. `ccls` or `nil`) 181 182 - **Else:** 183 184 - `development/tools/misc` (e.g. `binutils`) 185 186- **Else:** 187 188 - `development/misc` 189 190**If it’s a (set of) _tool(s)_:** 191 192(A tool is a relatively small program, especially one intended to be used non-interactively.) 193 194- **If it’s for _networking_:** 195 196 - `tools/networking` (e.g. `wget`) 197 198- **If it’s for _text processing_:** 199 200 - `tools/text` (e.g. `diffutils`) 201 202- **If it’s a _system utility_, i.e., something related or essential to the operation of a system:** 203 204 - `tools/system` (e.g. `cron`) 205 206- **If it’s an _archiver_ (which may include a compression function):** 207 208 - `tools/archivers` (e.g. `zip`, `tar`) 209 210- **If it’s a _compression_ program:** 211 212 - `tools/compression` (e.g. `gzip`, `bzip2`) 213 214- **If it’s a _security_-related program:** 215 216 - `tools/security` (e.g. `nmap`, `gnupg`) 217 218- **Else:** 219 220 - `tools/misc` 221 222**If it’s a _shell_:** 223 224- `shells` (e.g. `bash`) 225 226**If it’s a _server_:** 227 228- **If it’s a web server:** 229 230 - `servers/http` (e.g. `apache-httpd`) 231 232- **If it’s an implementation of the X Windowing System:** 233 234 - `servers/x11` (e.g. `xorg` — this includes the client libraries and programs) 235 236- **Else:** 237 238 - `servers/misc` 239 240**If it’s a _desktop environment_:** 241 242- `desktops` (e.g. `kde`, `gnome`, `enlightenment`) 243 244**If it’s a _window manager_:** 245 246- `applications/window-managers` (e.g. `awesome`, `stumpwm`) 247 248**If it’s an _application_:** 249 250A (typically large) program with a distinct user interface, primarily used interactively. 251 252- **If it’s a _version management system_:** 253 254 - `applications/version-management` (e.g. `subversion`) 255 256- **If it’s a _terminal emulator_:** 257 258 - `applications/terminal-emulators` (e.g. `alacritty` or `rxvt` or `termite`) 259 260- **If it’s a _file manager_:** 261 262 - `applications/file-managers` (e.g. `mc` or `ranger` or `pcmanfm`) 263 264- **If it’s for _video playback / editing_:** 265 266 - `applications/video` (e.g. `vlc`) 267 268- **If it’s for _graphics viewing / editing_:** 269 270 - `applications/graphics` (e.g. `gimp`) 271 272- **If it’s for _networking_:** 273 274 - **If it’s a _mailreader_:** 275 276 - `applications/networking/mailreaders` (e.g. `thunderbird`) 277 278 - **If it’s a _newsreader_:** 279 280 - `applications/networking/newsreaders` (e.g. `pan`) 281 282 - **If it’s a _web browser_:** 283 284 - `applications/networking/browsers` (e.g. `firefox`) 285 286 - **Else:** 287 288 - `applications/networking/misc` 289 290- **Else:** 291 292 - `applications/misc` 293 294**If it’s _data_ (i.e., does not have a straight-forward executable semantics):** 295 296- **If it’s a _font_:** 297 298 - `data/fonts` 299 300- **If it’s an _icon theme_:** 301 302 - `data/icons` 303 304- **If it’s related to _SGML/XML processing_:** 305 306 - **If it’s an _XML DTD_:** 307 308 - `data/sgml+xml/schemas/xml-dtd` (e.g. `docbook`) 309 310 - **If it’s an _XSLT stylesheet_:** 311 312 (Okay, these are executable...) 313 314 - `data/sgml+xml/stylesheets/xslt` (e.g. `docbook-xsl`) 315 316- **If it’s a _theme_ for a _desktop environment_, a _window manager_ or a _display manager_:** 317 318 - `data/themes` 319 320**If it’s a _game_:** 321 322- `games` 323 324**Else:** 325 326- `misc` 327 328</details> 329 330# Conventions 331 332The 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. 333 334## Package naming 335 336In Nixpkgs, there are generally three different names associated with a package: 337 338- The `pname` attribute of the derivation. This is what most users see, in particular when using `nix-env`. 339 340- The attribute name used for the package in the [`pkgs/by-name` structure](./by-name/README.md) or in [`all-packages.nix`](./top-level/all-packages.nix), and when passing it as a dependency in recipes. 341 342- The filename for (the directory containing) the Nix expression. 343 344Most of the time, these are the same. For instance, the package `e2fsprogs` has a `pname` attribute `"e2fsprogs"`, is bound to the attribute name `e2fsprogs` in `all-packages.nix`, and the Nix expression is in `pkgs/os-specific/linux/e2fsprogs/default.nix`. 345 346Follow these guidelines: 347 348- For the `pname` attribute: 349 350 - It _should_ be identical to the upstream package name. 351 352 - It _must not_ contain uppercase letters. 353 354 Example: Use `"mplayer"` instead of `"MPlayer"` 355 356- For the package attribute name: 357 358 - It _must_ be a valid identifier in Nix. 359 360 - If the `pname` starts with a digit, the attribute name _should_ be prefixed with an underscore. Otherwise the attribute name _should not_ be prefixed with an underline. 361 362 Example: The corresponding attribute name for `0ad` should be `_0ad`. 363 364 - New attribute names _should_ be the same as the value in `pname`. 365 366 Hyphenated names _should not_ be converted to [snake case](https://en.wikipedia.org/wiki/Snake_case) or [camel case](https://en.wikipedia.org/wiki/Camel_case). 367 This was done historically, but is not necessary any more. 368 [The Nix language allows dashes in identifiers since 2012](https://github.com/NixOS/nix/commit/95c74eae269b2b9e4bc514581b5caa1d80b54acc). 369 370 - If there are multiple versions of a package, this _should_ be reflected in the attribute names in `all-packages.nix`. 371 372 Example: `json-c_0_9` and `json-c_0_11` 373 374 If there is an obvious “default” version, make an extra attribute. 375 376 Example: `json-c = json-c_0_9;` 377 378 See also [versioning][versioning]. 379 380## Versioning 381[versioning]: #versioning 382 383These are the guidelines the `version` attribute of a package: 384 385- It _must_ start with a digit. This is required for backwards-compatibility with [how `nix-env` parses derivation names](https://nix.dev/manual/nix/latest/command-ref/nix-env#selectors). 386 387 Example: `"0.3.1rc2"` or `"0-unstable-1970-01-01"` 388 389- If a package is a commit from a repository without a version assigned, then the `version` attribute _should_ be the latest upstream version preceding that commit, followed by `-unstable-` and the date of the (fetched) commit. The date _must_ be in `"YYYY-MM-DD"` format. 390 391 Example: Given a project had its latest releases `2.2` in November 2021 and `3.0` in January 2022, a commit authored on March 15, 2022 for an upcoming bugfix release `2.2.1` would have `version = "2.2-unstable-2022-03-15"`. 392 393- If a project has no suitable preceding releases - e.g., no versions at all, or an incompatible versioning or tagging scheme - then the latest upstream version in the above schema should be `0`. 394 395 Example: Given a project that has no tags or released versions at all, or applies versionless tags like `latest` or `YYYY-MM-DD-Build`, a commit authored on March 15, 2022 would have `version = "0-unstable-2022-03-15"`. 396 397Because 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. 398 399If there is only one version of a package, its Nix expression should be named (e.g) `pkgs/by-name/xy/xyz/package.nix`. If there are multiple versions, this should be reflected in the attribute name. If you wish to share code between the Nix expressions of each version, you cannot rely upon `pkgs/by-name`'s automatic attribute creation, and must create the attributes yourself in `all-packages.nix`. See also [`pkgs/by-name/README.md`'s section on this topic](https://github.com/NixOS/nixpkgs/blob/master/pkgs/by-name/README.md#recommendation-for-new-packages-with-multiple-versions). 400 401## Meta attributes 402 403The `meta` attribute set should always be placed last in the derivativion and any other "meta"-like attribute sets like `passthru` should be written before it. 404 405* `meta.description` must: 406 * Be short, just one sentence. 407 * Be capitalized. 408 * Not start with the definite or an indefinite article. 409 * Not start with the package name. 410 * More generally, it should not refer to the package name. 411 * Not end with a period (or any punctuation for that matter). 412 * Provide factual information. 413 * Avoid subjective language. 414* `meta.license` must be set and match the upstream license. 415 * If there is no upstream license, `meta.license` should default to `lib.licenses.unfree`. 416 * If in doubt, try to contact the upstream developers for clarification. 417* `meta.mainProgram` must be set to the name of the executable which facilitates the primary function or purpose of the package, if there is such an executable in `$bin/bin/` (or `$out/bin/`, if there is no `"bin"` output). 418 * Packages that only have a single executable in the applicable directory above should set `meta.mainProgram`. For example, the package `ripgrep` only has a single executable `rg` under `$out/bin/`, so `ripgrep.meta.mainProgram` is set to `"rg"`. 419 * Packages like `polkit_gnome` that have no executables in the applicable directory should not set `meta.mainProgram`. 420 * Packages like `e2fsprogs` that have multiple executables, none of which can be considered the main program, should not set `meta.mainProgram`. 421 * Packages which are not primarily used for a single executable do not need to set `meta.mainProgram`. 422 * Always prefer using a hardcoded string (don't use `pname`, for example). 423 * When in doubt, ask for reviewer input. 424* `meta.maintainers` must be set for new packages. 425 426See the Nixpkgs manual for more details on [standard meta-attributes](https://nixos.org/nixpkgs/manual/#sec-standard-meta-attributes). 427 428## Import From Derivation 429 430[Import From Derivation](https://nixos.org/manual/nix/unstable/language/import-from-derivation) (IFD) is disallowed in Nixpkgs for performance reasons: 431[Hydra](https://github.com/NixOS/hydra) evaluates the entire package set, and sequential builds during evaluation would increase evaluation times to become impractical. 432 433Import From Derivation can be worked around in some cases by committing generated intermediate files to version control and reading those instead. 434 435## Sources 436 437Always fetch source files using [Nixpkgs fetchers](https://nixos.org/manual/nixpkgs/unstable/#chap-pkgs-fetchers). 438Use reproducible sources with a high degree of availability. 439Prefer protocols that support proxies. 440 441A list of schemes for `mirror://` URLs can be found in [`pkgs/build-support/fetchurl/mirrors.nix`](build-support/fetchurl/mirrors.nix), and is supported by [`fetchurl`](https://nixos.org/manual/nixpkgs/unstable/#fetchurl). 442Other fetchers which end up relying on `fetchurl` may also support mirroring. 443 444The preferred source hash type is `sha256`. 445 446Examples going from bad to best practices: 447 448- Bad: Uses `git://` which won't be proxied. 449 450 ```nix 451 { 452 src = fetchgit { 453 url = "git://github.com/NixOS/nix.git"; 454 rev = "1f795f9f44607cc5bec70d1300150bfefcef2aae"; 455 hash = "sha256-7D4m+saJjbSFP5hOwpQq2FGR2rr+psQMTcyb1ZvtXsQ="; 456 }; 457 } 458 ``` 459 460- Better: This is ok, but an archive fetch will still be faster. 461 462 ```nix 463 { 464 src = fetchgit { 465 url = "https://github.com/NixOS/nix.git"; 466 rev = "1f795f9f44607cc5bec70d1300150bfefcef2aae"; 467 hash = "sha256-7D4m+saJjbSFP5hOwpQq2FGR2rr+psQMTcyb1ZvtXsQ="; 468 }; 469 } 470 ``` 471 472- Best: Fetches a snapshot archive for the given revision. 473 474 ```nix 475 { 476 src = fetchFromGitHub { 477 owner = "NixOS"; 478 repo = "nix"; 479 rev = "1f795f9f44607cc5bec70d1300150bfefcef2aae"; 480 hash = "sha256-7D4m+saJjbSFP5hOwpQq2FGR2rr+psQMTcyb1ZvtXsQ="; 481 }; 482 } 483 ``` 484 485> [!Note] 486> When fetching from GitHub, always reference revisions by their full commit hash. 487> GitHub shares commit hashes among all forks and returns `404 Not Found` when a short commit hash is ambiguous. 488> It already happened in Nixpkgs for short, 6-character commit hashes. 489> 490> Pushing large amounts of auto generated commits into forks is a practical vector for a denial-of-service attack, and was already [demonstrated against GitHub Actions Beta](https://blog.teddykatz.com/2019/11/12/github-actions-dos.html). 491 492## Patches 493 494Sometimes, changes are needed to the source to allow building a derivation in nixpkgs, or to get earlier access to an upstream fix or improvement. 495When using the `patches` parameter to `mkDerivation`, make sure the patch name clearly describes the reason for the patch, or add a comment. 496 497> [!Note] 498> The version of the package does not need to be changed just because a patch is applied. Declarative package installations don't depend on the version, while imperative `nix-env` installations can use [`upgrade --eq/leq/--always`](https://nix.dev/manual/nix/2.25/command-ref/nix-env/upgrade#flags). 499> 500> See [Versioning](#versioning) for details on package versioning. 501 502### Fetching patches 503 504In the interest of keeping our maintenance burden and the size of Nixpkgs to a minimum, patches already merged upstream or published elsewhere _should_ be retrieved using `fetchpatch2`: 505 506```nix 507{ 508 patches = [ 509 (fetchpatch2 { 510 name = "fix-check-for-using-shared-freetype-lib.patch"; 511 url = "https://cgit.ghostscript.com/cgi-bin/cgit.cgi/ghostpdl.git/patch/?id=8f5d28536e4518716fdfe974e580194c8f57871d"; 512 hash = "sha256-uRcxaCjd+WAuGrXOmGfFeu79cUILwkRdBu48mwcBE7g="; 513 }) 514 ]; 515} 516``` 517 518If a patch is available online but does not cleanly apply, it can be modified in some fixed ways by using additional optional arguments for `fetchpatch2`. Check [the `fetchpatch` reference](https://nixos.org/manual/nixpkgs/unstable/#fetchpatch) for details. 519 520When adding patches in this manner you should be reasonably sure that the used URL is stable. Patches referencing open pull requests will change when the PR is updated and code forges (such as GitHub) usually garbage collect commits that are no longer reachable due to rebases/amends. 521 522### Vendoring patches 523 524In the following cases, a `.patch` file _should_ be added to Nixpkgs repository, instead of retrieved: 525 526- solves problems unique to packaging in Nixpkgs 527- cannot be fetched easily 528- has a high chance to disappear in the future due to unstable or unreliable URLs 529 530The latter avoids link rot when the upstream abandons, squashes or rebases their change, in which case the commit may get garbage-collected. 531 532```nix 533{ 534 patches = [ ./0001-add-missing-include.patch ]; 535} 536``` 537 538If you do need to do create this sort of patch file, one way to do so is with git: 539 5401. Move to the root directory of the source code you're patching. 541 542 ```ShellSession 543 $ cd the/program/source 544 ``` 545 5462. If a git repository is not already present, create one and stage all of the source files. 547 548 ```ShellSession 549 $ git init 550 $ git add . 551 ``` 552 5533. Edit some files to make whatever changes need to be included in the patch. 554 5554. Use git to create a diff, and pipe the output to a patch file: 556 557 ```ShellSession 558 $ git diff -a > nixpkgs/pkgs/the/package/0001-changes.patch 559 ``` 560 561## Deprecating/removing packages 562 563There is currently no policy when to remove a package. 564 565Before removing a package, one should try to find a new maintainer or fix smaller issues first. 566 567### Steps to remove a package from Nixpkgs 568 569We use jbidwatcher as an example for a discontinued project here. 570 5711. Have Nixpkgs checked out locally and up to date. 5721. Create a new branch for your change, e.g. `git checkout -b jbidwatcher` 5731. Remove the actual package including its directory, e.g. `git rm -rf pkgs/applications/misc/jbidwatcher` 5741. Remove the package from the list of all packages (`pkgs/top-level/all-packages.nix`). 5751. Add an alias for the package name in `pkgs/top-level/aliases.nix` (There is also `pkgs/applications/editors/vim/plugins/aliases.nix`. Package sets typically do not have aliases, so we can't add them there.) 576 577 For example in this case: 578 579 ```nix 580 { 581 jbidwatcher = throw "jbidwatcher was discontinued in march 2021"; # added 2021-03-15 582 } 583 ``` 584 585 The throw message should explain in short why the package was removed for users that still have it installed. 586 5871. Test if the changes introduced any issues by running `nix-env -qaP -f . --show-trace`. It should show the list of packages without errors. 5881. Commit the changes. Explain again why the package was removed. If it was declared discontinued upstream, add a link to the source. 589 590 ```ShellSession 591 $ git add pkgs/applications/misc/jbidwatcher/default.nix pkgs/top-level/all-packages.nix pkgs/top-level/aliases.nix 592 $ git commit 593 ``` 594 595 Example commit message: 596 597 ``` 598 jbidwatcher: remove 599 600 project was discontinued in march 2021. the program does not work anymore because ebay changed the login. 601 602 https://web.archive.org/web/20210315205723/http://www.jbidwatcher.com/ 603 ``` 604 6051. Push changes to your GitHub fork with `git push` 6061. Create a pull request against Nixpkgs. Mention the package maintainer. 607 608This is how the pull request looks like in this case: [https://github.com/NixOS/nixpkgs/pull/116470](https://github.com/NixOS/nixpkgs/pull/116470) 609 610## Package tests 611 612To run the main types of tests locally: 613 614- Run package-internal tests with `nix-build --attr pkgs.PACKAGE.passthru.tests` 615- Run [NixOS tests](https://nixos.org/manual/nixos/unstable/#sec-nixos-tests) with `nix-build --attr nixosTests.NAME`, where `NAME` is the name of the test listed in `nixos/tests/all-tests.nix` 616- Run [global package tests](https://nixos.org/manual/nixpkgs/unstable/#sec-package-tests) with `nix-build --attr tests.PACKAGE`, where `PACKAGE` is the name of the test listed in `pkgs/test/default.nix` 617- See `lib/tests/NAME.nix` for instructions on running specific library tests 618 619Tests are important to ensure quality and make reviews and automatic updates easy. 620 621The following types of tests exists: 622 623* [NixOS **module tests**](https://nixos.org/manual/nixos/stable/#sec-nixos-tests), which spawn one or more NixOS VMs. They exercise both NixOS modules and the packaged programs used within them. For example, a NixOS module test can start a web server VM running the `nginx` module, and a client VM running `curl` or a graphical `firefox`, and test that they can talk to each other and display the correct content. 624* Nix **package tests** are a lightweight alternative to NixOS module tests. They should be used to create simple integration tests for packages, but cannot test NixOS services, and some programs with graphical user interfaces may also be difficult to test with them. 625* The **`checkPhase` of a package**, which should execute the unit tests that are included in the source code of a package. 626 627Here in the nixpkgs manual we describe mostly _package tests_; for _module tests_ head over to the corresponding [section in the NixOS manual](https://nixos.org/manual/nixos/stable/#sec-nixos-tests). 628 629### Writing inline package tests 630 631For very simple tests, they can be written inline: 632 633```nix 634{ /* ... , */ yq-go }: 635 636buildGoModule rec { 637 # … 638 639 passthru.tests = { 640 simple = runCommand "${pname}-test" {} '' 641 echo "test: 1" | ${yq-go}/bin/yq eval -j > $out 642 [ "$(cat $out | tr -d $'\n ')" = '{"test":1}' ] 643 ''; 644 }; 645} 646``` 647 648Any derivation can be specified as a test, even if it's in a different file. 649Such a derivation that implements a test can depend on the package under test, even in the presence of `overrideAttrs`. 650 651In the following example, `(my-package.overrideAttrs f).passthru.tests` will work as expected, as long as the definition of `tests` does not rely on the original `my-package` or overrides all occurrences of `my-package`: 652 653```nix 654# my-package/default.nix 655{ stdenv, callPackage }: 656stdenv.mkDerivation (finalAttrs: { 657 # ... 658 passthru.tests.example = callPackage ./example.nix { my-package = finalAttrs.finalPackage; }; 659}) 660``` 661 662```nix 663# my-package/example.nix 664{ runCommand, lib, my-package, ... }: 665runCommand "my-package-test" { 666 nativeBuildInputs = [ my-package ]; 667 src = lib.sources.sourcesByRegex ./. [ ".*.in" ".*.expected" ]; 668} '' 669 my-package --help 670 my-package <example.in >example.actual 671 diff -U3 --color=auto example.expected example.actual 672 mkdir $out 673'' 674``` 675 676### Writing larger package tests 677[larger-package-tests]: #writing-larger-package-tests 678 679This is an example using the `phoronix-test-suite` package with the current best practices. 680 681Add the tests in `passthru.tests` to the package definition like this: 682 683```nix 684{ stdenv, lib, fetchurl, callPackage }: 685 686stdenv.mkDerivation { 687 # … 688 689 passthru.tests = { 690 simple-execution = callPackage ./tests.nix { }; 691 }; 692 693 meta = { /* … */ }; 694} 695``` 696 697Create `tests.nix` in the package directory: 698 699```nix 700{ runCommand, phoronix-test-suite }: 701 702let 703 inherit (phoronix-test-suite) pname version; 704in 705 706runCommand "${pname}-tests" { meta.timeout = 60; } 707 '' 708 # automatic initial setup to prevent interactive questions 709 ${phoronix-test-suite}/bin/phoronix-test-suite enterprise-setup >/dev/null 710 # get version of installed program and compare with package version 711 if [[ `${phoronix-test-suite}/bin/phoronix-test-suite version` != *"${version}"* ]]; then 712 echo "Error: program version does not match package version" 713 exit 1 714 fi 715 # run dummy command 716 ${phoronix-test-suite}/bin/phoronix-test-suite dummy_module.dummy-command >/dev/null 717 # needed for Nix to register the command as successful 718 touch $out 719 '' 720``` 721 722### Running package tests 723 724You can run these tests with: 725 726```ShellSession 727$ cd path/to/nixpkgs 728$ nix-build -A phoronix-test-suite.tests 729``` 730 731### Examples of package tests 732 733Here are examples of package tests: 734 735- [Jasmin compile test](by-name/ja/jasmin/test-assemble-hello-world/default.nix) 736- [Lobster compile test](development/compilers/lobster/test-can-run-hello-world.nix) 737- [Spacy annotation test](development/python-modules/spacy/annotation-test/default.nix) 738- [Libtorch test](development/libraries/science/math/libtorch/test/default.nix) 739- [Multiple tests for nanopb](./by-name/na/nanopb/package.nix) 740 741### Linking NixOS module tests to a package 742 743Like [package tests][larger-package-tests] as shown above, [NixOS module tests](https://nixos.org/manual/nixos/stable/#sec-nixos-tests) can also be linked to a package, so that the tests can be easily run when changing the related package. 744 745For example, assuming we're packaging `nginx`, we can link its module test via `passthru.tests`: 746 747```nix 748{ stdenv, lib, nixosTests }: 749 750stdenv.mkDerivation { 751 # ... 752 753 passthru.tests = { 754 nginx = nixosTests.nginx; 755 }; 756 757 # ... 758} 759``` 760 761## Automatic package updates 762[automatic-package-updates]: #automatic-package-updates 763 764Nixpkgs periodically tries to update all packages that have a `passthru.updateScript` attribute. 765 766> [!Note] 767> A common pattern is to use the [`nix-update-script`](../pkgs/by-name/ni/nix-update/nix-update-script.nix) attribute provided in Nixpkgs, which runs [`nix-update`](https://github.com/Mic92/nix-update): 768> 769> ```nix 770> { stdenv, nix-update-script }: 771> stdenv.mkDerivation { 772> # ... 773> passthru.updateScript = nix-update-script { }; 774> } 775> ``` 776> 777> For simple packages, this is often enough, and will ensure that the package is updated automatically by [`nixpkgs-update`](https://github.com/nix-community/nixpkgs-update) when a new version is released. 778> The [update bot](https://nix-community.org/update-bot) runs periodically to attempt to automatically update packages, and will run `passthru.updateScript` if set. 779> While not strictly necessary if the project is listed on [Repology](https://repology.org), using `nix-update-script` allows the package to update via many more sources (e.g. GitHub releases). 780 781The `passthru.updateScript` attribute can contain one of the following: 782 783- an executable file, either on the file system: 784 785 ```nix 786 { stdenv }: 787 stdenv.mkDerivation { 788 # ... 789 passthru.updateScript = ./update.sh; 790 } 791 ``` 792 793 or inside the expression itself: 794 795 ```nix 796 { stdenv, writeScript }: 797 stdenv.mkDerivation { 798 # ... 799 passthru.updateScript = writeScript "update-zoom-us" '' 800 #!/usr/bin/env nix-shell 801 #!nix-shell -i bash -p curl pcre2 common-updater-scripts 802 803 set -eu -o pipefail 804 805 version="$(curl -sI https://zoom.us/client/latest/zoom_x86_64.tar.xz | grep -Fi 'Location:' | pcre2grep -o1 '/(([0-9]\.?)+)/')" 806 update-source-version zoom-us "$version" 807 ''; 808 } 809 ``` 810 811- a list, a script file followed by arguments to be passed to it: 812 813 ```nix 814 { stdenv }: 815 stdenv.mkDerivation { 816 # ... 817 passthru.updateScript = [ ../../update.sh pname "--requested-release=unstable" ]; 818 } 819 ``` 820 821- an attribute set containing: 822 - `command` 823 824 A string or list in the [format expected by `passthru.updateScript`][automatic-package-updates] 825 826 - `attrPath` (optional) 827 828 A string containing the canonical attribute path for the package. 829 830 If present, it will be passed to the update script instead of the attribute path on which the package was discovered during Nixpkgs traversal. 831 832 - `supportedFeatures` (optional) 833 834 A list of the [extra features the script supports][supported-features]. 835 836 ```nix 837 { stdenv }: 838 stdenv.mkDerivation rec { 839 pname = "my-package"; 840 # ... 841 passthru.updateScript = { 842 command = [ ../../update.sh pname ]; 843 attrPath = pname; 844 supportedFeatures = [ /* ... */ ]; 845 }; 846 } 847 ``` 848 849### How are update scripts executed? 850 851Update scripts are to be invoked by the [automatic package update script](../maintainers/scripts/update.nix). 852You can run `nix-shell maintainers/scripts/update.nix` in the root of Nixpkgs repository for information on how to use it. 853`update.nix` offers several modes for selecting packages to update, and it will execute update scripts for all matched packages that have an `updateScript` attribute. 854 855Each update script will be passed the following environment variables: 856 857- [`UPDATE_NIX_NAME`] – content of the `name` attribute of the updated package 858- [`UPDATE_NIX_PNAME`] – content of the `pname` attribute of the updated package 859- [`UPDATE_NIX_OLD_VERSION`] – content of the `version` attribute of the updated package 860- [`UPDATE_NIX_ATTR_PATH`] – attribute path the `update.nix` discovered the package on (or the package's specified `attrPath` when available). Example: `pantheon.elementary-terminal` 861 862> [!Note] 863> An update script will be usually run from the root of the Nixpkgs repository, but you should not rely on that. 864> Also note that `update.nix` executes update scripts in parallel by default, so you should avoid running `git commit` or any other commands that cannot handle that. 865 866While update scripts should not create commits themselves, `update.nix` supports automatically creating commits when running it with `--argstr commit true`. 867If you need to customize commit message, you can have the update script implement the `commit` feature. 868 869### Supported features 870[update-script-supported-features]: #supported-features 871 872- `commit` 873 874 This feature allows update scripts to *ask* `update.nix` to create Git commits. 875 876 When support of this feature is declared, whenever the update script exits with `0` return status, it is expected to print a JSON list containing an object described below for each updated attribute to standard output. 877 Example: 878 879 ```json 880 [ 881 { 882 "attrPath": "volume_key", 883 "oldVersion": "0.3.11", 884 "newVersion": "0.3.12", 885 "files": [ 886 "/path/to/nixpkgs/pkgs/development/libraries/volume-key/default.nix" 887 ] 888 } 889 ] 890 ``` 891 ::: 892 893 When `update.nix` is run with `--argstr commit true`, it will create a separate commit for each of the objects. 894 An empty list can be returned when the script did not update any files; for example, when the package is already at the latest version. 895 896 The commit object contains the following values: 897 898 - `attrPath` – a string containing the attribute path 899 - `oldVersion` – a string containing the old version 900 - `newVersion` – a string containing the new version 901 - `files` – a non-empty list of file paths (as strings) to add to the commit 902 - `commitBody` (optional) – a string with extra content to be appended to the default commit message (useful for adding changelog links) 903 - `commitMessage` (optional) – a string to use instead of the default commit message 904 905 If the returned list contains exactly one object (e.g. `[{}]`), all values are optional and will be determined automatically. 906 907## Reviewing contributions 908 909### Package updates 910 911A 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. 912 913It can happen that non-trivial updates include patches or more complex changes. 914 915Reviewing process: 916 917- Ensure that the package versioning [fits the guidelines](#versioning). 918- Ensure that the commit text [fits the guidelines](../CONTRIBUTING.md#commit-conventions). 919- Ensure that the package maintainers are notified. 920 - The continuous integration system will make GitHub notify users based on the submitted changes, but it can happen that it misses some of the package maintainers. 921- Ensure that the meta field information [fits the guidelines](#meta-attributes) and is correct: 922 - License can change with version updates, so it should be checked to match the upstream license. 923 - 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. 924- Ensure that the code contains no typos. 925- Build the package locally. 926 - 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. 927 - 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. 928 929 ```ShellSession 930 $ git fetch origin nixos-unstable 931 $ git fetch origin pull/PRNUMBER/head 932 $ git rebase --onto nixos-unstable BASEBRANCH FETCH_HEAD 933 ``` 934 935 - The first command fetches the nixos-unstable branch. 936 - 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. 937 - The third command rebases the pull request changes to the nixos-unstable branch. 938 - 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. 939 940 ```ShellSession 941 $ nix-shell -p nixpkgs-review --run "nixpkgs-review pr PRNUMBER" 942 ``` 943- Run every binary. 944 945Sample template for a package update review is provided below. 946 947```markdown 948##### Reviewed points 949 950- [ ] package name fits guidelines 951- [ ] package version fits guidelines 952- [ ] package builds on ARCHITECTURE 953- [ ] executables tested on ARCHITECTURE 954- [ ] all depending packages build 955- [ ] patches have a comment describing either the upstream URL or a reason why the patch wasn't upstreamed 956- [ ] patches that are remotely available are fetched rather than vendored 957 958##### Possible improvements 959 960##### Comments 961``` 962 963### New packages 964 965New packages are a common type of pull requests. These pull requests consists in adding a new nix-expression for a package. 966 967Review process: 968 969- Ensure that all file paths [fit the guidelines](../CONTRIBUTING.md#file-naming-and-organisation). 970- Ensure that the package name and version [fits the guidelines](#package-naming). 971- Ensure that the package versioning [fits the guidelines](#versioning). 972- Ensure that the commit text [fits the guidelines](../CONTRIBUTING.md#commit-conventions). 973- Ensure that the meta fields [fits the guidelines](#meta-attributes) and contain the correct information: 974 - License must match the upstream license. 975 - Platforms should be set (or the package will not get binary substitutes). 976 - Maintainers must be set. This can be the package submitter or a community member that accepts taking up maintainership of the package. 977 - The `meta.mainProgram` must be set if a main executable exists. 978- Report detected typos. 979- Ensure the package source: 980 - Uses `mirror://` URLs when available. 981 - Uses the most appropriate functions (e.g. packages from GitHub should use `fetchFromGitHub`). 982- Build the package locally. 983- Run every binary. 984 985Sample template for a new package review is provided below. 986 987```markdown 988##### Reviewed points 989 990- [ ] package path fits guidelines 991- [ ] package name fits guidelines 992- [ ] package version fits guidelines 993- [ ] package builds on ARCHITECTURE 994- [ ] executables tested on ARCHITECTURE 995- [ ] `meta.description` is set and fits guidelines 996- [ ] `meta.license` fits upstream license 997- [ ] `meta.platforms` is set 998- [ ] `meta.maintainers` is set 999- [ ] `meta.mainProgram` is set, if applicable. 1000- [ ] build time only dependencies are declared in `nativeBuildInputs` 1001- [ ] source is fetched using the appropriate function 1002- [ ] the list of `phases` is not overridden 1003- [ ] when a phase (like `installPhase`) is overridden it starts with `runHook preInstall` and ends with `runHook postInstall`. 1004- [ ] patches have a comment describing either the upstream URL or a reason why the patch wasn't upstreamed 1005- [ ] patches that are remotely available are fetched rather than vendored 1006 1007##### Possible improvements 1008 1009##### Comments 1010``` 1011 1012## Security 1013 1014### Submitting security fixes 1015[security-fixes]: #submitting-security-fixes 1016 1017Security fixes are submitted in the same way as other changes and thus the same guidelines apply. 1018 1019- If a new version fixing the vulnerability has been released, update the package; 1020- 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. 1021 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.: 1022 1023 ```nix 1024 (fetchpatch { 1025 name = "CVE-2019-11068.patch"; 1026 url = "https://gitlab.gnome.org/GNOME/libxslt/commit/e03553605b45c88f0b4b2980adfbbb8f6fca2fd6.patch"; 1027 hash = "sha256-SEKe/8HcW0UBHCfPTTOnpRlzmV2nQPPeL6HOMxBZd14="; 1028 }) 1029 ``` 1030 1031If 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. 1032 1033Critical security fixes may by-pass the staging branches and be delivered directly to release branches such as `master` and `release-*`. 1034 1035### Vulnerability Roundup 1036 1037#### Issues 1038 1039Vulnerable packages in Nixpkgs are managed using issues. 1040Currently opened ones can be found using the following: 1041 1042[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) 1043 1044Each issue correspond to a vulnerable version of a package; As a consequence: 1045 1046- One issue can contain several CVEs; 1047- One CVE can be shared across several issues; 1048- A single package can be concerned by several issues. 1049 1050 1051A "Vulnerability roundup" issue usually respects the following format: 1052 1053```txt 1054<link to relevant package search on search.nix.gsc.io>, <link to relevant files in Nixpkgs on GitHub> 1055 1056<list of related CVEs, their CVSS score, and the impacted NixOS version> 1057 1058<list of the scanned Nixpkgs versions> 1059 1060<list of relevant contributors> 1061``` 1062 1063Note that there can be an extra comment containing links to previously reported (and still open) issues for the same package. 1064 1065 1066#### Triaging and Fixing 1067 1068**Note**: An issue can be a "false positive" (i.e. automatically opened, but without the package it refers to being actually vulnerable). 1069If 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. 1070 1071If you are investigating a "true positive": 1072 1073- Find the earliest patched version or a code patch in the CVE details; 1074- Is the issue already patched (version up-to-date or patch applied manually) in Nixpkgs's `master` branch? 1075 - **No**: 1076 - [Submit a security fix][security-fixes]; 1077 - Once the fix is merged into `master`, [submit the change to the vulnerable release branch(es)](../CONTRIBUTING.md#how-to-backport-pull-requests); 1078 - **Yes**: [Backport the change to the vulnerable release branch(es)](../CONTRIBUTING.md#how-to-backport-pull-requests). 1079- When the patch has made it into all the relevant branches (`master`, and the vulnerable releases), close the relevant issue(s).