Skip to content

Commit 60417e2

Browse files
committed
docs/src/modules: add introduction-nixos and introduction
1 parent c3c1a45 commit 60417e2

File tree

6 files changed

+371
-5
lines changed

6 files changed

+371
-5
lines changed

docs/.vitepress/config.mts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ function themeConfigEnglish() {return {
5050
{
5151
text: "Modules",
5252
items: [
53+
{ text: "Introduction to NixOS Modules", link: "/modules/introduction-nixos" },
5354
{ text: "Introduction", link: "/modules/introduction" },
5455
{ text: "Structure", link: "/modules/structure" },
5556
{ text: "Examples", link: "/modules/examples" }
@@ -85,6 +86,7 @@ function themeConfigRussian() {return {
8586
{
8687
text: "Модули",
8788
items: [
89+
{ text: "Вступление в модули NixOS", link: "/ru/modules/introduction-nixos" },
8890
{ text: "Вступление", link: "/ru/modules/introduction" },
8991
{ text: "Структура", link: "/ru/modules/structure" },
9092
{ text: "Примеры", link: "/ru/modules/examples" }
Lines changed: 148 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,148 @@
1+
# Introduction to NixOS Modules {#introduction-nixos}
2+
A NixOS module is a file containing a Nix expression with a specific structure. It defines options (options) and values for those options (config). For example, the `/etc/nixos/configuration.nix` file is also a module.
3+
4+
Home Manager modules work similarly, but they can be used not only in NixOS but also on other systems.
5+
6+
This is not a comprehensive guide on Nix modules, so it is recommended to read the [NixOS Wiki article on modules](https://nixos.wiki/wiki/NixOS_modules).
7+
8+
## Structure {#structure}
9+
The structure of a NixOS module:
10+
11+
```nix
12+
{
13+
imports = [
14+
# Paths to other modules or Nix expressions.
15+
];
16+
17+
options = {
18+
# Declaration of options.
19+
};
20+
21+
config = {
22+
# Assigning values to previously declared options.
23+
# For example, networking.hostName = "denix";
24+
};
25+
26+
# However, values are usually assigned to options not in config, but here.
27+
# For example, networking.hostName = "denix";
28+
}
29+
```
30+
31+
### Function {#structure-function}
32+
A module can also be a function (lambda) that returns an attribute set:
33+
34+
```nix
35+
{lib, ...} @ args: {
36+
# Formally, this is config._module.args.hostname
37+
_module.args.hostname = lib.concatStrings ["de" "nix"];
38+
39+
imports = [
40+
{hostname, config, ...}: {
41+
config = lib.mkIf config.customOption.enable {
42+
networking.hostName = hostname;
43+
};
44+
}
45+
];
46+
}
47+
```
48+
49+
### Imports
50+
`imports` is a list of relative and absolute paths, as well as [functions](#structure-function) and attribute sets:
51+
52+
```nix
53+
{
54+
imports = [
55+
./pureModule.nix
56+
/etc/nixos/impureModule.nix
57+
{pkgs, ...}: {
58+
# ...
59+
}
60+
];
61+
}
62+
```
63+
64+
### Nixpkgs Options
65+
Options are usually declared using `lib.mkOption`:
66+
67+
```nix
68+
optionName = lib.mkOption {
69+
# ...
70+
};
71+
```
72+
73+
`lib.mkOption` accepts an attribute set. Some attributes include:
74+
75+
- `type`: the type of value for this option, e.g., `lib.types.listOf lib.types.port`.
76+
- `default`: the default value for this option.
77+
- `example`: an example value for this option, used in documentation.
78+
- `description`: a description of this option, also used in documentation.
79+
- `readOnly`: whether the option can be modified after declaration.
80+
81+
For more information on Nixpkgs options, see the [NixOS Wiki](https://nixos.wiki/wiki/Declaration).
82+
83+
### Denix Options
84+
Denix uses a different approach to options, although both methods can be used simultaneously.
85+
86+
An example of a module with options using Denix:
87+
88+
```nix
89+
{denix, ...}:
90+
delib.module {
91+
name = "coolmodule";
92+
93+
options.coolmodule = with delib; {
94+
# boolOption <default>
95+
enable = boolOption false;
96+
# noDefault (listOf) <default>
97+
ports = noDefault (listOfOption port null);
98+
# allowNull (strOption) <default>
99+
email = allowNull (strOption null);
100+
};
101+
}
102+
```
103+
104+
For more information on Denix options, see the [Options](/options/introduction) section.
105+
106+
## Creating Your Own Modules (Options)
107+
Declaring your own options is a great practice if you want to enable or disable certain parts of the code. This can be useful if you have multiple hosts (machines) with the same configuration, and, for example, machine `foo` does not need a program that is used on machine `bar`.
108+
109+
An example of a NixOS module for simple git configuration:
110+
111+
```nix
112+
{lib, config, ...}: {
113+
options.programs.git = {
114+
enable = lib.mkEnableOption "git";
115+
};
116+
117+
config = lib.mkIf config.programs.git.enable {
118+
programs.git = {
119+
enable = true;
120+
lfs.enable = true;
121+
122+
config = {
123+
init.defaultBranch = "master";
124+
};
125+
};
126+
};
127+
}
128+
```
129+
130+
The same configuration but using Denix:
131+
132+
```nix
133+
{delib, ...}:
134+
delib.module {
135+
name = "programs.git";
136+
137+
options = delib.singleEnableOption true;
138+
139+
nixos.ifEnabled.programs.git = {
140+
enable = true;
141+
lfs.enable = true;
142+
143+
config = {
144+
init.defaultBranch = "master";
145+
};
146+
};
147+
}
148+
```

docs/src/modules/introduction.md

Lines changed: 36 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1,36 @@
1-
# TODO
1+
# Introduction to Denix Modules {#introduction}
2+
A Denix module is the same as a NixOS or Home Manager module, but its attribute set is wrapped in the [`delib.module`](/modules/structure) function.
3+
4+
## No Limitations
5+
This means that you can use all three types of modules simultaneously, although it's unlikely you'll need anything other than the first option:
6+
7+
### Denix Module
8+
```nix
9+
{delib, ...}: delib.module {
10+
name = "...";
11+
}
12+
```
13+
14+
### Denix Module with NixOS/Home Manager Module
15+
```nix
16+
{delib, ...}: delib.module {
17+
name = "...";
18+
}
19+
// {
20+
21+
}
22+
```
23+
24+
### NixOS/Home Manager Module Only
25+
```nix
26+
{
27+
28+
}
29+
```
30+
31+
## Simplicity and Cleanliness
32+
Denix modules tend to look simpler and cleaner compared to NixOS/Home Manager modules, due to the following reasons:
33+
34+
1. Simple yet fully functional option declaration (see [Options](/TODO)).
35+
2. Built-in logic for separating configurations based on the value of `${delib.module :: name}.enable`: always, ifEnabled, ifDisabled.
36+
3. Shared options but separated configurations for NixOS, Home Manager, and custom options.

docs/src/ru/introduction.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@ Denix - это библиотека для Nix, предназначенная
99
Предоставленные функции, грубо говоря, делятся на пять категорий:
1010
- Создание конфигураций для Flake ([NixOS](https://nixos.org/) или [Home Manager](https://github.com/nix-community/home-manager))
1111
- Опции - аналог типов и функций для создания опций из [Nixpkgs](https://github.com/NixOS/nixpkgs)
12-
- [Модули](#модули)
13-
- [Хосты](#хосты)
14-
- [Райсы](#райсы)
12+
- [Модули](#modules)
13+
- [Хосты](#hosts)
14+
- [Райсы](#rices)
1515

1616
## Зачем и кому нужен Denix {#why-and-who-needs-denix}
1717
Denix в первую очередь нужен для упрощения создания, редактирования и улучшения читаемости кода конфигураций. Он избавляет от необходимости создавать типичные выражения для создания своих модулей, хостов, райсов и т.д.
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
# Введение в модули NixOS {#introduction-nixos}
2+
Модуль NixOS - это файл, содержащий Nix-выражение с определенной структурой. В нем указаны опции (options) и значения для этих опций (config). Например, файл `/etc/nixos/configuration.nix` тоже является модулем.
3+
4+
Модули Home Manager устроены аналогично, но они могут работать не только в NixOS, но и на других системах.
5+
6+
Это не подробный гайд по Nix-модулям, поэтому рекомендуется прочитать статью [NixOS Wiki о модулях](https://nixos.wiki/wiki/NixOS_modules).
7+
8+
## Структура {#structure}
9+
Структура модуля NixOS:
10+
```nix
11+
{
12+
imports = [
13+
# Пути к остальным модулям или Nix-выражения.
14+
];
15+
16+
options = {
17+
# Декларация опций.
18+
};
19+
20+
config = {
21+
# Присвоение ранее созданным опциям значений.
22+
# Например, networking.hostName = "denix";
23+
};
24+
25+
# Однако обычно значения опциям присваиваются не в config, а тут.
26+
# Например, networking.hostName = "denix";
27+
}
28+
```
29+
30+
### Функция {#structure-function}
31+
Модуль также может быть функцией (lambda), которая возвращает attribute set:
32+
33+
```nix
34+
{lib, ...} @ args: {
35+
# Формально это config._module.args.hostname
36+
_module.args.hostname = lib.concatStrings ["de" "nix"];
37+
38+
imports = [
39+
{hostname, config, ...}: {
40+
config = lib.mkIf config.customOption.enable {
41+
networking.hostName = hostname;
42+
};
43+
}
44+
];
45+
}
46+
```
47+
48+
### Импортирование
49+
`imports` - это список из относительных и абсолютных путей, а также из [функций](#structure-function) и attribute set:
50+
51+
```nix
52+
{
53+
imports = [
54+
./pureModule.nix
55+
/etc/nixos/impureModule.nix
56+
{pkgs, ...}: {
57+
# ...
58+
}
59+
];
60+
}
61+
```
62+
63+
### Опции Nixpkgs
64+
Опции обычно указываются через `lib.mkOption`:
65+
66+
```nix
67+
optionName = lib.mkOption {
68+
# ...
69+
};
70+
```
71+
72+
`lib.mkOption` принимает attribute set. Некоторые атрибуты:
73+
74+
- `type`: тип значения этой опции, например, `lib.types.listOf lib.types.port`.
75+
- `default`: значение по умолчанию для этой опции.
76+
- `example`: пример значения для этой опции, используется для документации.
77+
- `description`: описание этой опции, также используется для документации.
78+
- `readOnly`: может ли опция быть изменена после декларирования.
79+
80+
Более подробно о опциях Nixpkgs можно узнать в [NixOS Wiki](https://nixos.wiki/wiki/Declaration).
81+
82+
### Опции Denix
83+
В Denix используется другой подход к опциям, хотя можно использовать оба метода одновременно.
84+
85+
Пример модуля с опциями в Denix:
86+
87+
```nix
88+
{denix, ...}: delib.module {
89+
name = "coolmodule";
90+
91+
options.coolmodule = with delib; {
92+
# boolOption <default>
93+
enable = boolOption false;
94+
# noDefault (listOf <type> <default>)
95+
ports = noDefault (listOfOption port null);
96+
# allowNull (strOption <default>)
97+
email = allowNull (strOption null);
98+
};
99+
}
100+
```
101+
102+
Более подробно о опциях Denix можно узнать в разделе [Опции](/ru/options/introduction).
103+
104+
## Создание своих модулей (опций)
105+
Декларирование своих опций - отличная практика, если вы хотите включать и отключать части кода. Это может понадобиться, если у вас несколько хостов (машин) с одной конфигурацией, и, например, машине `foo` не нужна программа, которая используется на машине `bar`.
106+
107+
Пример NixOS-модуля для простой настройки git:
108+
109+
```nix
110+
{lib, config, ...}: {
111+
options.programs.git = {
112+
enable = lib.mkEnableOption "git";
113+
};
114+
115+
config = lib.mkIf config.programs.git.enable {
116+
programs.git = {
117+
enable = true;
118+
lfs.enable = true;
119+
120+
config = {
121+
init.defaultBranch = "master";
122+
};
123+
};
124+
};
125+
}
126+
```
127+
128+
То же самое, но с использованием Denix:
129+
130+
```nix
131+
{delib, ...}:
132+
delib.module {
133+
name = "programs.git";
134+
135+
options = delib.singleEnableOption true;
136+
137+
nixos.ifEnabled.programs.git = {
138+
enable = true;
139+
lfs.enable = true;
140+
141+
config = {
142+
init.defaultBranch = "master";
143+
};
144+
};
145+
}
146+
```

0 commit comments

Comments
 (0)