Skip to content

Instantly share code, notes, and snippets.

@tennox
Created May 26, 2023 20:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tennox/87db667bac14062f71b46fb594985e5b to your computer and use it in GitHub Desktop.
Save tennox/87db667bac14062f71b46fb594985e5b to your computer and use it in GitHub Desktop.
Nix: Flatten VSCode settings to allow structured config

Instead of

{
  "editor.fontLigatures" = true;
  "editor.inlayHints.enabled" = "offUnlessPressed";
  "editor.inlayHints.fontSize" = 12;
}

I want to be able to write

{
  editor = {
    fontLigatures = true;
    inlayHints = {
      enabled = "offUnlessPressed";
      fontSize = 12;
    };
  };
}

But VSCode doesn't want to support it, so I wrote a helper function (using some lib functions which have yet to make it into nixpkgs):

{ lib, ... }:
with lib;
with builtins;
rec {
flattenVscodeSettings = settings:
flattenAttrs
(value: (!isAttrs value))
(concatStringsSep ".")
settings;
# RIPPED FROM PENDING PULL REQUEST: https://github.com/NixOS/nixpkgs/pull/221608
# SOURCE: https://github.com/NixOS/nixpkgs/blob/d65b3968a0a1eb7659b75b78160c6b75dde3ee57/lib/attrsets.nix#L499
flattenAttrs =
pred:
f:
attrs:
if pred attrs then attrs
else
listToAttrs (map (x: nameValuePair (f x.path) x.value) (collect'
(_: v: pred v || !isAttrs v)
(path: value: { inherit path value; })
attrs));
# SOURCE: https://github.com/NixOS/nixpkgs/blob/d65b3968a0a1eb7659b75b78160c6b75dde3ee57/lib/attrsets.nix#L420
collect' =
pred:
f:
attrs:
let
recurse = prefix: attrs:
concatMap
(name: visit (prefix ++ [ name ]) attrs.${name})
(attrNames attrs);
visit = path: value:
if pred path value then
[ (f path value) ]
else if isAttrs value then
recurse path value
else
[ ];
in
visit [ ] attrs;
}
@tennox
Copy link
Author

tennox commented May 26, 2023

NOTE: some settings might need to stay nested, so I make two sections in my settings config:

{
  userSettings = (lib.tx.flattenVscodeSettings {
    # ! THESE VALUES WILL BE FLATTENED ! #
    editor = {
      # ...
    };
  }) // {
    # PUT SETTINGS HERE WHICH SHOULD NOT BE FLATTENED

    terminal.integrated.env.linux = {
      EDITOR = "codium";
      VISUAL_DIFF = "codium -d";
      VISUAL = "codium --wait";
      GIT_EDITOR = "codium --wait";
    };
  };
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment