1
0
Fork 0
mirror of https://github.com/NixOS/nix synced 2025-06-25 02:21:16 +02:00
nix/tests/functional/formatter.sh
Jeremy Fleischman ba6b617e75
Add nix formatter build command
`nix formatter build` is sort of like `nix build`: it builds, links, and
prints a path to the formatter program:

    $ nix formatter build
    /nix/store/cb9w44vkhk2x4adfxwgdkkf5gjmm856j-treefmt/bin/treefmt

Note that unlike `nix build`, this prints the full path to the program,
not just the store path (in the example above that would be
`/nix/store/cb9w44vkhk2x4adfxwgdkkf5gjmm856j-treefmt`).

Motivation
----------

I maintain a vim plugin that automatically runs `nix fmt` on files on
save. Since `nix fmt` can be quite slow due to nix evaluation, I choose
to cache the `nix fmt `entrypoint. This was very awkward to do, see the
implementation for details:
7864607231/lua/null-ls/builtins/formatting/nix_flake_fmt.lua (L83-L110).

I recently discovered that my implementation was buggy (it didn't handle
flakes that expose a `formatter` package, such as nixpkgs), so I had to
rework the implementation:
https://github.com/nvimtools/none-ls.nvim/pull/272.

With the new `nix formatter build` command, I can delete all this akward
code, and it will be easier for other folks to build performant editor
integrations for `nix fmt`.
2025-04-29 18:40:02 -07:00

62 lines
1.5 KiB
Bash
Executable file

#!/usr/bin/env bash
source common.sh
TODO_NixOS # Provide a `shell` variable. Try not to `export` it, perhaps.
clearStoreIfPossible
rm -rf "$TEST_HOME"/.cache "$TEST_HOME"/.config "$TEST_HOME"/.local
cp ./simple.nix ./simple.builder.sh ./formatter.simple.sh "${config_nix}" "$TEST_HOME"
cd "$TEST_HOME"
nix formatter --help | grep "build or run the formatter"
nix fmt --help | grep "reformat your code"
nix fmt run --help | grep "reformat your code"
nix fmt build --help | grep "build"
cat << EOF > flake.nix
{
outputs = _: {
formatter.$system =
with import ./config.nix;
mkDerivation {
name = "formatter";
buildCommand = ''
mkdir -p \$out/bin
echo "#! ${shell}" > \$out/bin/formatter
cat \${./formatter.simple.sh} >> \$out/bin/formatter
chmod +x \$out/bin/formatter
'';
};
};
}
EOF
# No arguments check
[[ "$(nix fmt)" = "Formatting(0):" ]]
[[ "$(nix formatter run)" = "Formatting(0):" ]]
# Argument forwarding check
nix fmt ./file ./folder | grep 'Formatting(2): ./file ./folder'
nix formatter run ./file ./folder | grep 'Formatting(2): ./file ./folder'
# Build checks
## Defaults to a ./result.
nix formatter build | grep ".\+/bin/formatter"
[[ -L ./result ]]
rm result
## Can prevent the symlink.
nix formatter build --no-link
[[ ! -e ./result ]]
## Can change the symlink name.
nix formatter build --out-link my-result | grep ".\+/bin/formatter"
[[ -L ./my-result ]]
rm ./my-result
# Flake outputs check.
nix flake check
nix flake show | grep -P "package 'formatter'"