numtide / blueprint

Nix without the glue code
41 stars 3 forks source link

formatter.nix #11

Closed brianmcgee closed 2 months ago

brianmcgee commented 2 months ago

Is your feature request related to a problem? Please describe.

It's not clear how to set a custom formatted e.g. treefmt. set the flake formatter.

Describe the solution you'd like

Just like with devshell.nix, if a formatter.nix is present it could be used to set the flake formatted.

zimbatm commented 2 months ago

You can create a pkgs/formatter/default.nix with the following content:

{
  flake,
  inputs,
  pkgs,
  ...
}:
# treefmt with config
let
  formatter = inputs.treefmt-nix.lib.mkWrapper pkgs {
    _file = ./default.nix;
    package = pkgs.treefmt2;

    projectRootFile = ".git/config";

    programs.deadnix.enable = true;
    programs.hclfmt.enable = true;
    programs.mdformat.enable = true;
    programs.nixfmt-rfc-style.enable = true;
    programs.shellcheck.enable = true;
    programs.shfmt.enable = true;
    programs.terraform.enable = true;

    # don't format the .tf files
    settings.formatter.hclfmt.includes = pkgs.lib.mkForce [ "*.hcl" ];

    settings.formatter.deadnix.pipeline = "nix";
    settings.formatter.deadnix.priority = 1;
    settings.formatter.nixfmt-rfc-style.pipeline = "nix";
    settings.formatter.nixfmt-rfc-style.priority = 2;

    settings.formatter.shellcheck.pipeline = "shell";
    settings.formatter.shellcheck.priority = 1;
    settings.formatter.shfmt.pipeline = "shell";
    settings.formatter.shfmt.priority = 2;
  };

  check =
    pkgs.runCommand "format-check"
      {
        nativeBuildInputs = [
          formatter
          pkgs.git
        ];

        # only check on Linux
        meta.platforms = pkgs.lib.platforms.linux;
      }
      ''
        export HOME=$NIX_BUILD_TOP/home

        # keep timestamps so that treefmt is able to detect mtime changes
        cp --no-preserve=mode --preserve=timestamps -r ${flake} source
        cd source
        git init --quiet
        git add .
        treefmt --no-cache
        if ! git diff --exit-code; then
          echo "-------------------------------"
          echo "aborting due to above changes ^"
          exit 1
        fi
        touch $out
      '';
in
formatter
// {
  meta = formatter.meta // {
    tests = {
      check = check;
    };
  };
}

And make sure to add treefmt-nix to the flake inputs.

The integration could be cleaner though.

brianmcgee commented 2 months ago

Yeah I came to this conclusion after implementing the PR.