fork/home-manager

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

Robert HelgessonMerge PR #421575790441

master
6.5 KiB213 linesraw
1{ config, lib, pkgs, ... }:
2
3with lib;
4
5let
6  inherit (pkgs.stdenv.hostPlatform) isDarwin;
7  inherit (lib.generators) toPlist;
8
9  cfg = config.launchd;
10  labelPrefix = "org.nix-community.home.";
11  dstDir = "${config.home.homeDirectory}/Library/LaunchAgents";
12
13  launchdConfig = { config, name, ... }: {
14    options = {
15      enable = mkEnableOption name;
16      config = mkOption {
17        type = types.submodule (import ./launchd.nix);
18        default = { };
19        example = literalExpression ''
20          {
21            ProgramArguments = [ "/usr/bin/say" "Good afternoon" ];
22            StartCalendarInterval = [
23              {
24                Hour = 12;
25                Minute = 0;
26              }
27            ];
28          }
29        '';
30        description = ''
31          Define a launchd job. See {manpage}`launchd.plist(5)` for details.
32        '';
33      };
34    };
35
36    config = { config.Label = mkDefault "${labelPrefix}${name}"; };
37  };
38
39  toAgent = config: pkgs.writeText "${config.Label}.plist" (toPlist { } config);
40
41  agentPlists =
42    mapAttrs' (n: v: nameValuePair "${v.config.Label}.plist" (toAgent v.config))
43    (filterAttrs (n: v: v.enable) cfg.agents);
44
45  agentsDrv = pkgs.runCommand "home-manager-agents" { } ''
46    mkdir -p "$out"
47
48    declare -A plists
49    plists=(${
50      concatStringsSep " "
51      (mapAttrsToList (name: value: "['${name}']='${value}'") agentPlists)
52    })
53
54    for dest in "''${!plists[@]}"; do
55      src="''${plists[$dest]}"
56      ln -s "$src" "$out/$dest"
57    done
58  '';
59in {
60  meta.maintainers = with maintainers; [ midchildan ];
61
62  options.launchd = {
63    enable = mkOption {
64      type = types.bool;
65      default = isDarwin;
66      defaultText = literalExpression "pkgs.stdenv.hostPlatform.isDarwin";
67      description = ''
68        Whether to enable Home Manager to define per-user daemons by making use
69        of launchd's LaunchAgents.
70      '';
71    };
72
73    agents = mkOption {
74      type = with types; attrsOf (submodule launchdConfig);
75      default = { };
76      description = "Define LaunchAgents.";
77    };
78  };
79
80  config = mkMerge [
81    {
82      assertions = [{
83        assertion = (cfg.enable && agentPlists != { }) -> isDarwin;
84        message = let names = lib.concatStringsSep ", " (attrNames agentPlists);
85        in "Must use Darwin for modules that require Launchd: " + names;
86      }];
87    }
88
89    (mkIf isDarwin {
90      home.extraBuilderCommands = ''
91        ln -s "${agentsDrv}" $out/LaunchAgents
92      '';
93
94      home.activation.checkLaunchAgents =
95        hm.dag.entryBefore [ "writeBoundary" ] ''
96          checkLaunchAgents() {
97            local oldDir newDir dstDir err
98            oldDir=""
99            err=0
100            if [[ -n "''${oldGenPath:-}" ]]; then
101              oldDir="$(readlink -m "$oldGenPath/LaunchAgents")" || err=$?
102              if (( err )); then
103                oldDir=""
104              fi
105            fi
106            newDir=${escapeShellArg agentsDrv}
107            dstDir=${escapeShellArg dstDir}
108
109            local oldSrcPath newSrcPath dstPath agentFile agentName
110
111            find -L "$newDir" -maxdepth 1 -name '*.plist' -type f -print0 \
112                | while IFS= read -rd "" newSrcPath; do
113              agentFile="''${newSrcPath##*/}"
114              agentName="''${agentFile%.plist}"
115              dstPath="$dstDir/$agentFile"
116              oldSrcPath="$oldDir/$agentFile"
117
118              if [[ ! -e "$dstPath" ]]; then
119                continue
120              fi
121
122              if ! cmp --quiet "$oldSrcPath" "$dstPath"; then
123                errorEcho "Existing file '$dstPath' is in the way of '$newSrcPath'"
124                exit 1
125              fi
126            done
127          }
128
129          checkLaunchAgents
130        '';
131
132      # NOTE: Launch Agent configurations can't be symlinked from the Nix store
133      # because it needs to be owned by the user running it.
134      home.activation.setupLaunchAgents =
135        hm.dag.entryAfter [ "writeBoundary" ] ''
136          setupLaunchAgents() {
137            local oldDir newDir dstDir domain err
138            oldDir=""
139            err=0
140            if [[ -n "''${oldGenPath:-}" ]]; then
141              oldDir="$(readlink -m "$oldGenPath/LaunchAgents")" || err=$?
142              if (( err )); then
143                oldDir=""
144              fi
145            fi
146            newDir="$(readlink -m "$newGenPath/LaunchAgents")"
147            dstDir=${escapeShellArg dstDir}
148            domain="gui/$UID"
149            err=0
150
151            local srcPath dstPath agentFile agentName i bootout_retries
152            bootout_retries=10
153
154            find -L "$newDir" -maxdepth 1 -name '*.plist' -type f -print0 \
155                | while IFS= read -rd "" srcPath; do
156              agentFile="''${srcPath##*/}"
157              agentName="''${agentFile%.plist}"
158              dstPath="$dstDir/$agentFile"
159
160              if cmp --quiet "$srcPath" "$dstPath"; then
161                continue
162              fi
163              if [[ -f "$dstPath" ]]; then
164                for (( i = 0; i < bootout_retries; i++ )); do
165                  $DRY_RUN_CMD /bin/launchctl bootout "$domain/$agentName" || err=$?
166                  if [[ -v DRY_RUN ]]; then
167                    break
168                  fi
169                  if (( err != 9216 )) &&
170                    ! /bin/launchctl print "$domain/$agentName" &> /dev/null; then
171                    break
172                  fi
173                  sleep 1
174                done
175                if (( i == bootout_retries )); then
176                  warnEcho "Failed to stop '$domain/$agentName'"
177                  return 1
178                fi
179              fi
180              $DRY_RUN_CMD install -Dm444 -T "$srcPath" "$dstPath"
181              $DRY_RUN_CMD /bin/launchctl bootstrap "$domain" "$dstPath"
182            done
183
184            if [[ ! -e "$oldDir" ]]; then
185              return
186            fi
187
188            find -L "$oldDir" -maxdepth 1 -name '*.plist' -type f -print0 \
189                | while IFS= read -rd "" srcPath; do
190              agentFile="''${srcPath##*/}"
191              agentName="''${agentFile%.plist}"
192              dstPath="$dstDir/$agentFile"
193              if [[ -e "$newDir/$agentFile" ]]; then
194                continue
195              fi
196
197              $DRY_RUN_CMD /bin/launchctl bootout "$domain/$agentName" || :
198              if [[ ! -e "$dstPath" ]]; then
199                continue
200              fi
201              if ! cmp --quiet "$srcPath" "$dstPath"; then
202                warnEcho "Skipping deletion of '$dstPath', since its contents have diverged"
203                continue
204              fi
205              $DRY_RUN_CMD rm -f $VERBOSE_ARG "$dstPath"
206            done
207          }
208
209          setupLaunchAgents
210        '';
211    })
212  ];
213}