Looking for nix formatter which can convert nested attrests into "path" style notation

I’d like the following:

{ one = { two = { tree = 4; }; }; }

to be converted into:

{ one.two.tree = 4; }

Thanks!

Edit: I tried alejandra, nixpkgs-fmt and nixfmt but non of them seem to provide an option to do this

There is currently no formatter that would do what you are asking for.

All of them consider the nesting style users choice.

Also your example leaves it open how to proceed with the following example:

{
  foo = {
    bar = 1;
    baz = 2;
  };
};

Shall this be formatted into foo.bar and foo.baz? Or shal this be left untouched?

Maybe the formatting proposed by @adrian-gierakowski could be limited to attribute sets that recursively only have one child.

Thereby

{
  foo = {
    bar = 1;
    baz = 2;
  };
};

would stay the same, but

{
  foo = {
    bar = 1;
    baz = {
      boo = 2;
    };
  };
};

would become

{
  foo = {
    bar = 1;
    baz.boo = 2;
  };
};
2 Likes

@NobbZ

Shall this be formatted into foo.bar and foo.baz ? Or shal this be left untouched?

ideally that would be configurable, with an option to convert everything to path style or to do it based on number of children as suggersted by @PhilTaken

The use case here is converting configurations (generated by others tools) from json to nix

Why not use builtins.fromJson then?

1 Like

I consider this occasionally too. I think such a formatter should also rewrite e.g.:

{
  inputs.nixpkgs.url = "nixpkgs";
  inputs.flake-utils.url = "flake-utils";
  inputs.flake-utils.inputs.nixpkgs.follows = "nixpkgs";
}

to:

{
  inputs = {
    nixpkgs.url = "nixpkgs";
    flake-utils = {
      url = "flake-utils";
      inputs.nixpkgs.follows = "nixpkgs";
    };
  };
}

I find myself doing this a lot manually, and would probably enjoy hitting C-c f and my file magically being rearranged. Alphabetic ordering would be cool too in some places.

The problem is ultimately that this isn’t universally the right style, especially when you’re dealing with things like environment variable attrsets, e.g.:

env = {
  NIX_PATH  = "nixpkgs=/some/path";
};

vs

env.NIX_PATH = "nixpkgs=/some/path";

From experience, I find the latter less readable. There are also situations where you might want to split a bunch of submodules into conceptually similar blocks.

I think it would be cool if some tool that helps with this existed, but I don’t think it should be considered for a style guide or anything along those lines, which is what the existing formatters aim to be.

Maybe it could be added to GitHub - oxalica/nil: NIx Language server, an incremental analysis assistant for writing in Nix. as a code action?

Why not use builtins.fromJson then?

Because I want to be able to edit the files manually once they have been generated. The use case is a migration from some other system to nix: for example from kubernetes configs in yaml files (generated via helm and kustomize) to nix