Skip to content

Commit a99005c

Browse files
committed
docs/src/options: init
1 parent 5ebde13 commit a99005c

File tree

9 files changed

+136
-6
lines changed

9 files changed

+136
-6
lines changed

docs/.vitepress/config.mts

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,12 @@ function themeConfigEnglish() {return {
5959
{ text: "Examples", link: "/modules/examples" }
6060
],
6161
},
62+
{
63+
text: "Options",
64+
items: [
65+
{ text: "Introduction", link: "/options/introduction" },
66+
],
67+
},
6268
{
6369
text: "Hosts",
6470
items: [
@@ -112,6 +118,12 @@ function themeConfigRussian() {return {
112118
{ text: "Примеры", link: "/ru/modules/examples" }
113119
],
114120
},
121+
{
122+
text: "Опции",
123+
items: [
124+
{ text: "Вступление", link: "/ru/options/introduction" },
125+
],
126+
},
115127
{
116128
text: "Хосты",
117129
items: [

docs/src/modules/introduction-nixos.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ delib.module {
101101
}
102102
```
103103

104-
For more information on Denix options, see the [Options](/TODO) section.
104+
For more information on Denix options, see the [Options](/options/introduction) section.
105105

106106
## Creating Your Own Modules (Options) {#creating-own-modules}
107107
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`.

docs/src/modules/introduction.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,6 @@ This means that you can use all three types of modules simultaneously, although
3131
## Simplicity and Cleanliness {#simplicity-and-cleanliness}
3232
Denix modules tend to look simpler and cleaner compared to NixOS/Home Manager modules, due to the following reasons:
3333

34-
1. Simple yet fully functional option declaration (see [Options](/TODO)).
34+
1. Simple yet fully functional option declaration (see [Options](/options/introduction)).
3535
2. Built-in logic for separating configurations based on the value of `${delib.module :: name}.enable`: always, ifEnabled, ifDisabled.
3636
3. Shared options but separated configurations for NixOS, Home Manager, and custom options.

docs/src/modules/structure.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ This section uses the variables `myconfigName`, `isHomeManager`, and `homeManage
33

44
## Function Arguments {#function-arguments}
55
- `name`{#function-arguments-name}: string. It is recommended that it matches the parent path of the module's `enable` option, such as `"programs.example"`, since the `cfg` argument depends on this path.
6-
- `options`: attrset or a lambda that returns an attrset (see [Options](/TODO)).
6+
- `options`: attrset or a lambda that returns an attrset (see [Options](/options/introduction)).
77
- `[myconfig|nixos|home].[ifEnabled|ifDisabled|always]`: attrset or a lambda that returns an attrset.
88
- `myconfig.*`: sets values in `config.${myconfigName}`.
99
- `nixos.*`: sets values in `config` if `isHomeManager` is `false`; otherwise, it does nothing.

docs/src/options/introduction.md

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Introduction to Denix Options {#introduction}
2+
Denix options are a wrapper for `lib.mkOption`. This means that any Denix option can be created using the standard `lib.mkOption`, and using Denix options is optional.
3+
4+
## Why use Denix options? {#why}
5+
Using `lib.mkOption` can be cumbersome, and writing something like this every time:
6+
7+
```nix
8+
lib.mkOption {type = lib.types.listOf lib.types.str; default = [];}
9+
```
10+
11+
is inconvenient, especially when options are used extensively in your configuration. Instead, you can write something more concise:
12+
13+
```nix
14+
delib.listOfOption delib.str []
15+
```
16+
17+
Thus, instead of creating an option by specifying all parameters, you can use Denix functions for more readable and cleaner code.
18+
19+
## Working Principle {#principle}
20+
Functions related to options are divided into four main types:
21+
22+
### Creating an Option with Type N
23+
- `*Option <default>` - for example, `strOption "foo"`.
24+
- `*OfOption <secondType> <default>` - for example, `listOfOption str ["foo" "bar"]`.
25+
- `*ToOption <secondType> <default>` - for example, `lambdaToOption int (x: 123)`.
26+
27+
### Adding Type N to Option Type X
28+
- `allow* <option>` - for example, `allowStr ...`.
29+
- `allow*Of <secondType> <option>` - for example, `allowListOf str ...`.
30+
- `allow*To <secondType> <option>` - for example, `allowLambdaTo int ...`.
31+
32+
### Directly Modifying the Attribute Set of an Option
33+
- `noDefault <option>` - removes the `default` attribute from the option. It is rarely used since options without a default value are uncommon.
34+
- `readOnly <option>` - adds the `readOnly` attribute with the value `true`.
35+
- `apply <option> <apply>` - adds the `apply` attribute with the value passed to this function.
36+
- `description <option> <description>` - adds the `description` attribute with the given value.
37+
38+
### Generating Specific Options
39+
- `singleEnableOption <default> {name, ...}` - creates an attribute set using the expression `delib.setAttrByStrPath "${name}.enable" (boolOption default)`. This is commonly used in `delib.module :: options` with its [passed arguments](/modules/structure#passed-arguments), so you can simply write:
40+
41+
```nix
42+
options = delib.singleEnableOption <default>;
43+
```
44+
45+
The list of current options can be found in the source code: [github:yunfachi/denix?path=lib/options.nix](https://github.com/yunfachi/denix/blob/master/lib/options.nix)
46+
47+
## Examples {#examples}
48+
49+
| Denix | lib.mkOption |
50+
|--------------------------------------------|--------------------------------------------------------------|
51+
| `portOption 22` | `mkOption {type = types.port; default = 22;}` |
52+
| `noDefault (portOption null)` | `mkOption {type = types.port;}` |
53+
| `allowNull (portOption null)` | `mkOption {type = types.nullOr types.port; default = null;}` |
54+
| `allowStr (portOption "22")` | `mkOption {type = types.strOr types.port; default = "22";}` |
55+
| `listOfOption port []` | `mkOption {type = types.listOf types.port; default = [];}` |
56+
| `readOnly (noDefault (portOption null))` | `mkOption {type = types.port; readOnly = true;}` |
57+
| `singleEnableOption true {name = "git";}` | `git.enable = mkEnableOption "git" // {default = true;}` |
58+
59+
> *(Usually `{name = "git";}` is not required, as this function is mainly used in `delib.module :: options`)*

docs/src/ru/modules/introduction-nixos.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ optionName = lib.mkOption {
9999
}
100100
```
101101

102-
Более подробно о опциях Denix можно узнать в разделе [Опции](/TODO).
102+
Более подробно о опциях Denix можно узнать в разделе [Опции](/ru/options/introduction).
103103

104104
## Создание своих модулей (опций) {#creating-own-modules}
105105
Декларирование своих опций - отличная практика, если вы хотите включать и отключать части кода. Это может понадобиться, если у вас несколько хостов (машин) с одной конфигурацией, и, например, машине `foo` не нужна программа, которая используется на машине `bar`.

docs/src/ru/modules/introduction.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,6 @@
3131
## Простота и чистота {#simplicity-and-cleanliness}
3232
Модули Denix в большинстве случаев выглядят проще и чище, чем модули NixOS/Home Manager, по следующим причинам:
3333

34-
1. Простое, но при этом полноценное декларирование опций (см. [Опции](/TODO)).
34+
1. Простое, но при этом полноценное декларирование опций (см. [Опции](/ru/options/introduction)).
3535
2. Встроенная логика разделения конфигураций в зависимости от значения опции `${delib.module :: name}.enable`: always, ifEnabled, ifDisabled.
3636
3. Общие опции, но разделённые конфигурации для NixOS, Home Manager и собственных опций.

docs/src/ru/modules/structure.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
## Аргументы функции {#function-arguments}
55
- `name`{#function-arguments-name}: строка. Рекомендуется, чтобы она совпадала с родительским путём опции `enable` модуля, например, `"programs.example"`, так как передаваемый аргумент `cfg` зависит именно от этого пути.
6-
- `options`: attrset или lambda, которая возвращает attrset (см. [Опции](/TODO)).
6+
- `options`: attrset или lambda, которая возвращает attrset (см. [Опции](/ru/options/introduction)).
77
- `[myconfig|nixos|home].[ifEnabled|ifDisabled|always]`: attrset или lambda, которая возвращает attrset.
88
- `myconfig.*`: устанавливает значения в `config.${myconfigName}`.
99
- `nixos.*`: устанавливает значения в `config`, если `isHomeManager` равен `false`, иначе не выполняется.
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Введение в опции Denix {#introduction}
2+
Опции Denix представляют собой обёртку для `lib.mkOption`. Это означает, что любую опцию Denix можно создать, используя стандартный `lib.mkOption`, и использование опций Denix является необязательным.
3+
4+
## Зачем использовать опции Denix? {#why}
5+
Использование `lib.mkOption` может быть громоздким, и каждый раз писать что-то вроде:
6+
7+
```nix
8+
lib.mkOption {type = lib.types.listOf lib.types.str; default = [];}
9+
```
10+
11+
- неудобно, особенно когда опции в вашей конфигурации используются повсеместно. Вместо этого можно написать более лаконично:
12+
13+
```nix
14+
delib.listOfOption delib.str []
15+
```
16+
17+
Таким образом, вместо создания опции через указание всех параметров, можно использовать функции Denix для более читабельного и аккуратного кода.
18+
19+
## Принцип работы {#principle}
20+
Функции, связанные с опциями, делятся на четыре основных типа:
21+
22+
### Создание опции с типом N
23+
- `*Option <default>` - например, `strOption "foo"`.
24+
- `*OfOption <secondType> <default>` - например, `listOfOption str ["foo" "bar"]`.
25+
- `*ToOption <secondType> <default>` - например, `lambdaToOption int (x: 123)`.
26+
27+
### Добавление к типам опции X тип N
28+
- `allow* <option>` - например, `allowStr ...`.
29+
- `allow*Of <secondType> <option>` - например, `allowListOf str ...`.
30+
- `allow*To <secondType> <option>` - например, `allowLambdaTo int ...`.
31+
32+
### Прямое изменение attribute set опции
33+
- `noDefault <option>` - удаляет атрибут `default` из опции. Используется редко, так как редко бывают опции без значения по умолчанию.
34+
- `readOnly <option>` - добавляет атрибут `readOnly` со значением `true`.
35+
- `apply <option> <apply>` - добавляет атрибут `apply` с переданным значением.
36+
- `description <option> <description>` - добавляет атрибут `description` с переданным значением.
37+
38+
### Генерация конкретной опции/опций
39+
- `singleEnableOption <default> {name, ...}` - создаёт attribute set с помощью выражения `delib.setAttrByStrPath "${name}.enable" (boolOption default)`. Обычно это используется в `delib.module :: options`, с её [передаваемыми аргументами](/ru/modules/structure#passed-arguments), поэтому достаточно написать:
40+
41+
```nix
42+
options = delib.singleEnableOption <default>;
43+
```
44+
45+
Список актуальных опций можно найти в исходном коде: [github:yunfachi/denix?path=lib/options.nix](https://github.com/yunfachi/denix/blob/master/lib/options.nix)
46+
47+
## Примеры {#examples}
48+
49+
| Denix | lib.mkOption |
50+
|--------------------------------------------|--------------------------------------------------------------|
51+
| `portOption 22` | `mkOption {type = types.port; default = 22;}` |
52+
| `noDefault (portOption null)` | `mkOption {type = types.port;}` |
53+
| `allowNull (portOption null)` | `mkOption {type = types.nullOr types.port; default = null;}` |
54+
| `allowStr (portOption "22")` | `mkOption {type = types.strOr types.port; default = "22";}` |
55+
| `listOfOption port []` | `mkOption {type = types.listOf types.port; default = [];}` |
56+
| `readOnly (noDefault (portOption null))` | `mkOption {type = types.port; readOnly = true;}` |
57+
| `singleEnableOption true {name = "git";}` | `git.enable = mkEnableOption "git" // {default = true;}` |
58+
59+
> *(Обычно `{name = "git";}` указывать не требуется, так как эта функция в основном используется в `delib.module :: options`)*

0 commit comments

Comments
 (0)