nixfmt icon indicating copy to clipboard operation
nixfmt copied to clipboard

Support single '-' operand and take it as reading from standard input

Open terlar opened this issue 2 years ago • 5 comments

Currently passing the argument - does not try to read the "file" from standard input.

E.g.:

nixfmt - < flake.nix

This is a common standard as suggested per POSIX.

This is especially required if using nixfmt via flake formatter nix fmt. As nix fmt does not handle standard input by default, but you need to run nix fmt -- -. One could also argue that it would be neat if nix fmt supported this.

terlar avatar Jul 19 '22 14:07 terlar

Speaking of compatibility with nix fmt. Just plainly running nix fmt doesn't work as that will invoke. nixfmt . which is also not supported by nixfmt.

$ nix fmt
nixfmt: .: openFile: inappropriate type (is a directory)

terlar avatar Jul 19 '22 14:07 terlar

Not the cleanest, but a current workaround is to create a wrapper and assign it to the formatter attribute, something like this:

pkgs.writeShellApplication {
  name = "nixfmt-wrapper";
  runtimeInputs = [ pkgs.coreutils pkgs.findutils pkgs.nixfmt ];
  text = ''
    case "$*" in
      (-) cat - | exec nixfmt;;
      (.) exec find . -name '*.nix' -exec nixfmt {} +;;
      (*) exec nixfmt "$@";;
    esac
  '';
});

terlar avatar Jul 19 '22 15:07 terlar

nixfmt already reads from stdin by default when no positional argument is passed.

Lucus16 avatar Jul 20 '22 12:07 Lucus16

I suppose this issue is about compatibility with nix fmt in general. I can't find any specification that needs to be followed in order to be compatible with it, but if there is, I don't mind implementing it.

Lucus16 avatar Jul 20 '22 13:07 Lucus16

Yeah, I guess nix fmt could be changed as well. Currently it does not support forwarding stdin by default, but you need to provide a - in order to get that behavior. This could probably be changed. Especially since it is a bit annoying to do | nix fmt -- - as opposed to just | nix fmt

Should I rename the issue to be about nix fmt compatibility. Perhaps this is something that should be raised on that end as well, seeing it is still part of the unstable API.

terlar avatar Jul 21 '22 09:07 terlar