Skip to content

Commit c76bc9b

Browse files
jflyMic92
authored andcommitted
Add some documentation about the official nix formatter
We now have some decent tooling around this, but it's not very discoverable for people new to nix. We (the formatting team) believe `nix.dev` is a good place for this documentation to live.
1 parent 4307fa0 commit c76bc9b

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
+56
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
(autoformatting)=
2+
# Autoformatting
3+
4+
[`nixfmt`](https://github.com/NixOS/nixfmt) is the official Nix autoformatter.
5+
Official tooling currently does not use nixfmt out of the box. Subscribe to
6+
[NixOS/nix PR #11252](https://github.com/NixOS/nix/pull/11252) for updates on that effort.
7+
8+
Because `nixfmt` doesn't support formatting whole directory trees, you need
9+
additional tooling such as `treefmt`. The `nixfmt-tree` package provides a
10+
`treefmt` pre-configured to run `nixfmt` on all nix files in your project. Just
11+
add it to your shell:
12+
13+
```nix
14+
mkShell {
15+
packages = [ pkgs.nixfmt-tree ];
16+
}
17+
```
18+
19+
Note: this assumes you're project is in a git repository, and you wish to treat
20+
the entire repo as your project to be formatted.
21+
22+
If you need to configure any [treefmt options], or enable formatting other
23+
(non-nix) files, you can use `treefmt.withConfig`:
24+
25+
[treefmt options]: https://treefmt.com/latest/getting-started/configure/#global-options
26+
27+
```nix
28+
pkgs.treefmt.withConfig {
29+
runtimeInputs = [
30+
pkgs.nixfmt-rfc-style
31+
pkgs.ruff
32+
];
33+
34+
settings = {
35+
# Customize detection of the root of the project.
36+
tree-root-file = "flake.nix";
37+
38+
# Configure nixfmt for .nix files.
39+
formatter.nixfmt = {
40+
command = "nixfmt";
41+
includes = [ "*.nix" ];
42+
};
43+
44+
# And for .py file.
45+
formatter.ruff = {
46+
command = "ruff";
47+
options = [ "format" ];
48+
includes = [ "*.py" ];
49+
};
50+
};
51+
}
52+
```
53+
54+
This can get a little tedious.
55+
[treefmt-nix](https://github.com/numtide/treefmt-nix) has a big library of
56+
preconfigured formatters, and provides a `check` derivation you can use in CI.

source/guides/recipes/index.md

+1
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,5 @@ Managing remote sources <./dependency-management.md>
1111
Python development environment <./python-environment.md>
1212
post-build-hook.md
1313
continuous-integration-github-actions.md
14+
autoformatting.md
1415
```

0 commit comments

Comments
 (0)