robin/weave

simple neovim wrapper for nix

git clone https://git.robinwobin.dev/robin/weave

robinwrapper: use laufey initb2c82bd

main
7.6 KiB273 linesraw
1{
2  lib,
3  lndir,
4  stdenvNoCC,
5  callPackage,
6  makeBinaryWrapper,
7  neovim-unwrapped,
8}:
9
10let
11  inherit (lib)
12    concatMapStrings
13    getExe
14    getVersion
15    makeBinPath
16    optionalString
17    ;
18
19  inherit (builtins) typeOf baseNameOf;
20in
21
22lib.extendMkDerivation {
23  constructDrv = stdenvNoCC.mkDerivation;
24
25  excludeDrvArgNames = [
26    "extraLuaPackages"
27  ];
28
29  extendDrvArgs =
30    _:
31    {
32      # neovim
33      pname ? "neovim",
34      versionSuffix ? "wrapped",
35
36      # you can choose the base, i choose neovim-unwrapped
37      basePackage ? neovim-unwrapped,
38
39      # extra lua packages
40      extraLuaPackages ? _: [ ],
41
42      # path, see there explanation below
43      extraPackages ? [ ],
44
45      # providers, these are the providers that will be enabled
46      providers ? { },
47
48      # extra init.lua, this is useful for setting up the environment
49      extraPreloadLua ? "",
50
51      # plugins
52      plugins ? { },
53      pluginOverrides ? null,
54      startPlugins ? [ ],
55      optPlugins ? [ ],
56
57      # our config
58      userConfig,
59
60      # PERF: clean runtime path so it only contains explicit runtime directories
61      # - removes directories from homedir as well as nix data directories
62      # - this means some programs that ship extra nvim data files need to be
63      #   explicitly added to the rtp with a package override
64      cleanRuntimePath ? false,
65      additionalRuntimePaths ? [ ],
66
67      # other customisation
68      aliases ? [ ],
69      keepDesktopFiles ? false,
70    }@args:
71    let
72      inherit (basePackage) lua;
73      luaEnv = lua.withPackages extraLuaPackages;
74      inherit (lua.pkgs) luaLib;
75
76      structuredPlugins = import ./plugins {
77        inherit lib startPlugins optPlugins;
78        plugins = callPackage ./plugins/package.nix {
79          pins = plugins;
80          inherit pluginOverrides;
81        };
82      };
83
84      # i couldn't chose a nice api between attrs and lists, so i just did both lol
85      attrsifiedProviders =
86        if lib.isAttrs providers then providers else (lib.genAttrs providers (_: true));
87
88      # merge providers attrs, with priority to the user providerd options
89      pluginProviders = {
90        node = false;
91        perl = false;
92        python = false;
93        python3 = false;
94        ruby = false;
95      }
96      // attrsifiedProviders;
97
98      mkResultingPath =
99        subdir: p:
100        "pack/${pname}/${subdir}/${if typeOf p == "path" then baseNameOf p else (p.pname or p.name)}";
101
102      config = stdenvNoCC.mkDerivation {
103        name = "neovim-config";
104        __structuredAttrs = true;
105
106        plugins = structuredPlugins.start ++ structuredPlugins.opt;
107        resultingPaths =
108          map (mkResultingPath "start") structuredPlugins.start
109          ++ map (mkResultingPath "opt") structuredPlugins.opt;
110
111        # didn't know you could do this. thanks getchiee
112        buildCommand =
113          # bash
114          ''
115            mkdir -pv $out/parser
116            mkdir -pv $out/pack/${pname}/{start,opt}
117
118            echo "generating preload.lua"
119            cat > $out/preload.lua <<EOF
120            vim.g.nix = true
121            package.path = "${luaLib.genLuaPathAbsStr luaEnv};$LUA_PATH" .. package.path
122            package.cpath = "${luaLib.genLuaCPathAbsStr luaEnv};$LUA_CPATH" .. package.cpath
123            vim.env.PATH = vim.env.PATH .. ":${makeBinPath extraPackages}"
124          ''
125          + (
126            if cleanRuntimePath then
127              (
128                let
129                  # if the runtime path is cleaned, it will be faster to leave the nvim
130                  # base paths at the start since most startup dependencies will be
131                  # found there.
132                  # $out will be put *before* the additionalRuntimePaths to replicate the behavior of `:prepend('$out')`.
133                  runtimePaths = [
134                    "${basePackage}/lib/nvim"
135                    "${basePackage}/share/nvim/runtime"
136                    "$out"
137                    "${userConfig}"
138                  ]
139                  ++ additionalRuntimePaths;
140                  rtp = builtins.concatStringsSep "," runtimePaths;
141                in
142                ''
143                  vim.o.runtimepath = "${rtp}"
144                  vim.o.packpath = "${rtp}"
145                ''
146              )
147            else
148              ''
149                vim.opt.runtimepath:prepend('$out')
150                vim.opt.packpath:prepend('$out')
151              ''
152          )
153          + ''
154            vim.loader.enable()
155
156            ${lib.concatMapAttrsStringSep "\n" (provider: enabled: ''
157              vim.g.loaded_${provider}_provider = ${if enabled then "1" else "0"}
158            '') pluginProviders}
159
160            ${extraPreloadLua}
161            EOF
162
163            shopt -s extglob dotglob
164            for (( i = 0; i < "''${#plugins[@]}"; i++ )); do
165              source="''${plugins[$i]}"
166              path="''${resultingPaths[$i]}"
167              dest="$out/$path"
168
169              if [[ -d "$dest" ]]; then
170                echo "warning: destination '$dest' already exists, skipping"
171                continue
172              fi
173
174              mkdir -p "$dest"
175
176              tolink=("$source/"!(parser))
177              if (( "''${#tolink[@]}" )); then
178                ln -ns "''${tolink[@]}" -t "$dest"
179              fi
180
181              if [[ -d "$source/parser" && -n "$(ls -A "$source/parser")" ]]; then
182                mkdir -p "$out/parser"
183                ln -nsf "$source/parser/"* -t "$out/parser"
184              fi
185            done
186            shopt -u extglob dotglob
187
188            ${getExe basePackage} \
189              -n -u NONE -i NONE \
190              --headless \
191              -c "set packpath=$out" \
192              -c "packloadall" \
193              -c "helptags ALL" \
194              +"quit!"
195
196            find "$out/pack/${pname}" -type d -empty -print -delete
197
198            mkdir "$out/nix-support"
199            for i in $(find -L "$out" -name 'propagated-build-inputs'); do
200              cat "$i" >> "$out/nix-support/propagated-build-inputs"
201            done
202          '';
203      };
204    in
205    {
206      inherit pname;
207      version = "${args.version or (getVersion basePackage)}${
208        if versionSuffix != "" then "-${versionSuffix}" else ""
209      }";
210
211      # don't allow for simple arugments here these **should** remain this way
212      # so the wrapper works correctly
213      __structuredAttrs = true;
214      strictDeps = true;
215
216      # this won't really remove anything since we still are running fixup on basePackage and the config
217      # but it does speed up the build speed
218      dontUnpack = true;
219      dontFixup = true;
220      dontConfigure = true;
221      dontRewriteSymlinks = true;
222
223      nativeBuildInputs = args.nativeBuildInputs or [ ] ++ [
224        makeBinaryWrapper
225        lndir
226      ];
227
228      wrapperArgs = [
229        "--set-default"
230        "NVIM_CONFIG"
231        "${userConfig}"
232
233        "--add-flag"
234        "--cmd"
235        "--add-flag"
236        "source ${config}/preload.lua"
237
238        "--set-default"
239        "NVIM_APPNAME"
240        pname
241      ]
242      ++ args.wrapperArgs or [ ];
243
244      installPhase = ''
245        runHook preInstall
246
247        mkdir -p $out
248        lndir -silent ${basePackage} $out
249
250        ${optionalString (!keepDesktopFiles) "rm -rf $out/share/applications"}
251
252        wrapProgram $out/bin/nvim "''${wrapperArgs[@]}"
253
254        ${concatMapStrings (alias: ''
255          ln -s $out/bin/nvim $out/bin/${alias}
256        '') aliases}
257
258        runHook postInstall
259      '';
260
261      passthru = {
262        inherit config;
263      }
264      // args.passthru or { };
265
266      meta =
267        basePackage.meta
268        // {
269          priority = (basePackage.meta.priority or lib.meta.defaultPriority) - 1;
270        }
271        // args.meta or { };
272    };
273}