Misterio77 / nix-config

Personal nixos and home-manager configurations.
https://m7.rs/git/nix-config/
MIT License
719 stars 42 forks source link

Remove hardcoded username from HM cli features #31

Open breezeight opened 5 months ago

no-mood commented 2 months ago

Related to this, I just rewrote my home-manager nixos module so I don't have to hardcode hostname and usernames.

So hosts/common/optional/home-manager.nix :

{
  inputs,
  outputs,
  lib,
  config,
  ...
}: let
  cfg = config.home-manager;
in {
  imports = [
    inputs.home-manager.nixosModules.home-manager
  ];

  # Don't pass arguments, instead make an option. Source:
  # https://discourse.nixos.org/t/passing-parameters-into-import/34082/4
  options.home-manager = {
    hostname = lib.mkOption {
      type = lib.types.nullOr lib.types.str;
      default = null;
    };

    usernames = lib.mkOption {
      type = lib.types.nullOr (lib.types.listOf lib.types.str);
      default = null;
    };
  };

  config = lib.mkIf ((cfg.hostname != null) && (cfg.usernames != null) && (lib.length cfg.usernames > 0)) {
    home-manager = {
      useUserPackages = lib.mkDefault true;
      extraSpecialArgs = {inherit inputs outputs;};

      users = builtins.listToAttrs (map (username: {
          name = username;
          value = import "${inputs.self}/home/${username}/${cfg.hostname}.nix"; # inputs.self references the flakes' root
        })
        cfg.usernames);
    };
  };
}

This requires some option to be set, like this: hosts/foo/default.nix:

{}:{
imports = [
  ../common/optional/home-manager.nix
];
  home-manager.usernames = ["misterio user2"];
  home-manager.hostname = "foo";
}

This allows for using a single module for home-manager, without needing to hardcode the path.