fork/home-manager
git clone https://git.julia.blue/fork/home-manager
75790441
master
1{ pkgs , config , lib , ...} : 2 3with lib ; 4 5let 6 7cfg = filterAttrs ( n :f :f . enable ) config . home . file ; 8 9homeDirectory = config . home . homeDirectory ; 10 11fileType = ( import lib/file-type.nix { 12inherit homeDirectory lib pkgs ; 13}). fileType ; 14 15sourceStorePath = file : 16let 17sourcePath = toString file . source ; 18sourceName = config . lib . strings . storeFileName ( baseNameOf sourcePath ); 19in 20if builtins . hasContext sourcePath 21then file . source 22else builtins . path { path = file . source ; name = sourceName ; }; 23 24in 25 26{ 27options = { 28home . file = mkOption { 29description = "Attribute set of files to link into the user home." ; 30default = {}; 31type = fileType "home.file" "{env}`HOME`" homeDirectory ; 32}; 33 34home-files = mkOption { 35type = types . package ; 36internal = true ; 37description = "Package to contain all home files" ; 38}; 39}; 40 41config = { 42assertions = [( 43let 44dups = 45attrNames 46( filterAttrs ( n :v :v > 1 ) 47( foldAttrs ( acc :v :acc + v ) 0 48( mapAttrsToList ( n :v :{ ${ v . target } = 1 ; }) cfg ))); 49dupsStr = concatStringsSep ", " dups ; 50in { 51assertion = dups == []; 52message = '' 53Conflicting managed target files: ${ dupsStr } 54 55This may happen, for example, if you have a configuration similar to 56 57home.file = { 58conflict1 = { source = ./foo.nix; target = "baz"; }; 59conflict2 = { source = ./bar.nix; target = "baz"; }; 60}'' ; 61}) 62]; 63 64lib . file . mkOutOfStoreSymlink = path : 65let 66pathStr = toString path ; 67name = hm . strings . storeFileName ( baseNameOf pathStr ); 68in 69pkgs . 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. 73home . activation . checkLinkTargets = hm . dag . entryBefore [ "writeBoundary" ] ( 74let 75# Paths that should be forcibly overwritten by Home Manager. 76# Caveat emptor! 77forcedPaths = 78concatMapStringsSep " " ( p :''"$HOME"/ ${ escapeShellArg p } '' ) 79( mapAttrsToList ( n :v :v . target ) 80( filterAttrs ( n :v :v . force ) cfg )); 81 82check = 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. 87homeFilePattern="$(readlink -e ${ escapeShellArg builtins . storeDir } )/*-home-manager-files/*" 88 89forcedPaths=( ${ forcedPaths } ) 90 91newGenFiles="$1" 92shift 93for sourcePath in "$@" ; do 94relativePath="''${sourcePath#$newGenFiles/}" 95targetPath="$HOME/$relativePath" 96 97forced="" 98for forcedPath in "''${forcedPaths[@]}"; do 99if [[ $targetPath == $forcedPath* ]]; then 100forced="yeah" 101break 102fi 103done 104 105if [[ -n $forced ]]; then 106$VERBOSE_ECHO "Skipping collision check for $targetPath" 107elif [[ -e "$targetPath" \ 108&& ! "$(readlink "$targetPath")" == $homeFilePattern ]] ; then 109# The target file already exists and it isn't a symlink owned by Home Manager. 110if cmp -s "$sourcePath" "$targetPath"; then 111# First compare the files' content. If they're equal, we're fine. 112warnEcho "Existing file '$targetPath' is in the way of '$sourcePath', will be skipped since they are the same" 113elif [[ ! -L "$targetPath" && -n "$HOME_MANAGER_BACKUP_EXT" ]] ; then 114# Next, try to move the file to a backup location if configured and possible 115backup="$targetPath.$HOME_MANAGER_BACKUP_EXT" 116if [[ -e "$backup" ]]; then 117errorEcho "Existing file '$backup' would be clobbered by backing up '$targetPath'" 118collision=1 119else 120warnEcho "Existing file '$targetPath' is in the way of '$sourcePath', will be moved to '$backup'" 121fi 122else 123# Fail if nothing else works 124errorEcho "Existing file '$targetPath' is in the way of '$sourcePath'" 125collision=1 126fi 127fi 128done 129 130if [[ -v collision ]] ; then 131errorEcho "Please move the above files and try again or use 'home-manager switch -b backup' to back up existing files automatically." 132exit 1 133fi 134'' ; 135in 136'' 137function checkNewGenCollision() { 138local newGenFiles 139newGenFiles="$(readlink -e "$newGenPath/home-files")" 140find "$newGenFiles" \( -type f -or -type l \) \ 141-exec bash ${ check } "$newGenFiles" {} + 142} 143 144checkNewGenCollision || 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. 169home . activation . linkGeneration = hm . dag . entryAfter [ "writeBoundary" ] ( 170let 171link = pkgs . writeShellScript "link" '' 172newGenFiles =" $ 1 " 173shift 174for sourcePath in " $ @" ; do 175relativePath ="'' $ { sourcePath #$newGenFiles/}" 176targetPath =" $ HOME / $ relativePath " 177if [[ -e " $ targetPath " && ! -L " $ targetPath " && -n " $ HOME_MANAGER_BACKUP_EXT " ]] ; then 178# The target exists, back it up 179backup =" $ targetPath . $ HOME_MANAGER_BACKUP_EXT " 180$ DRY_RUN_CMD mv $ VERBOSE_ARG " $ targetPath " " $ backup " || errorEcho "Moving ' $ targetPath ' failed!" 181fi 182 183if [[ -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 '" 186else 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 191fi 192done 193'' ; 194 195cleanup = 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. 200homeFilePattern ="$( readlink -e ${ escapeShellArg builtins . storeDir } ) /*-home-manager-files/* " 201 202newGenFiles=" $ 1" 203shift 1 204for relativePath in " $ @" ; do 205targetPath=" $ HOME/ $ relativePath " 206if [[ -e " $ newGenFiles/ $ relativePath " ]] ; then 207$ VERBOSE_ECHO "Checking $ targetPath : exists" 208elif [[ ! " $( readlink " $ targetPath " ) " == $ homeFilePattern ]] ; then 209warnEcho "Path '$targetPath' does not link into a Home Manager generation. Skipping delete." 210else 211$ VERBOSE_ECHO "Checking $ targetPath : gone ( deleting )" 212$ DRY_RUN_CMD rm $ VERBOSE_ARG " $ targetPath " 213 214# Recursively delete empty parent directories. 215targetDir=" $( dirname " $ relativePath " ) " 216if [[ " $ targetDir " != " . " ]] ; then 217pushd " $ 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 226popd > /dev/null 227fi 228fi 229done 230'' ; 231in 232'' 233function linkNewGen() { 234_i "Creating home file links in %s" "$HOME" 235 236local newGenFiles 237newGenFiles="$(readlink -e "$newGenPath/home-files")" 238find "$newGenFiles" \( -type f -or -type l \) \ 239-exec bash ${ link } "$newGenFiles" {} + 240} 241 242function cleanOldGen() { 243if [[ ! -v oldGenPath || ! -e "$oldGenPath/home-files" ]] ; then 244return 245fi 246 247_i "Cleaning up orphan links from %s" "$HOME" 248 249local newGenFiles oldGenFiles 250newGenFiles="$(readlink -e "$newGenPath/home-files")" 251oldGenFiles="$(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. 256find "$oldGenFiles" '(' -type f -or -type l ')' -printf '%P\0' \ 257| xargs -0 bash ${ cleanup } "$newGenFiles" 258} 259 260cleanOldGen 261 262if [[ ! -v oldGenPath || "$oldGenPath" != "$newGenPath" ]] ; then 263_i "Creating profile generation %s" $newGenNum 264if [[ -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: 267nix 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" 271else 272$DRY_RUN_CMD nix-env $VERBOSE_ARG --profile "$genProfilePath" --set "$newGenPath" 273fi 274 275$DRY_RUN_CMD nix-store --realise "$newGenPath" --add-root "$newGenGcPath" > "$DRY_RUN_NULL" 276if [[ -e "$legacyGenGcPath" ]]; then 277$DRY_RUN_CMD rm $VERBOSE_ARG "$legacyGenGcPath" 278fi 279else 280_i "No change so reusing latest profile generation %s" "$oldGenNum" 281fi 282 283linkNewGen 284'' 285); 286 287home . activation . checkFilesChanged = hm . dag . entryBefore [ "linkGeneration" ] ( 288let 289homeDirArg = escapeShellArg homeDirectory ; 290in '' 291function _cmp() { 292if [[ -d $1 && -d $2 ]]; then 293diff -rq "$1" "$2" &> /dev/null 294else 295cmp --quiet "$1" "$2" 296fi 297} 298declare -A changedFiles 299'' + concatMapStrings ( v : 300let 301sourceArg = escapeShellArg ( sourceStorePath v ); 302targetArg = escapeShellArg v . target ; 303in '' 304_cmp ${ sourceArg } ${ homeDirArg } / ${ targetArg } \ 305&& changedFiles[ ${ targetArg } ]=0 \ 306|| changedFiles[ ${ targetArg } ]=1 307'' ) ( filter ( v :v . onChange != "" ) ( attrValues cfg )) 308+ '' 309unset -f _cmp 310'' 311); 312 313home . activation . onFilesChange = hm . dag . entryAfter [ "linkGeneration" ] ( 314concatMapStrings ( v :'' 315if (( ''${changedFiles[ ${ escapeShellArg v . target } ]} == 1 )); then 316if [[ -v DRY_RUN || -v VERBOSE ]]; then 317echo "Running onChange hook for" ${ escapeShellArg v . target } 318fi 319if [[ ! -v DRY_RUN ]]; then 320${ v . onChange } 321fi 322fi 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. 328home-files = pkgs . runCommandLocal 329"home-manager-files" 330{ 331nativeBuildInputs = [ pkgs . xorg . lndir ]; 332} 333( '' 334mkdir -p $out 335 336# Needed in case /nix is a symbolic link. 337realOut="$(realpath -m "$out")" 338 339function insertFile() { 340local source="$1" 341local relTarget="$2" 342local executable="$3" 343local 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. 349if [[ -e "$realOut/$relTarget" ]]; then 350echo "File conflict for file '$relTarget'" >&2 351return 352fi 353 354# Figure out the real absolute path to the target. 355local target 356target="$(realpath -m "$realOut/$relTarget")" 357 358# Target path must be within $HOME. 359if [[ ! $target == $realOut* ]] ; then 360echo "Error installing file '$relTarget' outside \$HOME" >&2 361exit 1 362fi 363 364mkdir -p "$(dirname "$target")" 365if [[ -d $source ]]; then 366if [[ $recursive ]]; then 367mkdir -p "$target" 368lndir -silent "$source" "$target" 369else 370ln -s "$source" "$target" 371fi 372else 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. 379if [[ $executable == inherit || $isExecutable == $executable ]]; then 380ln -s "$source" "$target" 381else 382cp "$source" "$target" 383 384if [[ $executable == inherit ]]; then 385# Don't change file mode if it should match the source. 386: 387elif [[ $executable ]]; then 388chmod +x "$target" 389else 390chmod -x "$target" 391fi 392fi 393fi 394} 395'' + concatStrings ( 396mapAttrsToList ( n :v :'' 397insertFile ${ 398escapeShellArgs [ 399( sourceStorePath v ) 400v . target 401( if v . executable == null 402then "inherit" 403else toString v . executable ) 404( toString v . recursive ) 405]} 406'' ) cfg 407)); 408}; 409}