fork/home-manager

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

Robert HelgessonMerge PR #421575790441

master
14.6 KiB409 linesraw
1{ pkgs, config, lib, ... }:
2
3with lib;
4
5let
6
7  cfg = filterAttrs (n: f: f.enable) config.home.file;
8
9  homeDirectory = config.home.homeDirectory;
10
11  fileType = (import lib/file-type.nix {
12    inherit homeDirectory lib pkgs;
13  }).fileType;
14
15  sourceStorePath = file:
16    let
17      sourcePath = toString file.source;
18      sourceName = config.lib.strings.storeFileName (baseNameOf sourcePath);
19    in
20      if builtins.hasContext sourcePath
21      then file.source
22      else builtins.path { path = file.source; name = sourceName; };
23
24in
25
26{
27  options = {
28    home.file = mkOption {
29      description = "Attribute set of files to link into the user home.";
30      default = {};
31      type = fileType "home.file" "{env}`HOME`" homeDirectory;
32    };
33
34    home-files = mkOption {
35      type = types.package;
36      internal = true;
37      description = "Package to contain all home files";
38    };
39  };
40
41  config = {
42    assertions = [(
43      let
44        dups =
45          attrNames
46            (filterAttrs (n: v: v > 1)
47            (foldAttrs (acc: v: acc + v) 0
48            (mapAttrsToList (n: v: { ${v.target} = 1; }) cfg)));
49        dupsStr = concatStringsSep ", " dups;
50      in {
51        assertion = dups == [];
52        message = ''
53          Conflicting managed target files: ${dupsStr}
54
55          This may happen, for example, if you have a configuration similar to
56
57              home.file = {
58                conflict1 = { source = ./foo.nix; target = "baz"; };
59                conflict2 = { source = ./bar.nix; target = "baz"; };
60              }'';
61      })
62    ];
63
64    lib.file.mkOutOfStoreSymlink = path:
65      let
66        pathStr = toString path;
67        name = hm.strings.storeFileName (baseNameOf pathStr);
68      in
69        pkgs.runCommandLocal name {} ''ln -s ${escapeShellArg pathStr} $out'';
70
71    # This verifies that the links we are about to create will not
72    # overwrite an existing file.
73    home.activation.checkLinkTargets = hm.dag.entryBefore ["writeBoundary"] (
74      let
75        # Paths that should be forcibly overwritten by Home Manager.
76        # Caveat emptor!
77        forcedPaths =
78          concatMapStringsSep " " (p: ''"$HOME"/${escapeShellArg p}'')
79            (mapAttrsToList (n: v: v.target)
80            (filterAttrs (n: v: v.force) cfg));
81
82        check = pkgs.writeText "check" ''
83          ${config.lib.bash.initHomeManagerLib}
84
85          # A symbolic link whose target path matches this pattern will be
86          # considered part of a Home Manager generation.
87          homeFilePattern="$(readlink -e ${escapeShellArg builtins.storeDir})/*-home-manager-files/*"
88
89          forcedPaths=(${forcedPaths})
90
91          newGenFiles="$1"
92          shift
93          for sourcePath in "$@" ; do
94            relativePath="''${sourcePath#$newGenFiles/}"
95            targetPath="$HOME/$relativePath"
96
97            forced=""
98            for forcedPath in "''${forcedPaths[@]}"; do
99              if [[ $targetPath == $forcedPath* ]]; then
100                forced="yeah"
101                break
102              fi
103            done
104
105            if [[ -n $forced ]]; then
106              $VERBOSE_ECHO "Skipping collision check for $targetPath"
107            elif [[ -e "$targetPath" \
108                && ! "$(readlink "$targetPath")" == $homeFilePattern ]] ; then
109              # The target file already exists and it isn't a symlink owned by Home Manager.
110              if cmp -s "$sourcePath" "$targetPath"; then
111                # First compare the files' content. If they're equal, we're fine.
112                warnEcho "Existing file '$targetPath' is in the way of '$sourcePath', will be skipped since they are the same"
113              elif [[ ! -L "$targetPath" && -n "$HOME_MANAGER_BACKUP_EXT" ]] ; then
114                # Next, try to move the file to a backup location if configured and possible
115                backup="$targetPath.$HOME_MANAGER_BACKUP_EXT"
116                if [[ -e "$backup" ]]; then
117                  errorEcho "Existing file '$backup' would be clobbered by backing up '$targetPath'"
118                  collision=1
119                else
120                  warnEcho "Existing file '$targetPath' is in the way of '$sourcePath', will be moved to '$backup'"
121                fi
122              else
123                # Fail if nothing else works
124                errorEcho "Existing file '$targetPath' is in the way of '$sourcePath'"
125                collision=1
126              fi
127            fi
128          done
129
130          if [[ -v collision ]] ; then
131            errorEcho "Please move the above files and try again or use 'home-manager switch -b backup' to back up existing files automatically."
132            exit 1
133          fi
134        '';
135      in
136      ''
137        function checkNewGenCollision() {
138          local newGenFiles
139          newGenFiles="$(readlink -e "$newGenPath/home-files")"
140          find "$newGenFiles" \( -type f -or -type l \) \
141              -exec bash ${check} "$newGenFiles" {} +
142        }
143
144        checkNewGenCollision || exit 1
145      ''
146    );
147
148    # This activation script will
149    #
150    # 1. Remove files from the old generation that are not in the new
151    #    generation.
152    #
153    # 2. Switch over the Home Manager gcroot and current profile
154    #    links.
155    #
156    # 3. Symlink files from the new generation into $HOME.
157    #
158    # This order is needed to ensure that we always know which links
159    # belong to which generation. Specifically, if we're moving from
160    # generation A to generation B having sets of home file links FA
161    # and FB, respectively then cleaning before linking produces state
162    # transitions similar to
163    #
164    #      FA   →   FA ∩ FB   →   (FA ∩ FB) ∪ FB = FB
165    #
166    # and a failure during the intermediate state FA ∩ FB will not
167    # result in lost links because this set of links are in both the
168    # source and target generation.
169    home.activation.linkGeneration = hm.dag.entryAfter ["writeBoundary"] (
170      let
171        link = pkgs.writeShellScript "link" ''
172          newGenFiles="$1"
173          shift
174          for sourcePath in "$@" ; do
175            relativePath="''${sourcePath#$newGenFiles/}"
176            targetPath="$HOME/$relativePath"
177            if [[ -e "$targetPath" && ! -L "$targetPath" && -n "$HOME_MANAGER_BACKUP_EXT" ]] ; then
178              # The target exists, back it up
179              backup="$targetPath.$HOME_MANAGER_BACKUP_EXT"
180              $DRY_RUN_CMD mv $VERBOSE_ARG "$targetPath" "$backup" || errorEcho "Moving '$targetPath' failed!"
181            fi
182
183            if [[ -e "$targetPath" && ! -L "$targetPath" ]] && cmp -s "$sourcePath" "$targetPath" ; then
184              # The target exists but is identical – don't do anything.
185              $VERBOSE_ECHO "Skipping '$targetPath' as it is identical to '$sourcePath'"
186            else
187              # Place that symlink, --force
188              # This can still fail if the target is a directory, in which case we bail out.
189              $DRY_RUN_CMD mkdir -p $VERBOSE_ARG "$(dirname "$targetPath")"
190              $DRY_RUN_CMD ln -Tsf $VERBOSE_ARG "$sourcePath" "$targetPath" || exit 1
191            fi
192          done
193        '';
194
195        cleanup = pkgs.writeShellScript "cleanup" ''
196          ${config.lib.bash.initHomeManagerLib}
197
198          # A symbolic link whose target path matches this pattern will be
199          # considered part of a Home Manager generation.
200          homeFilePattern="$(readlink -e ${escapeShellArg builtins.storeDir})/*-home-manager-files/*"
201
202          newGenFiles="$1"
203          shift 1
204          for relativePath in "$@" ; do
205            targetPath="$HOME/$relativePath"
206            if [[ -e "$newGenFiles/$relativePath" ]] ; then
207              $VERBOSE_ECHO "Checking $targetPath: exists"
208            elif [[ ! "$(readlink "$targetPath")" == $homeFilePattern ]] ; then
209              warnEcho "Path '$targetPath' does not link into a Home Manager generation. Skipping delete."
210            else
211              $VERBOSE_ECHO "Checking $targetPath: gone (deleting)"
212              $DRY_RUN_CMD rm $VERBOSE_ARG "$targetPath"
213
214              # Recursively delete empty parent directories.
215              targetDir="$(dirname "$relativePath")"
216              if [[ "$targetDir" != "." ]] ; then
217                pushd "$HOME" > /dev/null
218
219                # Call rmdir with a relative path excluding $HOME.
220                # Otherwise, it might try to delete $HOME and exit
221                # with a permission error.
222                $DRY_RUN_CMD rmdir $VERBOSE_ARG \
223                    -p --ignore-fail-on-non-empty \
224                    "$targetDir"
225
226                popd > /dev/null
227              fi
228            fi
229          done
230        '';
231      in
232        ''
233          function linkNewGen() {
234            _i "Creating home file links in %s" "$HOME"
235
236            local newGenFiles
237            newGenFiles="$(readlink -e "$newGenPath/home-files")"
238            find "$newGenFiles" \( -type f -or -type l \) \
239              -exec bash ${link} "$newGenFiles" {} +
240          }
241
242          function cleanOldGen() {
243            if [[ ! -v oldGenPath || ! -e "$oldGenPath/home-files" ]] ; then
244              return
245            fi
246
247            _i "Cleaning up orphan links from %s" "$HOME"
248
249            local newGenFiles oldGenFiles
250            newGenFiles="$(readlink -e "$newGenPath/home-files")"
251            oldGenFiles="$(readlink -e "$oldGenPath/home-files")"
252
253            # Apply the cleanup script on each leaf in the old
254            # generation. The find command below will print the
255            # relative path of the entry.
256            find "$oldGenFiles" '(' -type f -or -type l ')' -printf '%P\0' \
257              | xargs -0 bash ${cleanup} "$newGenFiles"
258          }
259
260          cleanOldGen
261
262          if [[ ! -v oldGenPath || "$oldGenPath" != "$newGenPath" ]] ; then
263            _i "Creating profile generation %s" $newGenNum
264            if [[ -e "$genProfilePath"/manifest.json ]] ; then
265              # Remove all packages from "$genProfilePath"
266              # `nix profile remove '.*' --profile "$genProfilePath"` was not working, so here is a workaround:
267              nix profile list --profile "$genProfilePath" \
268                | cut -d ' ' -f 4 \
269                | xargs -t $DRY_RUN_CMD nix profile remove $VERBOSE_ARG --profile "$genProfilePath"
270              $DRY_RUN_CMD nix profile install $VERBOSE_ARG --profile "$genProfilePath" "$newGenPath"
271            else
272              $DRY_RUN_CMD nix-env $VERBOSE_ARG --profile "$genProfilePath" --set "$newGenPath"
273            fi
274
275            $DRY_RUN_CMD nix-store --realise "$newGenPath" --add-root "$newGenGcPath" > "$DRY_RUN_NULL"
276            if [[ -e "$legacyGenGcPath" ]]; then
277              $DRY_RUN_CMD rm $VERBOSE_ARG "$legacyGenGcPath"
278            fi
279          else
280            _i "No change so reusing latest profile generation %s" "$oldGenNum"
281          fi
282
283          linkNewGen
284        ''
285    );
286
287    home.activation.checkFilesChanged = hm.dag.entryBefore ["linkGeneration"] (
288      let
289        homeDirArg = escapeShellArg homeDirectory;
290      in ''
291        function _cmp() {
292          if [[ -d $1 && -d $2 ]]; then
293            diff -rq "$1" "$2" &> /dev/null
294          else
295            cmp --quiet "$1" "$2"
296          fi
297        }
298        declare -A changedFiles
299      '' + concatMapStrings (v:
300        let
301          sourceArg = escapeShellArg (sourceStorePath v);
302          targetArg = escapeShellArg v.target;
303        in ''
304          _cmp ${sourceArg} ${homeDirArg}/${targetArg} \
305            && changedFiles[${targetArg}]=0 \
306            || changedFiles[${targetArg}]=1
307        '') (filter (v: v.onChange != "") (attrValues cfg))
308      + ''
309        unset -f _cmp
310      ''
311    );
312
313    home.activation.onFilesChange = hm.dag.entryAfter ["linkGeneration"] (
314      concatMapStrings (v: ''
315        if (( ''${changedFiles[${escapeShellArg v.target}]} == 1 )); then
316          if [[ -v DRY_RUN || -v VERBOSE ]]; then
317            echo "Running onChange hook for" ${escapeShellArg v.target}
318          fi
319          if [[ ! -v DRY_RUN ]]; then
320            ${v.onChange}
321          fi
322        fi
323      '') (filter (v: v.onChange != "") (attrValues cfg))
324    );
325
326    # Symlink directories and files that have the right execute bit.
327    # Copy files that need their execute bit changed.
328    home-files = pkgs.runCommandLocal
329      "home-manager-files"
330      {
331        nativeBuildInputs = [ pkgs.xorg.lndir ];
332      }
333      (''
334        mkdir -p $out
335
336        # Needed in case /nix is a symbolic link.
337        realOut="$(realpath -m "$out")"
338
339        function insertFile() {
340          local source="$1"
341          local relTarget="$2"
342          local executable="$3"
343          local recursive="$4"
344
345          # If the target already exists then we have a collision. Note, this
346          # should not happen due to the assertion found in the 'files' module.
347          # We therefore simply log the conflict and otherwise ignore it, mainly
348          # to make the `files-target-config` test work as expected.
349          if [[ -e "$realOut/$relTarget" ]]; then
350            echo "File conflict for file '$relTarget'" >&2
351            return
352          fi
353
354          # Figure out the real absolute path to the target.
355          local target
356          target="$(realpath -m "$realOut/$relTarget")"
357
358          # Target path must be within $HOME.
359          if [[ ! $target == $realOut* ]] ; then
360            echo "Error installing file '$relTarget' outside \$HOME" >&2
361            exit 1
362          fi
363
364          mkdir -p "$(dirname "$target")"
365          if [[ -d $source ]]; then
366            if [[ $recursive ]]; then
367              mkdir -p "$target"
368              lndir -silent "$source" "$target"
369            else
370              ln -s "$source" "$target"
371            fi
372          else
373            [[ -x $source ]] && isExecutable=1 || isExecutable=""
374
375            # Link the file into the home file directory if possible,
376            # i.e., if the executable bit of the source is the same we
377            # expect for the target. Otherwise, we copy the file and
378            # set the executable bit to the expected value.
379            if [[ $executable == inherit || $isExecutable == $executable ]]; then
380              ln -s "$source" "$target"
381            else
382              cp "$source" "$target"
383
384              if [[ $executable == inherit ]]; then
385                # Don't change file mode if it should match the source.
386                :
387              elif [[ $executable ]]; then
388                chmod +x "$target"
389              else
390                chmod -x "$target"
391              fi
392            fi
393          fi
394        }
395      '' + concatStrings (
396        mapAttrsToList (n: v: ''
397          insertFile ${
398            escapeShellArgs [
399              (sourceStorePath v)
400              v.target
401              (if v.executable == null
402               then "inherit"
403               else toString v.executable)
404              (toString v.recursive)
405            ]}
406        '') cfg
407      ));
408  };
409}