about summary refs log tree commit diff
path: root/lib/generators.nix
diff options
context:
space:
mode:
authorMykola Orliuk <virkony@gmail.com>2023-04-09 22:21:36 +0200
committerMykola Orliuk <virkony@gmail.com>2023-04-23 01:07:58 +0200
commit4ec4c6fda90cec38b0878bf6e601f5df82ae5a8f (patch)
treec56e2d0cdcec4d7a03217c076b70453dad3f3c31 /lib/generators.nix
parentc1c73f72a6982646522bf6d676d734b68820b47d (diff)
lib/generators: add toLua/mkLuaInline
Suitable to simplify Lua-based configurations like neovim-lspconfig that
might need to interpolate Nix package paths.
Diffstat (limited to 'lib/generators.nix')
-rw-r--r--lib/generators.nix55
1 files changed, 55 insertions, 0 deletions
diff --git a/lib/generators.nix b/lib/generators.nix
index 4357a03533984..41c2862973f18 100644
--- a/lib/generators.nix
+++ b/lib/generators.nix
@@ -426,4 +426,59 @@ ${expr "" v}
       abort "generators.toDhall: cannot convert a null to Dhall"
     else
       builtins.toJSON v;
+
+  /*
+   * Translate a simple Nix expression to Lua representation with occasional
+   * Lua-inlines that can be construted by mkLuaInline function.
+   *
+   * generators.toLua {} {
+   *   cmd = [ "typescript-language-server" "--stdio" ];
+   *   settings.workspace.library = mkLuaInline ''vim.api.nvim_get_runtime_file("", true)'';
+   * }
+   *
+   *> {
+   *>   ["cmd"] = {
+   *>     "typescript-language-server",
+   *>     "--stdio"
+   *>   },
+   *>   ["settings"] = {
+   *>     ["workspace"] = {
+   *>       ["library"] = (vim.api.nvim_get_runtime_file("", true))
+   *>     }
+   *>   }
+   *> }
+   */
+  toLua = { indent ? "" }@args: v:
+    with builtins;
+    let
+      indent' = "${indent}  ";
+      args' = args // { indent = indent'; };
+      concatItems = concatStringsSep ",\n";
+      isLuaInline = { _type ? null, ... }: _type == "lua-inline";
+    in
+    if v == null then
+      "nil"
+    else if isInt v || isFloat v || isString v || isBool v then
+      builtins.toJSON v
+    else if isList v then
+      (if v == [ ] then "{}" else
+      "{\n${concatItems (map (value: "${indent'}${toLua args' value}") v)}\n${indent}}")
+    else if isAttrs v then
+      (
+        if isLuaInline v then
+          "(${v.expr})"
+        else if v == { } then
+          "{}"
+        else
+          "{\n${concatItems (
+            lib.attrsets.mapAttrsToList (key: value: "${indent'}[${builtins.toJSON key}] = ${toLua args' value}") v
+            )}\n${indent}}"
+      )
+    else
+      abort "generators.toLua: type ${typeOf v} is unsupported";
+
+  /*
+   * Mark string as Lua expression to be inlined when processed by toLua.
+   */
+  mkLuaInline = expr: { _type = "lua-inline"; inherit expr; };
 }