fork/home-manager

git clone https://git.julia.blue/fork/home-manager

Robert HelgessonMerge PR #421575790441

master
8.6 KiB291 linesraw
1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7  cfg = config.programs.vscode;
8
9  vscodePname = cfg.package.pname;
10  vscodeVersion = cfg.package.version;
11
12  jsonFormat = pkgs.formats.json { };
13
14  configDir = {
15    "vscode" = "Code";
16    "vscode-insiders" = "Code - Insiders";
17    "vscodium" = "VSCodium";
18  }.${vscodePname};
19
20  extensionDir = {
21    "vscode" = "vscode";
22    "vscode-insiders" = "vscode-insiders";
23    "vscodium" = "vscode-oss";
24  }.${vscodePname};
25
26  userDir = if pkgs.stdenv.hostPlatform.isDarwin then
27    "Library/Application Support/${configDir}/User"
28  else
29    "${config.xdg.configHome}/${configDir}/User";
30
31  configFilePath = "${userDir}/settings.json";
32  tasksFilePath = "${userDir}/tasks.json";
33  keybindingsFilePath = "${userDir}/keybindings.json";
34
35  snippetDir = "${userDir}/snippets";
36
37  # TODO: On Darwin where are the extensions?
38  extensionPath = ".${extensionDir}/extensions";
39
40  extensionJson = pkgs.vscode-utils.toExtensionJson cfg.extensions;
41  extensionJsonFile = pkgs.writeTextFile {
42    name = "extensions-json";
43    destination = "/share/vscode/extensions/extensions.json";
44    text = extensionJson;
45  };
46
47  mergedUserSettings = cfg.userSettings
48    // optionalAttrs (!cfg.enableUpdateCheck) { "update.mode" = "none"; }
49    // optionalAttrs (!cfg.enableExtensionUpdateCheck) {
50      "extensions.autoCheckUpdates" = false;
51    };
52in {
53  imports = [
54    (mkChangedOptionModule [ "programs" "vscode" "immutableExtensionsDir" ] [
55      "programs"
56      "vscode"
57      "mutableExtensionsDir"
58    ] (config: !config.programs.vscode.immutableExtensionsDir))
59  ];
60
61  options = {
62    programs.vscode = {
63      enable = mkEnableOption "Visual Studio Code";
64
65      package = mkOption {
66        type = types.package;
67        default = pkgs.vscode;
68        defaultText = literalExpression "pkgs.vscode";
69        example = literalExpression "pkgs.vscodium";
70        description = ''
71          Version of Visual Studio Code to install.
72        '';
73      };
74
75      enableUpdateCheck = mkOption {
76        type = types.bool;
77        default = true;
78        description = ''
79          Whether to enable update checks/notifications.
80        '';
81      };
82
83      enableExtensionUpdateCheck = mkOption {
84        type = types.bool;
85        default = true;
86        description = ''
87          Whether to enable update notifications for extensions.
88        '';
89      };
90
91      userSettings = mkOption {
92        type = jsonFormat.type;
93        default = { };
94        example = literalExpression ''
95          {
96            "files.autoSave" = "off";
97            "[nix]"."editor.tabSize" = 2;
98          }
99        '';
100        description = ''
101          Configuration written to Visual Studio Code's
102          {file}`settings.json`.
103        '';
104      };
105
106      userTasks = mkOption {
107        type = jsonFormat.type;
108        default = { };
109        example = literalExpression ''
110          {
111            version = "2.0.0";
112            tasks = [
113              {
114                type = "shell";
115                label = "Hello task";
116                command = "hello";
117              }
118            ];
119          }
120        '';
121        description = ''
122          Configuration written to Visual Studio Code's
123          {file}`tasks.json`.
124        '';
125      };
126
127      keybindings = mkOption {
128        type = types.listOf (types.submodule {
129          options = {
130            key = mkOption {
131              type = types.str;
132              example = "ctrl+c";
133              description = "The key or key-combination to bind.";
134            };
135
136            command = mkOption {
137              type = types.str;
138              example = "editor.action.clipboardCopyAction";
139              description = "The VS Code command to execute.";
140            };
141
142            when = mkOption {
143              type = types.nullOr (types.str);
144              default = null;
145              example = "textInputFocus";
146              description = "Optional context filter.";
147            };
148
149            # https://code.visualstudio.com/docs/getstarted/keybindings#_command-arguments
150            args = mkOption {
151              type = types.nullOr (jsonFormat.type);
152              default = null;
153              example = { direction = "up"; };
154              description = "Optional arguments for a command.";
155            };
156          };
157        });
158        default = [ ];
159        example = literalExpression ''
160          [
161            {
162              key = "ctrl+c";
163              command = "editor.action.clipboardCopyAction";
164              when = "textInputFocus";
165            }
166          ]
167        '';
168        description = ''
169          Keybindings written to Visual Studio Code's
170          {file}`keybindings.json`.
171        '';
172      };
173
174      extensions = mkOption {
175        type = types.listOf types.package;
176        default = [ ];
177        example = literalExpression "[ pkgs.vscode-extensions.bbenoist.nix ]";
178        description = ''
179          The extensions Visual Studio Code should be started with.
180        '';
181      };
182
183      mutableExtensionsDir = mkOption {
184        type = types.bool;
185        default = true;
186        example = false;
187        description = ''
188          Whether extensions can be installed or updated manually
189          or by Visual Studio Code.
190        '';
191      };
192
193      languageSnippets = mkOption {
194        type = jsonFormat.type;
195        default = { };
196        example = {
197          haskell = {
198            fixme = {
199              prefix = [ "fixme" ];
200              body = [ "$LINE_COMMENT FIXME: $0" ];
201              description = "Insert a FIXME remark";
202            };
203          };
204        };
205        description = "Defines user snippets for different languages.";
206      };
207
208      globalSnippets = mkOption {
209        type = jsonFormat.type;
210        default = { };
211        example = {
212          fixme = {
213            prefix = [ "fixme" ];
214            body = [ "$LINE_COMMENT FIXME: $0" ];
215            description = "Insert a FIXME remark";
216          };
217        };
218        description = "Defines global user snippets.";
219      };
220    };
221  };
222
223  config = mkIf cfg.enable {
224    home.packages = [ cfg.package ];
225
226    home.file = mkMerge [
227      (mkIf (mergedUserSettings != { }) {
228        "${configFilePath}".source =
229          jsonFormat.generate "vscode-user-settings" mergedUserSettings;
230      })
231      (mkIf (cfg.userTasks != { }) {
232        "${tasksFilePath}".source =
233          jsonFormat.generate "vscode-user-tasks" cfg.userTasks;
234      })
235      (mkIf (cfg.keybindings != [ ])
236        (let dropNullFields = filterAttrs (_: v: v != null);
237        in {
238          "${keybindingsFilePath}".source =
239            jsonFormat.generate "vscode-keybindings"
240            (map dropNullFields cfg.keybindings);
241        }))
242      (mkIf (cfg.extensions != [ ]) (let
243        subDir = "share/vscode/extensions";
244
245        # Adapted from https://discourse.nixos.org/t/vscode-extensions-setup/1801/2
246        toPaths = ext:
247          map (k: { "${extensionPath}/${k}".source = "${ext}/${subDir}/${k}"; })
248          (if ext ? vscodeExtUniqueId then
249            [ ext.vscodeExtUniqueId ]
250          else
251            builtins.attrNames (builtins.readDir (ext + "/${subDir}")));
252      in if cfg.mutableExtensionsDir then
253        mkMerge (concatMap toPaths cfg.extensions
254          ++ lib.optional (lib.versionAtLeast vscodeVersion "1.74.0") {
255            # Whenever our immutable extensions.json changes, force VSCode to regenerate
256            # extensions.json with both mutable and immutable extensions.
257            "${extensionPath}/.extensions-immutable.json" = {
258              text = extensionJson;
259              onChange = ''
260                $DRY_RUN_CMD rm $VERBOSE_ARG -f ${extensionPath}/{extensions.json,.init-default-profile-extensions}
261                $VERBOSE_ECHO "Regenerating VSCode extensions.json"
262                $DRY_RUN_CMD ${getExe cfg.package} --list-extensions > /dev/null
263              '';
264            };
265          })
266      else {
267        "${extensionPath}".source = let
268          combinedExtensionsDrv = pkgs.buildEnv {
269            name = "vscode-extensions";
270            paths = cfg.extensions
271              ++ lib.optional (lib.versionAtLeast vscodeVersion "1.74.0")
272              extensionJsonFile;
273          };
274        in "${combinedExtensionsDrv}/${subDir}";
275      }))
276
277      (mkIf (cfg.globalSnippets != { })
278        (let globalSnippets = "${snippetDir}/global.code-snippets";
279        in {
280          "${globalSnippets}".source =
281            jsonFormat.generate "user-snippet-global.code-snippets"
282            cfg.globalSnippets;
283        }))
284
285      (lib.mapAttrs' (language: snippet:
286        lib.nameValuePair "${snippetDir}/${language}.json" {
287          source = jsonFormat.generate "user-snippet-${language}.json" snippet;
288        }) cfg.languageSnippets)
289    ];
290  };
291}