How to add the formatter.<system> option in a flake using flake-parts

I want to use the new cli features (nix fmt) for formatting

{
  description = "My experimental flake";

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

    home-manager = {
      url = "github:nix-community/home-manager/release-24.11";
      inputs.nixpkgs.follows = "nixpkgs";
    };

    nix-colors.url = "github:misterio77/nix-colors";

    nixCats.url = "github:BirdeeHub/nixCats-nvim";

    flake-parts.url = "github:hercules-ci/flake-parts";

    git-hooks-nix.url = "github:cachix/git-hooks.nix";
  };

  outputs =
    {
      flake-parts,
      ...
    }@inputs:
    flake-parts.lib.mkFlake { inherit inputs; } {
      systems = [
        "x86_64-linux"
      ];
      imports = [ 
        ./hosts 
        inputs.git-hooks-nix.flakeModule
      ];

      perSystem = {
        pre-commit.settings.hooks.nixfmt-rfc-style.enable = true;
      };
      flake = {
        formatter = inputs.nixpkgs.legacyPackages.x86_64-linux.nixfmt-rfc-style;
      };
    };
}

This is my flake.nix. How and where do I add the formatter.x86_64-linux option (I want to use the official nixfmt for formatting). How do I do it?

My dotfiles

EDIT: running
$nix fmt
Gives

error: flake 'git+file:///home/krish/.dotfiles' does not provide attribute 'formatter.x86_64-linux'

I think inside the flake arg you directly control outputs, so you need to set it per-platform:

      flake = {
        formatter.x86_64-linux = inputs.nixpkgs.legacyPackages.x86_64-linux.nixfmt-rfc-style;
      };

Not sure if there’s a better way with flake-parts.

1 Like

Set it inside perSystem. It generates the needed system attributes. The flake parts template has an example for packages; formatter would be set in a similar way.

2 Likes
      perSystem =
        {
          pkgs,
          config,
          ...
        }:
        {
          formatter = pkgs.nixfmt-rfc-style;
        };
3 Likes

The formatter option in the perSystem thing worked. Thanks a lot, for your help.

$nix fmt 

now works in the flake directory.

Using nixfmt-rfc-style directly doesn’t work, I think you have to use treefmt-nix or some alternative.

Will do that. Got it in my TODO list.