polish: nixpkgs module system - the import function

This commit is contained in:
Ryan Yin 2024-12-10 21:35:54 +08:00
parent 6ea7ef8215
commit 72ec7f2b0d
2 changed files with 21 additions and 9 deletions

View File

@ -17,8 +17,8 @@ The functions of these four files are:
- `flake.lock`: An automatically generated version-lock file that records all input
sources, hash values, and version numbers of the entire flake to ensure reproducibility.
- `flake.nix`: The entry file that will be recognized and deployed when executing
`sudo nixos-rebuild switch`. See [Flakes - NixOS Wiki](https://wiki.nixos.org/wiki/Flakes)
for all options of flake.nix.
`sudo nixos-rebuild switch`. See
[Flakes - NixOS Wiki](https://wiki.nixos.org/wiki/Flakes) for all options of flake.nix.
- `configuration.nix`: Imported as a Nix module in flake.nix, all system-level
configuration is currently written here. See
[Configuration - NixOS Manual](https://nixos.org/manual/nixos/unstable/index.html#ch-configuration)
@ -37,8 +37,16 @@ can lead to bloated and difficult-to-maintain files. A better solution is to use
module system to split the configuration into multiple Nix modules and write them in a
classified manner.
The Nix module system provides a parameter, `imports`, which accepts a list of `.nix`
files and merges all the configuration defined in these files into the current Nix module.
The Nix language provides an
[import function](https://nix.dev/tutorials/nix-language.html#import) with a special rule:
> If the parameter of `import` is a folder path, it will return the execution result of
> the `default.nix` file in that folder.
The Nixpkgs module system provides a similar parameter, `imports`, which accepts a list of
`.nix` files and **merge** all the configuration defined in these files into the current
Nix module.
Note that `imports` will not simply overwrite duplicate configuration but handle it more
reasonably. For example, if `program.packages = [...]` is defined in multiple modules,
then `imports` will merge all `program.packages` defined in all Nix modules into one list.

View File

@ -29,11 +29,15 @@ $ tree
`configuration.nix``home.nix` 会导致配置文件臃肿,难以维护。更好的解决方案是通过
Nix 的模块机制,将配置文件拆分成多个模块,分门别类地编写维护。
在前面的 Nix 语法一节有介绍过:「`import` 的参数如果为文件夹路径,那么会返回该文件夹下的
`default.nix` 文件的执行结果」,实际 Nix 还提供了一个 `imports` 参数,它可以接受一个
`.nix` 文件列表,并将该列表中的所有配置**合并**Merge到当前的 attribute set 中。注意这
里的用词是「合并」,它表明 `imports` 如果遇到重复的配置项,不会简单地按执行顺序互相覆盖,
而是更合理地处理。比如说我在多个 modules 中都定义了 `program.packages = [...]`,那么
Nix 语言提供了一个 [`import` 函数](https://nix.dev/tutorials/nix-language.html#import),它有一条特殊规则:
> `import` 的参数如果为文件夹路径,那么会返回该文件夹下的 `default.nix` 文件的执行结果
Nixpkgs 模块系统提供了一个与之类似的 `imports` 参数,它可以接受一个 `.nix` 文件列表,并将
该列表中的所有配置**合并**Merge到当前的 attribute set 中。
注意这里的用词是「**合并**」,它表明 `imports` 如果遇到重复的配置项,不会简单地按执行顺序互相
覆盖,而是更合理地处理。比如说我在多个 modules 中都定义了 `program.packages = [...]`,那么
`imports` 会将所有 modules 中的 `program.packages` 这个 list 合并。不仅 list 能被正确合
attribute set 也能被正确合并,具体行为各位看官可以自行探索。