Autoformatting#
nixfmt
is the official Nix autoformatter.
Official tooling currently does not use nixfmt out of the box. Subscribe to
NixOS/nix PR #11252 for updates on that effort.
Because nixfmt
doesn’t support formatting whole directory trees, you need
additional tooling such as treefmt
. The nixfmt-tree
package provides a
treefmt
pre-configured to run nixfmt
on all nix files in your project. Just
add it to your shell:
1mkShell {
2 packages = [ pkgs.nixfmt-tree ];
3}
Note: this assumes you’re project is in a git repository, and you wish to treat the entire repo as your project to be formatted.
If you need to configure any treefmt options, or enable formatting other
(non-nix) files, you can use treefmt.withConfig
:
1pkgs.treefmt.withConfig {
2 runtimeInputs = [
3 pkgs.nixfmt-rfc-style
4 pkgs.ruff
5 ];
6
7 settings = {
8 # Customize detection of the root of the project.
9 tree-root-file = "flake.nix";
10
11 # Configure nixfmt for .nix files.
12 formatter.nixfmt = {
13 command = "nixfmt";
14 includes = [ "*.nix" ];
15 };
16
17 # And for .py file.
18 formatter.ruff = {
19 command = "ruff";
20 options = [ "format" ];
21 includes = [ "*.py" ];
22 };
23 };
24}
This can get a little tedious.
treefmt-nix has a big library of
preconfigured formatters, and provides a check
derivation you can use in CI.