Description
Official Nix formatter zero-setup starter using treefmt.
A zero-setup treefmt starter to get started using the official Nix formatter.
For
nix fmt
to format all Nix files, add this to theflake.nix
outputs:formatter.${system} = nixpkgs.legacyPackages.${system}.nixfmt-tree;
The same can be done more efficiently with the
treefmt
command, which you can get innix-shell
/nix develop
by extendingmkShell
usingmkShell { packages = [ pkgs.nixfmt-tree ]; }
You can then also use
treefmt
in a pre-commit/pre-push Git hook and with your editor's format-on-save feature.To check formatting in CI, run the following in a checkout of your Git repository:
treefmt --ci
For more flexibility, you can customise this package using
pkgs.nixfmt-tree.override {
settings = { /* additional treefmt config */ };
runtimeInputs = [ /* additional formatter packages */ ];
}
You can achieve similar results by manually configuring treefmt
:
pkgs.treefmt.withConfig {
runtimeInputs = [ pkgs.nixfmt-rfc-style ];
settings = {
# Log level for files treefmt won't format
on-unmatched = "info";
# Assume the tree is a Git repository, will fail if it's not
tree-root-file = ".git/index";
# Configure nixfmt for .nix files
formatter.nixfmt = {
command = "nixfmt";
includes = [ "*.nix" ];
};
};
}
Alternatively you can switch to the more fully-featured treefmt-nix.