Skip to content

Commit 22c2578

Browse files
committed
Add a --print-command option to nix fmt
For example, here's what this does in `nixpkgs`: $ nix fmt --print-command /nix/store/cb9w44vkhk2x4adfxwgdkkf5gjmm856j-treefmt/bin/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: https://github.com/nvimtools/none-ls.nvim/blob/786460723170bda9e9f95c55a382d21436575297/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: nvimtools/none-ls.nvim#272. With this extra option for `nix fmt`, I'd get to delete all this akward code, and it would be easier for other folks to build performant editor integrations for `nix fmt`.
1 parent 876f676 commit 22c2578

File tree

2 files changed

+16
-2
lines changed

2 files changed

+16
-2
lines changed

src/nix/fmt.cc

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,17 @@ using namespace nix;
77

88
struct CmdFmt : SourceExprCommand {
99
std::vector<std::string> args;
10+
bool print_command = false;
1011

11-
CmdFmt() { expectArgs({.label = "args", .handler = {&args}}); }
12+
CmdFmt() {
13+
expectArgs({.label = "args", .handler = {&args}});
14+
15+
addFlag({
16+
.longName = "print-command",
17+
.description = "Print the formatting command instead of executing the command.",
18+
.handler = {&print_command, true},
19+
});
20+
}
1221

1322
std::string description() override {
1423
return "reformat your code in the standard style";
@@ -48,7 +57,11 @@ struct CmdFmt : SourceExprCommand {
4857
// we are about to exec out of this process without running C++ destructors.
4958
evalState->evalCaches.clear();
5059

51-
execProgramInStore(store, UseLookupPath::DontUse, app.program, programArgs);
60+
if(print_command) {
61+
logger->cout("%s", app.program);
62+
} else {
63+
execProgramInStore(store, UseLookupPath::DontUse, app.program, programArgs);
64+
}
5265
};
5366
};
5467

tests/functional/fmt.sh

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,5 +34,6 @@ EOF
3434
[[ "$(nix fmt)" = "Formatting(0):" ]]
3535
# Argument forwarding check
3636
nix fmt ./file ./folder | grep 'Formatting(2): ./file ./folder'
37+
nix fmt --print-command | grep ".\+/bin/formatter"
3738
nix flake check
3839
nix flake show | grep -P "package 'formatter'"

0 commit comments

Comments
 (0)