OFFSET偏移
← All articlesOFFSET / FIELD NOTESNO. 027

Flake Utils and project templates

Generate outputs for multiple platforms and turn development environments into reusable templates.

English translation · Code and commands follow the Chinese original.

IN THESE READING PATHSFlakes: project and dependency management ↗
About 2 min readStart reading

What is flake-utils?#

Flake outputs often require the same attribute sets to be defined repeatedly for different architectures, such as x86_64-linux and aarch64-linux, making the code very verbose. flake-utils provides a simple helper function to eliminate this repetition.

1. The traditional approach

You need to iterate over all architectures manually.

{
  outputs = { self, nixpkgs }: {
    packages.x86_64-linux.default = ...;
    packages.aarch64-linux.default = ...;
  };
}

2. A concise approach with flake-utils

{
  inputs.flake-utils.url = "github:numtide/flake-utils";

  inputs.nixpkgs.url = "github:NixOS/nixpkgs/nixos-unstable";

  outputs = { self, nixpkgs, flake-utils }:
    flake-utils.lib.eachDefaultSystem (system:
      let pkgs = nixpkgs.legacyPackages.${system}; in
      {
        packages.default = pkgs.hello;
        devShells.default = pkgs.mkShell { buildInputs = [ pkgs.git ]; };
      }
    );
}
  • eachDefaultSystem: generates outputs for the library’s default list of systems. Use eachSystem to specify your own set of platforms.

Flake templates#

Flakes let you create templates that other people can use to initialize projects quickly with a single command.

1. View the official templates

nix flake show templates

2. Initialize a project from a template

# 初始化一个简单的 python 环境
nix flake init -t templates#simple

3. Define templates in your own Flake

You can turn your configuration into a template to share with others:

{
  outputs = { self }: {
    templates.my-rust-app = {
      path = ./templates/rust;
      description = "一个基础的 Rust 项目模板";
    };
  };
}

Why does this matter?#

On NixOS, defining your own Flake templates lets you set up development environments for different languages quickly, without having to configure PATH manually.

References & further reading

  1. Nix Flake manual ↗
  2. Nix flake update ↗
  3. Nix flake check ↗
  4. Upstream flake-utils ↗

Adapted from technical notes. Examples use generic names.

Continue along a reading path

Flakes: project and dependency management

  1. 01Flake structure: inputs and outputs
  2. 02flake.lock and reproducibility
  3. 03Flake Utils and project templates
  4. 04External Flake references and collaboration
  5. 05Migrating NixOS configuration to Flakes
  6. 06A tutorial on Flake projects and dependency management
  7. 07How Flake updates work
  8. 08Rolling back and manually editing flake.lock
CONTINUE READING / NEXT ARTICLEExternal Flake references and collaboration

Connect external modules and packages, and check the relationships between dependency versions.