fork/home-manager

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

Robert Helgessonhome-manager: handle profile list in Nix >2.17c3ab5ea0

master
23.5 KiB766 linesraw
1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6
7  inherit (config.home) stateVersion;
8
9  cfg = config.home;
10
11  languageSubModule = types.submodule {
12    options = {
13      base = mkOption {
14        default = null;
15        type = types.nullOr types.str;
16        description = ''
17          The language to use unless overridden by a more specific option.
18        '';
19      };
20
21      ctype = mkOption {
22        default = null;
23        type = types.nullOr types.str;
24        description = ''
25          Character classification category.
26        '';
27      };
28
29      numeric = mkOption {
30        default = null;
31        type = types.nullOr types.str;
32        description = ''
33          The language to use for numerical values.
34        '';
35      };
36
37      time = mkOption {
38        default = null;
39        type = types.nullOr types.str;
40        description = ''
41          The language to use for formatting times.
42        '';
43      };
44
45      collate = mkOption {
46        default = null;
47        type = types.nullOr types.str;
48        description = ''
49          The language to use for collation (alphabetical ordering).
50        '';
51      };
52
53      monetary = mkOption {
54        default = null;
55        type = types.nullOr types.str;
56        description = ''
57          The language to use for formatting currencies and money amounts.
58        '';
59      };
60
61      messages = mkOption {
62        default = null;
63        type = types.nullOr types.str;
64        description = ''
65          The language to use for messages, application UI languages, etc.
66        '';
67      };
68
69      paper = mkOption {
70        default = null;
71        type = types.nullOr types.str;
72        description = ''
73          The language to use for paper sizes.
74        '';
75      };
76
77      name = mkOption {
78        default = null;
79        type = types.nullOr types.str;
80        description = ''
81          The language to use for personal names.
82        '';
83      };
84
85      address = mkOption {
86        default = null;
87        type = types.nullOr types.str;
88        description = ''
89          The language to use for addresses.
90        '';
91      };
92
93      telephone = mkOption {
94        default = null;
95        type = types.nullOr types.str;
96        description = ''
97          The language to use for telephone numbers.
98        '';
99      };
100
101      measurement = mkOption {
102        default = null;
103        type = types.nullOr types.str;
104        description = ''
105          The language to use for measurement values.
106        '';
107      };
108
109    };
110  };
111
112  keyboardSubModule = types.submodule {
113    options = {
114      layout = mkOption {
115        type = with types; nullOr str;
116        default =
117          if versionAtLeast config.home.stateVersion "19.09"
118          then null
119          else "us";
120        defaultText = literalExpression "null";
121        description = ''
122          Keyboard layout. If `null`, then the system
123          configuration will be used.
124
125          This defaults to `null` for state
126          version ≥ 19.09 and `"us"` otherwise.
127        '';
128      };
129
130      model = mkOption {
131        type = with types; nullOr str;
132        default = null;
133        example = "presario";
134        description = ''
135          Keyboard model.
136        '';
137      };
138
139      options = mkOption {
140        type = types.listOf types.str;
141        default = [];
142        example = ["grp:caps_toggle" "grp_led:scroll"];
143        description = ''
144          X keyboard options; layout switching goes here.
145        '';
146      };
147
148      variant = mkOption {
149        type = with types; nullOr str;
150        default =
151          if versionAtLeast config.home.stateVersion "19.09"
152          then null
153          else "";
154        defaultText = literalExpression "null";
155        example = "colemak";
156        description = ''
157          X keyboard variant. If `null`, then the
158          system configuration will be used.
159
160          This defaults to `null` for state
161          version ≥ 19.09 and `""` otherwise.
162        '';
163      };
164    };
165  };
166
167in
168
169{
170  meta.maintainers = [ maintainers.rycee ];
171
172  imports = [
173    (mkRemovedOptionModule [ "home" "sessionVariableSetter" ] ''
174      Session variables are now always set through the shell. This is
175      done automatically if the shell configuration is managed by Home
176      Manager. If not, then you must source the
177
178        ~/.nix-profile/etc/profile.d/hm-session-vars.sh
179
180      file yourself.
181    '')
182  ];
183
184  options = {
185    home.username = mkOption {
186      type = types.str;
187      defaultText = literalExpression ''
188        "$USER"   for state version < 20.09,
189        undefined for state version ≥ 20.09
190      '';
191      example = "jane.doe";
192      description = "The user's username.";
193    };
194
195    home.homeDirectory = mkOption {
196      type = types.path;
197      defaultText = literalExpression ''
198        "$HOME"   for state version < 20.09,
199        undefined for state version ≥ 20.09
200      '';
201      apply = toString;
202      example = "/home/jane.doe";
203      description = "The user's home directory. Must be an absolute path.";
204    };
205
206    home.profileDirectory = mkOption {
207      type = types.path;
208      defaultText = literalExpression ''
209        "''${home.homeDirectory}/.nix-profile"  or
210        "/etc/profiles/per-user/''${home.username}"
211      '';
212      readOnly = true;
213      description = ''
214        The profile directory where Home Manager generations are installed.
215      '';
216    };
217
218    home.language = mkOption {
219      type = languageSubModule;
220      default = {};
221      description = "Language configuration.";
222    };
223
224    home.keyboard = mkOption {
225      type = types.nullOr keyboardSubModule;
226      default = if versionAtLeast stateVersion "21.11" then null else { };
227      defaultText = literalExpression ''
228        "{ }"  for state version < 21.11,
229        "null" for state version ≥ 21.11
230      '';
231      description = ''
232        Keyboard configuration. Set to `null` to
233        disable Home Manager keyboard management.
234      '';
235    };
236
237    home.shellAliases = mkOption {
238      type = with types; attrsOf str;
239      default = { };
240      example = literalExpression ''
241        {
242          g = "git";
243          "..." = "cd ../..";
244        }
245      '';
246      description = ''
247        An attribute set that maps aliases (the top level attribute names
248        in this option) to command strings or directly to build outputs.
249
250        This option should only be used to manage simple aliases that are
251        compatible across all shells. If you need to use a shell specific
252        feature then make sure to use a shell specific option, for example
253        [](#opt-programs.bash.shellAliases) for Bash.
254      '';
255    };
256
257    home.sessionVariables = mkOption {
258      default = {};
259      type = with types; lazyAttrsOf (oneOf [ str path int float ]);
260      example = { EDITOR = "emacs"; GS_OPTIONS = "-sPAPERSIZE=a4"; };
261      description = ''
262        Environment variables to always set at login.
263
264        The values may refer to other environment variables using
265        POSIX.2 style variable references. For example, a variable
266        {var}`parameter` may be referenced as
267        `$parameter` or `''${parameter}`. A
268        default value `foo` may be given as per
269        `''${parameter:-foo}` and, similarly, an alternate
270        value `bar` can be given as per
271        `''${parameter:+bar}`.
272
273        Note, these variables may be set in any order so no session
274        variable may have a runtime dependency on another session
275        variable. In particular code like
276        ```nix
277        home.sessionVariables = {
278          FOO = "Hello";
279          BAR = "$FOO World!";
280        };
281        ```
282        may not work as expected. If you need to reference another
283        session variable, then do so inside Nix instead. The above
284        example then becomes
285        ```nix
286        home.sessionVariables = {
287          FOO = "Hello";
288          BAR = "''${config.home.sessionVariables.FOO} World!";
289        };
290        ```
291      '';
292    };
293
294    home.sessionVariablesPackage = mkOption {
295      type = types.package;
296      internal = true;
297      description = ''
298        The package containing the
299        {file}`hm-session-vars.sh` file.
300      '';
301    };
302
303    home.sessionPath = mkOption {
304      type = with types; listOf str;
305      default = [ ];
306      example = [
307        "$HOME/.local/bin"
308        "\${xdg.configHome}/emacs/bin"
309        ".git/safe/../../bin"
310      ];
311      description = ''
312        Extra directories to add to {env}`PATH`.
313
314        These directories are added to the {env}`PATH` variable in a
315        double-quoted context, so expressions like `$HOME` are
316        expanded by the shell. However, since expressions like `~` or
317        `*` are escaped, they will end up in the {env}`PATH`
318        verbatim.
319      '';
320    };
321
322    home.sessionVariablesExtra = mkOption {
323      type = types.lines;
324      default = "";
325      internal = true;
326      description = ''
327        Extra configuration to add to the
328        {file}`hm-session-vars.sh` file.
329      '';
330    };
331
332    home.packages = mkOption {
333      type = types.listOf types.package;
334      default = [];
335      description = "The set of packages to appear in the user environment.";
336    };
337
338    home.extraOutputsToInstall = mkOption {
339      type = types.listOf types.str;
340      default = [];
341      example = [ "doc" "info" "devdoc" ];
342      description = ''
343        List of additional package outputs of the packages
344        {var}`home.packages` that should be installed into
345        the user environment.
346      '';
347    };
348
349    home.path = mkOption {
350      internal = true;
351      description = "The derivation installing the user packages.";
352    };
353
354    home.emptyActivationPath = mkOption {
355      internal = true;
356      type = types.bool;
357      default = versionAtLeast stateVersion "22.11";
358      defaultText = literalExpression ''
359        false   for state version < 22.11,
360        true    for state version ≥ 22.11
361      '';
362      description = ''
363        Whether the activation script should start with an empty
364        {env}`PATH` variable. When `false` then the
365        user's {env}`PATH` will be accessible in the script. It is
366        recommended to keep this at `true` to avoid
367        uncontrolled use of tools found in PATH.
368      '';
369    };
370
371    home.activation = mkOption {
372      type = hm.types.dagOf types.str;
373      default = {};
374      example = literalExpression ''
375        {
376          myActivationAction = lib.hm.dag.entryAfter ["writeBoundary"] '''
377            $DRY_RUN_CMD ln -s $VERBOSE_ARG \
378                ''${builtins.toPath ./link-me-directly} $HOME
379          ''';
380        }
381      '';
382      description = ''
383        The activation scripts blocks to run when activating a Home
384        Manager generation. Any entry here should be idempotent,
385        meaning running twice or more times produces the same result
386        as running it once.
387
388        If the script block produces any observable side effect, such
389        as writing or deleting files, then it
390        *must* be placed after the special
391        `writeBoundary` script block. Prior to the
392        write boundary one can place script blocks that verifies, but
393        does not modify, the state of the system and exits if an
394        unexpected state is found. For example, the
395        `checkLinkTargets` script block checks for
396        collisions between non-managed files and files defined in
397        [](#opt-home.file).
398
399        A script block should respect the {var}`DRY_RUN`
400        variable, if it is set then the actions taken by the script
401        should be logged to standard out and not actually performed.
402        The variable {var}`DRY_RUN_CMD` is set to
403        {command}`echo` if dry run is enabled.
404
405        A script block should also respect the
406        {var}`VERBOSE` variable, and if set print
407        information on standard out that may be useful for debugging
408        any issue that may arise. The variable
409        {var}`VERBOSE_ARG` is set to
410        {option}`--verbose` if verbose output is enabled.
411      '';
412    };
413
414    home.activationPackage = mkOption {
415      internal = true;
416      type = types.package;
417      description = "The package containing the complete activation script.";
418    };
419
420    home.extraActivationPath = mkOption {
421      internal = true;
422      type = types.listOf types.package;
423      default = [ ];
424      description = ''
425        Extra packages to add to {env}`PATH` within the activation
426        script.
427      '';
428    };
429
430    home.extraBuilderCommands = mkOption {
431      type = types.lines;
432      default = "";
433      internal = true;
434      description = ''
435        Extra commands to run in the Home Manager generation builder.
436      '';
437    };
438
439    home.extraProfileCommands = mkOption {
440      type = types.lines;
441      default = "";
442      internal = true;
443      description = ''
444        Extra commands to run in the Home Manager profile builder.
445      '';
446    };
447
448    home.enableNixpkgsReleaseCheck = mkOption {
449      type = types.bool;
450      default = true;
451      description = ''
452        Determines whether to check for release version mismatch between Home
453        Manager and Nixpkgs. Using mismatched versions is likely to cause errors
454        and unexpected behavior. It is therefore highly recommended to use a
455        release of Home Manager that corresponds with your chosen release of
456        Nixpkgs.
457
458        When this option is enabled and a mismatch is detected then a warning
459        will be printed when the user configuration is being built.
460      '';
461    };
462  };
463
464  config = {
465    assertions = [
466      {
467        assertion = config.home.username != "";
468        message = "Username could not be determined";
469      }
470      {
471        assertion = config.home.homeDirectory != "";
472        message = "Home directory could not be determined";
473      }
474    ];
475
476    warnings =
477      let
478        hmRelease = config.home.version.release;
479        nixpkgsRelease = lib.trivial.release;
480        releaseMismatch =
481          config.home.enableNixpkgsReleaseCheck
482          && hmRelease != nixpkgsRelease;
483      in
484        optional releaseMismatch ''
485          You are using
486
487            Home Manager version ${hmRelease} and
488            Nixpkgs version ${nixpkgsRelease}.
489
490          Using mismatched versions is likely to cause errors and unexpected
491          behavior. It is therefore highly recommended to use a release of Home
492          Manager that corresponds with your chosen release of Nixpkgs.
493
494          If you insist then you can disable this warning by adding
495
496            home.enableNixpkgsReleaseCheck = false;
497
498          to your configuration.
499        '';
500
501    home.username =
502      mkIf (versionOlder config.home.stateVersion "20.09")
503        (mkDefault (builtins.getEnv "USER"));
504    home.homeDirectory =
505      mkIf (versionOlder config.home.stateVersion "20.09")
506        (mkDefault (builtins.getEnv "HOME"));
507
508    home.profileDirectory =
509      if config.submoduleSupport.enable
510        && config.submoduleSupport.externalPackageInstall
511      then "/etc/profiles/per-user/${cfg.username}"
512      else if config.nix.enable && (config.nix.settings.use-xdg-base-directories or false)
513      then "${config.xdg.stateHome}/nix/profile"
514      else cfg.homeDirectory + "/.nix-profile";
515
516    programs.bash.shellAliases = cfg.shellAliases;
517    programs.zsh.shellAliases = cfg.shellAliases;
518    programs.fish.shellAliases = cfg.shellAliases;
519
520    home.sessionVariables =
521      let
522        maybeSet = n: v: optionalAttrs (v != null) { ${n} = v; };
523      in
524        (maybeSet "LANG" cfg.language.base)
525        //
526        (maybeSet "LC_CTYPE" cfg.language.ctype)
527        //
528        (maybeSet "LC_NUMERIC" cfg.language.numeric)
529        //
530        (maybeSet "LC_TIME" cfg.language.time)
531        //
532        (maybeSet "LC_COLLATE" cfg.language.collate)
533        //
534        (maybeSet "LC_MONETARY" cfg.language.monetary)
535        //
536        (maybeSet "LC_MESSAGES" cfg.language.messages)
537        //
538        (maybeSet "LC_PAPER" cfg.language.paper)
539        //
540        (maybeSet "LC_NAME" cfg.language.name)
541        //
542        (maybeSet "LC_ADDRESS" cfg.language.address)
543        //
544        (maybeSet "LC_TELEPHONE" cfg.language.telephone)
545        //
546        (maybeSet "LC_MEASUREMENT" cfg.language.measurement);
547
548    # Provide a file holding all session variables.
549    home.sessionVariablesPackage = pkgs.writeTextFile {
550      name = "hm-session-vars.sh";
551      destination = "/etc/profile.d/hm-session-vars.sh";
552      text = ''
553        # Only source this once.
554        if [ -n "$__HM_SESS_VARS_SOURCED" ]; then return; fi
555        export __HM_SESS_VARS_SOURCED=1
556
557        ${config.lib.shell.exportAll cfg.sessionVariables}
558      '' + lib.optionalString (cfg.sessionPath != [ ]) ''
559        export PATH="$PATH''${PATH:+:}${concatStringsSep ":" cfg.sessionPath}"
560      '' + cfg.sessionVariablesExtra;
561    };
562
563    home.packages = [ config.home.sessionVariablesPackage ];
564
565    # A dummy entry acting as a boundary between the activation
566    # script's "check" and the "write" phases.
567    home.activation.writeBoundary = hm.dag.entryAnywhere "";
568
569    # Install packages to the user environment.
570    #
571    # Note, sometimes our target may not allow modification of the Nix
572    # store and then we cannot rely on `nix-env -i`. This is the case,
573    # for example, if we are running as a NixOS module and building a
574    # virtual machine. Then we must instead rely on an external
575    # mechanism for installing packages, which in NixOS is provided by
576    # the `users.users.<name?>.packages` option. The activation
577    # command is still needed since some modules need to run their
578    # activation commands after the packages are guaranteed to be
579    # installed.
580    #
581    # In case the user has moved from a user-install of Home Manager
582    # to a submodule managed one we attempt to uninstall the
583    # `home-manager-path` package if it is installed.
584    home.activation.installPackages = hm.dag.entryAfter ["writeBoundary"] (
585      if config.submoduleSupport.externalPackageInstall
586      then
587        ''
588          if [[ -e $HOME/.nix-profile/manifest.json ]] ; then
589            nix profile list \
590              | { grep 'home-manager-path$' || test $? = 1; } \
591              | cut -d ' ' -f 4 \
592              | xargs -t $DRY_RUN_CMD nix profile remove $VERBOSE_ARG
593          else
594            if nix-env -q | grep '^home-manager-path$'; then
595              $DRY_RUN_CMD nix-env -e home-manager-path
596            fi
597          fi
598        ''
599      else
600        ''
601          function nixProfileList() {
602            # We attempt to use `--json` first (added in Nix 2.17). Otherwise attempt to
603            # parse the legacy output format.
604            {
605              nix profile list --json 2>/dev/null \
606                | jq -r --arg name "$1" '.elements[].storePaths[] | select(endswith($name))'
607            } || {
608              nix profile list \
609                | { grep "$1\$" || test $? = 1; } \
610                | cut -d ' ' -f 4
611            }
612          }
613
614          function nixRemoveProfileByName() {
615              nixProfileList "$1" | xargs -t $DRY_RUN_CMD nix profile remove $VERBOSE_ARG
616          }
617
618          function nixReplaceProfile() {
619            local oldNix="$(command -v nix)"
620
621            nixRemoveProfileByName 'home-manager-path'
622
623            $DRY_RUN_CMD $oldNix profile install $1
624          }
625
626          if [[ -e $HOME/.nix-profile/manifest.json ]] ; then
627            INSTALL_CMD="nix profile install"
628            INSTALL_CMD_ACTUAL="nixReplaceProfile"
629            LIST_CMD="nix profile list"
630            REMOVE_CMD_SYNTAX='nix profile remove {number | store path}'
631          else
632            INSTALL_CMD="nix-env -i"
633            INSTALL_CMD_ACTUAL="$DRY_RUN_CMD nix-env -i"
634            LIST_CMD="nix-env -q"
635            REMOVE_CMD_SYNTAX='nix-env -e {package name}'
636          fi
637
638          if ! $INSTALL_CMD_ACTUAL ${cfg.path} ; then
639            echo
640            _iError $'Oops, Nix failed to install your new Home Manager profile!\n\nPerhaps there is a conflict with a package that was installed using\n"%s"? Try running\n\n    %s\n\nand if there is a conflicting package you can remove it with\n\n    %s\n\nThen try activating your Home Manager configuration again.' "$INSTALL_CMD" "$LIST_CMD" "$REMOVE_CMD_SYNTAX"
641            exit 1
642          fi
643          unset -f nixProfileList nixRemoveProfileByName nixReplaceProfile
644          unset INSTALL_CMD INSTALL_CMD_ACTUAL LIST_CMD REMOVE_CMD_SYNTAX
645        ''
646    );
647
648    # Text containing Bash commands that will initialize the Home Manager Bash
649    # library. Most importantly, this will prepare for using translated strings
650    # in the `hm-modules` text domain.
651    lib.bash.initHomeManagerLib =
652      let
653        domainDir = pkgs.runCommand "hm-modules-messages" {
654          nativeBuildInputs = [ pkgs.buildPackages.gettext ];
655        } ''
656          for path in ${./po}/*.po; do
657            lang="''${path##*/}"
658            lang="''${lang%%.*}"
659            mkdir -p "$out/$lang/LC_MESSAGES"
660            msgfmt -o "$out/$lang/LC_MESSAGES/hm-modules.mo" "$path"
661          done
662        '';
663      in
664        ''
665          export TEXTDOMAIN=hm-modules
666          export TEXTDOMAINDIR=${domainDir}
667          source ${../lib/bash/home-manager.sh}
668        '';
669
670    home.activationPackage =
671      let
672        mkCmd = res: ''
673            _iNote "Activating %s" "${res.name}"
674            ${res.data}
675          '';
676        sortedCommands = hm.dag.topoSort cfg.activation;
677        activationCmds =
678          if sortedCommands ? result then
679            concatStringsSep "\n" (map mkCmd sortedCommands.result)
680          else
681            abort ("Dependency cycle in activation script: "
682              + builtins.toJSON sortedCommands);
683
684        # Programs that always should be available on the activation
685        # script's PATH.
686        activationBinPaths = lib.makeBinPath (
687          with pkgs; [
688            bash
689            coreutils
690            diffutils           # For `cmp` and `diff`.
691            findutils
692            gettext
693            gnugrep
694            gnused
695            jq
696            ncurses             # For `tput`.
697          ]
698          ++ config.home.extraActivationPath
699        )
700        + (
701          # Add path of the Nix binaries, if a Nix package is configured, then
702          # use that one, otherwise grab the path of the nix-env tool.
703          if config.nix.enable && config.nix.package != null then
704            ":${config.nix.package}/bin"
705          else
706            ":$(${pkgs.coreutils}/bin/dirname $(${pkgs.coreutils}/bin/readlink -m $(type -p nix-env)))"
707        )
708        + optionalString (!cfg.emptyActivationPath) "\${PATH:+:}$PATH";
709
710        activationScript = pkgs.writeShellScript "activation-script" ''
711          set -eu
712          set -o pipefail
713
714          cd $HOME
715
716          export PATH="${activationBinPaths}"
717          ${config.lib.bash.initHomeManagerLib}
718
719          ${builtins.readFile ./lib-bash/activation-init.sh}
720
721          if [[ ! -v SKIP_SANITY_CHECKS ]]; then
722            checkUsername ${escapeShellArg config.home.username}
723            checkHomeDirectory ${escapeShellArg config.home.homeDirectory}
724          fi
725
726          ${activationCmds}
727        '';
728      in
729        pkgs.runCommand
730          "home-manager-generation"
731          {
732            preferLocalBuild = true;
733          }
734          ''
735            mkdir -p $out
736
737            echo "${config.home.version.full}" > $out/hm-version
738
739            cp ${activationScript} $out/activate
740
741            mkdir $out/bin
742            ln -s $out/activate $out/bin/home-manager-generation
743
744            substituteInPlace $out/activate \
745              --subst-var-by GENERATION_DIR $out
746
747            ln -s ${config.home-files} $out/home-files
748            ln -s ${cfg.path} $out/home-path
749
750            ${cfg.extraBuilderCommands}
751          '';
752
753    home.path = pkgs.buildEnv {
754      name = "home-manager-path";
755
756      paths = cfg.packages;
757      inherit (cfg) extraOutputsToInstall;
758
759      postBuild = cfg.extraProfileCommands;
760
761      meta = {
762        description = "Environment of packages installed through home-manager";
763      };
764    };
765  };
766}