• Stars
    star
    226
  • Rank 176,514 (Top 4 %)
  • Language
    Nix
  • License
    MIT License
  • Created about 2 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

treefmt nix configuration

treefmt-nix β€” Fast and convenient multi-file formatting with Nix

treefmt combines file formatters for multiple programming languages so that you can format all your project files with a single command. With treefmt-nix you can specify treefmt build options, dependencies and config in one place, conveniently managed by Nix.

treefmt-nix automatically installs and configures the desired formatters as well as treefmt for you and integrates nicely into your Nix development environments. It comes with sane, pre-crafted formatter-configs maintained by the community; each config corresponds to a section that you would normally add to the treefmt config file treefmt.toml.

Take a look at the already supported formatters for Python, Rust, Go, Haskell and more.

Integration into Nix

Nix classic without flakes

To run treefmt-nix with nix-classic, import the repo using niv:

$ niv add numtide/treefmt-nix

Alternatively, you can download the source and run nix-build in the project root directory:

$ nix-build

The command will return the helper functions which will be later used to produce a derivation from the specified treefmt-nix configuration.

After you installed treefmt-nix, specify the formatter configuration. For instance, this one is for formatting terraform files:

# myfile.nix
{ system ? builtins.currentSystem }:
let
  nixpkgsSrc = builtins.fetchTarball "https://github.com/NixOS/nixpkgs/archive/refs/heads/nixos-unstable.tar.gz";
  treefmt-nixSrc = builtins.fetchTarball "https://github.com/numtide/treefmt-nix/archive/refs/heads/master.tar.gz";
  nixpkgs = import nixpkgsSrc { inherit system; };
  treefmt-nix = import treefmt-nixSrc;
in
treefmt-nix.mkWrapper nixpkgs {
  # Used to find the project root
  projectRootFile = ".git/config";
  # Enable the terraform formatter
  programs.terraform.enable = true;
  # Override the default package
  programs.terraform.package = nixpkgs.terraform_1;
  # Override the default settings generated by the above option
  settings.formatter.terraform.excludes = [ "hello.tf" ];
}

It's a good practice to place the configuration file in the project root directory.

Next, execute this command:

$ nix-build myfile.nix

This command returns a derivation that contains a treefmt binary at ./result/bin/treefmt in your current directory. The file is actually a symlink to the artifact in /nix/store.

treefmt.toml in this case isn't generated: the binary is wrapped with the config.

Flakes

Running treefmt-nix with flakes isn't hard. The library is exposed as the lib attribute:

# flake.nix
{
  inputs.treefmt-nix.url = "github:numtide/treefmt-nix";

  outputs = { self, nixpkgs, systems, treefmt-nix }:
    let
      # Small tool to iterate over each systems
      eachSystem = f: nixpkgs.lib.genAttrs (import systems) (system: f nixpkgs.legacyPackages.${system});

      # Eval the treefmt modules from ./treefmt.nix
      treefmtEval = eachSystem (pkgs: treefmt-nix.lib.evalModule pkgs ./treefmt.nix);
    in
    {
      # for `nix fmt`
      formatter = eachSystem (pkgs: treefmtEval.${pkgs.system}.config.build.wrapper);
      # for `nix flake check`
      checks = eachSystem (pkgs: {
        formatting = treefmtEval.${pkgs.system}.config.build.check self;
      });
    };
}

And also add the treefmt.nix file (or put the content inline if you prefer):

# treefmt.nix
{ pkgs, ... }:
{
  # Used to find the project root
  projectRootFile = "flake.nix";
  # Enable the terraform formatter
  programs.terraform.enable = true;
  # Override the default package
  programs.terraform.package = pkgs.terraform_1;
  # Override the default settings generated by the above option
  settings.formatter.terraform.excludes = [ "hello.tf" ];
}

This file is also the place to define all the treefmt parameters like includes, excludes and formatter options.

After specifying the flake, run nix fmt:

$ nix fmt

Nix-fmt is a tool to format all nix files in the project, but with the specified flake, it starts treefmt-nix and formats your project.

You can also run nix flake check (eg: in CI) to validate that the project's code is properly formatted.

Flake-parts

This flake exposes a flake-parts module as well. To use it:

  1. Add inputs.treefmt-nix.flakeModule to the imports list of your flake-parts call.

  2. Add treefmt = { .. } (containing the configuration above) to your perSystem.

  3. Add config.treefmt.build.wrapper to the nativeBuildInputs of your devShell. This will make the treefmt command available in the shell using the specified configuration.

    You can also use config.treefmt.build.programs to get access to the individual programs, which could be useful to provide them to your IDE or editor.

    For an example, see haskell-template's flake.nix.

See this page for a detailed walkthrough.

Configuration

While dealing with treefmt outside of nix, the formatter configuration is specified in a toml format. On the contrary, with nix, you write in with a nix syntax like this:

  # Used to find the project root
  projectRootFile = ".git/config";
  # Enable the terraform formatter
  programs.terraform.enable = true;
  # Override the default package
  programs.terraform.package = nixpkgs.terraform_1;
  # Override the default settings generated by the above option
  settings.formatter.terraform.excludes = [ "hello.tf" ];

Options:

  • Project root file is the git file of the project which you plan to format.
  • The option programs.terraform.enable enables the needed formatter. You can specify as many formatter as you want. For instance:
programs.terraform.enable = true;
programs.gofmt.enable = true;
  • The option programs.terraform.package allows you to use a particular build/version of the specified formatter.
  • By settingsettings.formatter.terraform.excludes you can mark the files which should be excluded from formatting. You can also specify other formatter options or includes this way.

For detailed description of the options, refer to the treefmt documentation.

Project structure

This repo contains a top-level default.nix that returns the library helper functions.

  • mkWrapper is the main function which wraps treefmt with the needed configuration.
  • mkConfigFile
  • evalModule
  • all-modules

Supported programs

treefmt-nix currently supports the following formatters:

  • alejandra
  • beautysh
  • black
  • buildifier
  • cabal-fmt
  • clang-format
  • cue
  • deadnix
  • deno
  • dhall
  • dprint
  • elm-format
  • erlfmt
  • fnlfmt
  • gofmt
  • gofumpt
  • google-java-format
  • hclfmt
  • hlint
  • isort
  • ktfmt
  • ktlint
  • leptosfmt
  • mdformat
  • mdsh
  • mix-format
  • muon
  • mypy
  • nickel
  • nixfmt
  • nixpkgs-fmt
  • ocamlformat
  • ormolu
  • php-cs-fixer
  • prettier
  • protolint
  • purs-tidy
  • ruff
  • rufo
  • rustfmt
  • scalafmt
  • shellcheck
  • shfmt
  • statix
  • stylish-haskell
  • stylua
  • taplo
  • terraform
  • yamlfmt
  • zprint

For non-Nix users, you can also find the generated examples in the ./examples folder.

Adding new formatters

PRs to add new formatters are welcome!

  • The formatter should conform to the formatter specifications.
  • This is not the place to debate formatting preferences. Please pick defaults that are standard in your community -- for instance, python is usually indented with 4 spaces, so don't add a python formatter with 2 spaces as the default.

In order to add a new formatter do the following things:

  1. Create a new entry in the ./programs/ folder.
  2. Run ./bors.toml.sh to update the bors.toml file.
  3. Run ./examples.sh to update the ./examples folder.
  4. To test the program:
    1. Extend the project's ./treefmt.nix file (temporarilt)
    2. Add a bunch of sources in this repo
    3. Run nix develop -c treefmt
    4. Once this is good, revert those changes.
  5. Submit the PR!

Commercial support

Looking for help or customization?

Get in touch with Numtide to get a quote. We make it easy for companies to work with Open Source projects: https://numtide.com/contact

License

All the code and documentation is licensed with the MIT license.

More Repositories

1

devshell

Per project developer environments
Nix
1,213
star
2

flake-utils

Pure Nix flake utility functions [maintainer=@zimbatm]
Nix
1,126
star
3

system-manager

Manage system config using nix on any distro
Rust
651
star
4

treefmt

one CLI to format your repo [maintainers=@zimbatm,@brianmcgee]
Go
602
star
5

nix-filter

a small self-contained source filtering lib
Nix
194
star
6

nixpkgs-unfree

nixpkgs with the unfree bits enabled
Nix
89
star
7

nits

Nix & NATS
Go
78
star
8

nix-gl-host

Run OpenGL/Cuda programs built with Nix, on all Linux distributions.
Python
77
star
9

systemd-vaultd

Provide access to vault secrets to systemd services
Nix
63
star
10

nixos-facter

Declarative nixos-generate-config [maintainer=@brianmcgee]
Go
48
star
11

blueprint

Nix without the glue code
Nix
39
star
12

nix-vm-test

Re-use the NixOS VM test infrastructure to test Ubuntu, Debian, and Fedora machines.
Nix
34
star
13

nar-serve

Unpack and serve NAR file content on the fly
Go
30
star
14

terraform-provider-linuxbox

Configure Linux machines with Terraform
Go
29
star
15

bld

Build nix targets based on git repository directories
Go
29
star
16

prj-spec

Project Base Directory Specification
Shell
28
star
17

deploykit

Execute commands remote via ssh and locally in parallel with python
Python
27
star
18

nix-stdlib

experimental nix prelude
Nix
25
star
19

action-cli

GitHub Actions without JavaScript
Rust
19
star
20

nix-eval-cache

Skips build/evaluation based on modification date of nix files.
Rust
18
star
21

software-consulting-documents

Software Consulting Legal Documents
16
star
22

zero-to-odoo

Nix
15
star
23

github-deploy

Track deployments on GitHub PRs
Go
13
star
24

clean-git-action

Leave no build artifacts behind
Shell
11
star
25

serve-go

Like vercel/serve but for production. Serve SPA apps quickly.
Go
10
star
26

build-go-cache

buildGoCache speeds up nix's buildGoModule by pre-compiling imported go modules
Nix
10
star
27

nixos-rke2

NixOS modules for RKE2
Nix
9
star
28

nix-gitignore

filterSource using .gitignore (experiment)
Go
7
star
29

numtide-github-runner

the best self-hosted github runners on the market
Nix
7
star
30

terraform-deploy-nixos-flakes

Shell
6
star
31

nixos-facter-modules

A series of NixOS modules to be used in conjunction with https://github.com/numtide/nixos-facter [maintainer=@brianmcgee]
Nix
5
star
32

terraform-upload-ami

Upload and import the AMI from a VHD
HCL
5
star
33

generate-terraform-provider-shim

Handle third-party Terraform providers
Go
4
star
34

harvest-invoice-calculator

A little tool that helps generating invoices from Harvest data
Python
4
star
35

configure-nix-action

Configures Nix on GitHub Actions
Shell
4
star
36

terraform-nixos-install

HCL
3
star
37

nixpkgs-terraform

terraform-related packages with Nix
Nix
3
star
38

gh-v6.com

GitHub downloads, with IPv6
HTML
3
star
39

terraform-nix-build

Build Nix with the external provider
Python
2
star
40

kartusche

Go
2
star
41

terraform-linuxbox-traefik

HCL
2
star
42

terraform-linuxbox-monitorpack

Seed DevOps monitoring module
HCL
2
star
43

activate

A small resource converger tool
Nix
2
star
44

mkdocs-numtide

Our own mkdocs template, based on the material design
Nix
2
star
45

docker-host-forwarder

Docker image that will forward udp/tcp to docker host
Shell
2
star
46

nix-vm-test-demo

Dump of the code used in the nix-vm-test demo
Nix
2
star
47

terraform-nixos-amis

Fork of https://github.com/tweag/terraform-nixos/tree/master/aws_image_nixos
HCL
2
star
48

nixionary.org

HTML
2
star
49

NixOS-Fleet-Update-Provider

Terraform provider to update a homogeneous NixOS fleet configuration
Shell
2
star
50

yarnlock2json

Convert `yarn.lock` files to JSON
JavaScript
1
star
51

cert-wizard

Go
1
star
52

nixos-facter-docs

Documentation for NixOS Facter and NixOS Facter Modules
Nix
1
star
53

treefmt-docs

Treefmt Docs
Nix
1
star
54

.github

GitHub Settings for the org
1
star