Flakes/ru: Difference between revisions

FuzzyBot (talk | contribs)
Updating to match new version of source page
FuzzyBot (talk | contribs)
Updating to match new version of source page
 
(22 intermediate revisions by 2 users not shown)
Line 1: Line 1:
<languages />
<languages />


<div class="mw-translate-fuzzy">
{{Cleanup}}
'''Nix flakes''' это [https://nixos.org/manual/nix/stable/contributing/experimental-Features.html экспериментальная особенность] которая была представлена с Nix 2.4 ([https://nixos.org/manual/nix/unstable/release-notes/rl-2.4.html см. Примечания к выпуску]).
 
</div>
'''Nix Flakes''' (Флейки Nix) — это [[Experimental Nix features|экспериментальная функция]], впервые представленная в релизе [[Nix]] 2.4{{Cite manual|nix|development/experimental-features|number=13.8|title=Experimental Features|subsection=xp-feature-flakes|subtitle=flakes}}{{Cite manual|nix|release-notes/rl-2.4|number=14.27|title=Release 2.4 (2021-11-01)}}, которая направлена на решение ряда задач по улучшению экосистемы Nix: Флейки предоставляют единую структуру для Nix-проектов, позволяя фиксировать конкретные версии каждой зависимости, делиться этими зависимостями с помощью lock-файлов и в целом делать запись репродуцируемых Nix-выражений более удобной.
 
Флейк — это каталог, который содержит файл Nix с именем <code>flake.nix</code>, который следует очень конкретной структуре. Флейки вводят похожий на URL синтаксис{{Cite manual|nix|command-ref/new-cli/nix3-flake|number=8.5.17|title=nix flake|subsection=url-like-syntax|subtitle=URL-like syntax}} для указания удалённых ресурсов. Чтобы упростить синтаксис, флейки используют реестр символических идентификаторов{{Cite manual|nix|command-ref/new-cli/nix3-registry|number=8.5.62|title=nix registry}}, что позволяет напрямую ссылаться на ресурсы в следующей форме: <code>github:NixOS/nixpkgs</code>.


<div lang="en" dir="ltr" class="mw-content-ltr">
Флейки также поддерживают фиксацию ссылок и версий, которые затем могут быть запрошены и обновлены программно через inputs{{cite manual|nix|command-ref/new-cli/nix3-flake-lock|number=7.5.19|title=nix flake lock}}{{cite manual|nix|command-ref/new-cli/nix3-flake-info|number=7.5.17|title=nix flake info}}. Кроме того, экспериментальная утилита командной строки принимает flake-ссылки для выражений, которые собирают, выполняют и развёртывают пакеты{{Cite manual|nix|command-ref/new-cli/nix|number=8.5.1|title=nix}}.
'''Nix flakes''' are an [[Experimental Nix features|experimental feature]] first introduced in the 2.4 [[Nix]] release,{{Cite manual|nix|development/experimental-features|number=13.8|title=Experimental Features|subsection=xp-feature-flakes|subtitle=flakes}}{{Cite manual|nix|release-notes/rl-2.4|number=14.27|title=Release 2.4 (2021-11-01)}} aiming to address a number of areas of improvement for the Nix ecosystem: they provide a uniform structure for Nix projects, allow for pinning specific versions of each dependencies, and sharing these dependencies via lock files, and overall make it more convenient to write reproducible Nix expressions.
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<span id="Flake_file_structure"></span>
A flake is a directory which directly contains a Nix file called <code>flake.nix</code>, that follows a very specific structure. Flakes introduce a URL-like syntax{{Cite manual|nix|command-ref/new-cli/nix3-flake|number=8.5.17|title=nix flake|subsection=url-like-syntax|subtitle=URL-like syntax}} for specifying remote resources. To simplify the URL syntax, flakes use a registry of symbolic identifiers,{{Cite manual|nix|command-ref/new-cli/nix3-registry|number=8.5.62|title=nix registry}} allowing the direct specification of resources through syntax such as <code>github:NixOS/nixpkgs</code>.
<div class="mw-translate-fuzzy">
== Структура flake-файла ==
В простейшем виде flake-файл содержит описание флейка, набор входных зависимостей (inputs) и выход (output). Вы можете сгенерировать шаблонный flake-файл в любой момент с помощью <code>nix flake init</code>. Это создаст в текущей директории файл <code>flake.nix</code>, содержащий примерно следующее:
{{File|3=<nowiki>{
  description = "A very basic flake";
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Flakes also allow for locking references and versions, which can then be queried and updated programatically via the inputs {{cite manual|nix|command-ref/new-cli/nix3-flake-lock|number=7.5.19|title=nix flake lock}}{{cite manual|nix|command-ref/new-cli/nix3-flake-info|number=7.5.17|title=nix flake info}}. Additionally, an experimental CLI utility accepts flake references for expressions that build, run, and deploy packages.{{Cite manual|nix|command-ref/new-cli/nix|number=8.5.1|title=nix}}
Minimally, a flake file contains a description of the flake, a set of input dependencies and an output. You can generate a very basic flake file at any time using nix flake init. This will populate the current directory with a file called flake.nix that will contain something akin to:
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
== Flake file structure ==
Minimally, a flake file contains a description of the flake, a set of input dependencies and an output. You can generate a very basic flake file at any time using nix flake init. This will populate the current directory with a file called flake.nix that will contain something akin to:
{{File|3=<nowiki>{
{{File|3=<nowiki>{
   description = "A very basic flake";
   description = "A very basic flake";
</div>


   <div lang="en" dir="ltr" class="mw-content-ltr">
   inputs = {
inputs = {
     nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
     nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
   };
   };
</div>


   <div lang="en" dir="ltr" class="mw-content-ltr">
   outputs = { self, nixpkgs }: {
outputs = { self, nixpkgs }: {
    packages.x86_64-linux = {
</div>
      default = self.packages.x86_64-linux.hello;
      hello = nixpkgs.legacyPackages.x86_64-linux.hello;
    };
  };
}</nowiki>|name=flake.nix|lang=nix}}


    <div lang="en" dir="ltr" class="mw-content-ltr">
<div class="mw-translate-fuzzy">
packages.x86_64-linux.hello = nixpkgs.legacyPackages.x86_64-linux.hello;
};
}</nowiki>|name=flake.nix|lang=nix}}
В примере выше вы можете видеть описание, вход (input), указанный как репозиторий GitHub с конкретной веткой (здесь <code>nixos/nixpkgs</code> на ветке <code>nixos-unstable</code>), и выход (output), который использует этот input. Output в этом примере просто определяет, что в флейке есть один пакет для архитектуры x86_64 под именем <code>hello</code>. Даже если output вашего флейка не использует его inputs (что на практике маловероятно), output всё равно должен быть Nix-функцией.
{{Note|Флейки требуют явного указания outputs для каждой архитектуры отдельно. Для дополнительной информации смотрите соответствующий раздел ниже.}}
</div>
</div>


    <div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
packages.x86_64-linux.default = self.packages.x86_64-linux.hello;
{{Note|Flakes require you to specify its outputs for each architecture separately. For more information, read the related section below.}}
</div>
</div>


  <div lang="en" dir="ltr" class="mw-content-ltr">
<span id="Nix_configuration"></span>
};
<div class="mw-translate-fuzzy">
}</nowiki>|name=flake.nix|lang=nix}}
=== Конфигурация Nix ===
In the example above, you can see the description, the input specified as a GitHub repository with a specific branch (here <code>nixos/nixpkgs</code> on the <code>nixos-unstable</code> branch), and an output that makes use of the input. The output simply specifies that the flake contains one package for the x86_64 architecture called <code>hello</code>. Even if your flake's output wouldn't use its input (however, in practice, that is highly unlikely), the output still needs to be a Nix function.
Можно переопределить глобальную конфигурацию Nix, заданную в файле <code>nix.conf</code>, чтобы оценить работу флейка. Это может быть полезно, например, для установки бинарных кэшей, специфичных для проекта, пока глобальная конфигурация останется нетронутой. Flake-файл может содержать атрибут <code>nixConfig</code> с любыми релевантными настройками. Например, чтобы включить бинарный кэш nix-community, можно добавить:
{{Note|Flakes require you to specify its outputs for each architecture separately. For more information, read the related section below.}}
{{File|3=<nowiki>{
  ...
  nixConfig = {
    extra-substituters = [
      "https://nix-community.cachix.org"
    ];
    extra-trusted-public-keys = [
      "nix-community.cachix.org-1:...="
    ];
}</nowiki>|name=flake.nix|lang=nix}}{{Note|Если вы привыкли настраивать Nix через конфигурацию NixOS, эти опции находятся под <code>nix.settings</code>, а не под <code>nix</code>. Например, вы не сможете указать автоматическую оптимизацию хранилища через <code>nix.optimisation.enable</code>.}}
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Nix configuration ===
It is possible to override the global Nix configuration set in your <code>nix.conf</code> file for the purposes of evaluating a flake. This can be useful, for example, for setting up binary caches specific to certain projects, while keeping the global configuration untouched. The flake file can contain a nixConfig attribute with any relevant configuration settings supplied. For example, enabling the nix-community binary cache would be achieved by:
It is possible to override the global Nix configuration set in your <code>nix.conf</code> file for the purposes of evaluating a flake. This can be useful, for example, for setting up binary caches specific to certain projects, while keeping the global configuration untouched. The flake file can contain a nixConfig attribute with any relevant configuration settings supplied. For example, enabling the nix-community binary cache would be achieved by:
</div>
{{File|3=<nowiki>{
{{File|3=<nowiki>{
   ...
   ...
Line 62: Line 77:
     ];
     ];
   }
   }
}</nowiki>|name=flake.nix|lang=nix}}{{Note|If you are used to configuring your Nix settings via the NixOS configuration, these options are under <code>nix.settings</code> and not <code>nix</code>. For example, you cannot specify the automatic storage optimisation under <code>nix.optimisation.enable</code>.}}
}</nowiki>|name=flake.nix|lang=nix}}
 
<div lang="en" dir="ltr" class="mw-content-ltr">
{{Note|If you are used to configuring your Nix settings via the NixOS configuration, these options are under <code>nix.settings</code> and not <code>nix</code>. For example, you cannot specify the automatic storage optimisation under <code>nix.optimisation.enable</code>.}}
</div>
</div>


Line 77: Line 95:
При использовании любой команды <code>nix</code> добавьте следующие параметры командной строки:
При использовании любой команды <code>nix</code> добавьте следующие параметры командной строки:
</div>
</div>
<syntaxhighlight lang="shell">
<syntaxhighlight lang="shell">
  --experimental-features 'nix-command flakes'
  --experimental-features 'nix-command flakes'
</syntaxhighlight>
</syntaxhighlight>
<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
=== Enabling flakes permanently ===
=== Enabling flakes permanently ===
Line 120: Line 140:
experimental-features = nix-command flakes
experimental-features = nix-command flakes
</syntaxHighlight>
</syntaxHighlight>
<span id="Usage"></span>
<span id="Usage"></span>
<div class="mw-translate-fuzzy">
<div class="mw-translate-fuzzy">
Line 139: Line 160:
<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
=== The nix flakes command ===
=== The nix flakes command ===
</div>
{{Main|Nix (command)}}
{{Main|Nix (command)}}
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 150: Line 172:
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="console">
<syntaxhighlight lang="console">
$ nix flake show
$ nix flake show
Line 158: Line 179:
         └───hello: package 'hello-2.12.2'
         └───hello: package 'hello-2.12.2'
</syntaxhighlight>
</syntaxhighlight>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 168: Line 188:
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
{
{
   description = "Example flake with a devShell";
   description = "Example flake with a devShell";
</div>


  <div lang="en" dir="ltr" class="mw-content-ltr">
inputs.nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
inputs.nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
</div>


  <div lang="en" dir="ltr" class="mw-content-ltr">
outputs = { self, nixpkgs}:
outputs = { self, nixpkgs}:
     let
     let
Line 195: Line 210:
}
}
</syntaxhighlight>
</syntaxhighlight>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 201: Line 215:
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="console">
<syntaxhighlight lang="console">
$ nix develop
$ nix develop
</syntaxhighlight>
</syntaxhighlight>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 220: Line 232:
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxHighlight lang=console>
<syntaxHighlight lang=console>
$ nix build .#hello
$ nix build .#hello
</syntaxHighlight>
</syntaxHighlight>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 277: Line 287:
<code>inputs.nixpkgs.url = "github:NixOS/nixpkgs/<branch name>";</code>
<code>inputs.nixpkgs.url = "github:NixOS/nixpkgs/<branch name>";</code>


<div lang="en" dir="ltr" class="mw-content-ltr">
Nixpkgs can alternatively also point to an url cached by the NixOS organization:
Nixpkgs can alternatively also point to an url cached by the NixOS organization:
</div>


<code>inputs.nixpkgs.url = "<nowiki>https://nixos.org/channels/nixpkgs-unstable/nixexprs.tar.xz</nowiki>";</code>
<code>inputs.nixpkgs.url = "<nowiki>https://nixos.org/channels/nixpkgs-unstable/nixexprs.tar.xz</nowiki>";</code>


<div lang="en" dir="ltr" class="mw-content-ltr">
In this example the input would point to the `nixpkgs-unstable` channel.
In this example the input would point to the `nixpkgs-unstable` channel.
 
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 301: Line 314:


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Using curly brackets({}), we can shorten all of this and put it in a table. The code will look something like this:
Using curly brackets (<code>{}</code>), we can shorten all of this and put it in a table. The code will look something like this:
</div>
</div>


Line 318: Line 331:
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
   inputs.self.submodules = true;
   inputs.self.submodules = true;
</syntaxhighlight>
</syntaxhighlight>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 354: Line 365:
</div>
</div>


<syntaxHighlight lang=nix>
<syntaxhighlight lang="nix">
{ self, ... }@inputs:
{ self, ... }@inputs:
{
{
Line 367: Line 378:
     type = "app";
     type = "app";
     program = "<store-path>";
     program = "<store-path>";
    meta = {description = "..."; inherit otherMetaAttrs; };
   };
   };
   # Executed by `nix run . -- <args?>`
   # Executed by `nix run . -- <args?>`
   apps."<system>".default = { type = "app"; program = "..."; };
   apps."<system>".default = { type = "app"; program = "..."; meta = {description = "..."; inherit otherMetaAttrs; }; };


   # Formatter (alejandra, nixfmt or nixpkgs-fmt)
   # Formatter (alejandra, nixfmt, treefmt-nix or nixpkgs-fmt)
   formatter."<system>" = derivation;
   formatter."<system>" = derivation;
   # Used for nixpkgs packages, also accessible via `nix build .#<name>`
   # Used for nixpkgs packages, also accessible via `nix build .#<name>`
Line 400: Line 412:
   templates.default = { path = "<store-path>"; description = ""; };
   templates.default = { path = "<store-path>"; description = ""; };
}
}
</syntaxHighlight>
</syntaxhighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 438: Line 450:
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
{
{
   description = "A flake targeting multiple architectures";
   description = "A flake targeting multiple architectures";
</div>


  <div lang="en" dir="ltr" class="mw-content-ltr">
inputs = {
inputs = {
     nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
     nixpkgs.url = "github:nixos/nixpkgs?ref=nixos-unstable";
   };
   };
</div>


  <div lang="en" dir="ltr" class="mw-content-ltr">
outputs = { self, nixpkgs }: let
outputs = { self, nixpkgs }: let
     systems = [ "x86_64-linux" "aarch64-linux" ];
     systems = [ "x86_64-linux" "aarch64-linux" ];
Line 467: Line 474:
}
}
</syntaxhighlight>
</syntaxhighlight>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 490: Line 496:
</div>
</div>


<div lang="en" dir="ltr" class="mw-content-ltr">
<syntaxhighlight lang="nix">
<syntaxhighlight lang="nix">
{
{
Line 502: Line 507:
     };
     };
}
}
</syntaxhighlight>
</syntaxhighlight>  
</div>  


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 630: Line 634:
# Output should show ~/libdep-src-checkout/ so you know it worked
# Output should show ~/libdep-src-checkout/ so you know it worked
</syntaxHighlight>
</syntaxHighlight>


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
Line 713: Line 718:
* [https://github.com/nix-community/todomvc-nix building Rust and Haskell flakes]
* [https://github.com/nix-community/todomvc-nix building Rust and Haskell flakes]
</div>
</div>
{{references}}


<div lang="en" dir="ltr" class="mw-content-ltr">
<div lang="en" dir="ltr" class="mw-content-ltr">
{{references}}
[[Category:Software|Software]]
[[Category:Nix|Nix]]
[[Category:Nix Language|Nix Language]]
[[Category:Flakes|Flakes]]
</div>
</div>
[[Category:Software]]
[[Category:Nix]]
[[Category:Nix Language]]
[[Category:Flakes]]