at 17.09-beta 13 kB view raw
1# This file originates from node2nix 2 3{stdenv, nodejs, python2, utillinux, runCommand, writeTextFile}: 4 5let 6 python = if nodejs ? python then nodejs.python else python2; 7 8 # Create a tar wrapper that filters all the 'Ignoring unknown extended header keyword' noise 9 tarWrapper = runCommand "tarWrapper" {} '' 10 mkdir -p $out/bin 11 12 cat > $out/bin/tar <<EOF 13 #! ${stdenv.shell} -e 14 $(type -p tar) "\$@" --warning=no-unknown-keyword 15 EOF 16 17 chmod +x $out/bin/tar 18 ''; 19 20 # Function that generates a TGZ file from a NPM project 21 buildNodeSourceDist = 22 { name, version, src, ... }: 23 24 stdenv.mkDerivation { 25 name = "node-tarball-${name}-${version}"; 26 inherit src; 27 buildInputs = [ nodejs ]; 28 buildPhase = '' 29 export HOME=$TMPDIR 30 tgzFile=$(npm pack) 31 ''; 32 installPhase = '' 33 mkdir -p $out/tarballs 34 mv $tgzFile $out/tarballs 35 mkdir -p $out/nix-support 36 echo "file source-dist $out/tarballs/$tgzFile" >> $out/nix-support/hydra-build-products 37 ''; 38 }; 39 40 includeDependencies = {dependencies}: 41 stdenv.lib.optionalString (dependencies != []) 42 (stdenv.lib.concatMapStrings (dependency: 43 '' 44 # Bundle the dependencies of the package 45 mkdir -p node_modules 46 cd node_modules 47 48 # Only include dependencies if they don't exist. They may also be bundled in the package. 49 if [ ! -e "${dependency.name}" ] 50 then 51 ${composePackage dependency} 52 fi 53 54 cd .. 55 '' 56 ) dependencies); 57 58 # Recursively composes the dependencies of a package 59 composePackage = { name, packageName, src, dependencies ? [], ... }@args: 60 '' 61 DIR=$(pwd) 62 cd $TMPDIR 63 64 unpackFile ${src} 65 66 # Make the base dir in which the target dependency resides first 67 mkdir -p "$(dirname "$DIR/${packageName}")" 68 69 if [ -f "${src}" ] 70 then 71 # Figure out what directory has been unpacked 72 packageDir="$(find . -maxdepth 1 -type d | tail -1)" 73 74 # Restore write permissions to make building work 75 find "$packageDir" -type d -print0 | xargs -0 chmod u+x 76 chmod -R u+w "$packageDir" 77 78 # Move the extracted tarball into the output folder 79 mv "$packageDir" "$DIR/${packageName}" 80 elif [ -d "${src}" ] 81 then 82 # Get a stripped name (without hash) of the source directory. 83 # On old nixpkgs it's already set internally. 84 if [ -z "$strippedName" ] 85 then 86 strippedName="$(stripHash ${src})" 87 fi 88 89 # Restore write permissions to make building work 90 chmod -R u+w "$strippedName" 91 92 # Move the extracted directory into the output folder 93 mv "$strippedName" "$DIR/${packageName}" 94 fi 95 96 # Unset the stripped name to not confuse the next unpack step 97 unset strippedName 98 99 # Include the dependencies of the package 100 cd "$DIR/${packageName}" 101 ${includeDependencies { inherit dependencies; }} 102 cd .. 103 ${stdenv.lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} 104 ''; 105 106 pinpointDependencies = {dependencies, production}: 107 let 108 pinpointDependenciesFromPackageJSON = writeTextFile { 109 name = "pinpointDependencies.js"; 110 text = '' 111 var fs = require('fs'); 112 var path = require('path'); 113 114 function resolveDependencyVersion(location, name) { 115 if(location == process.env['NIX_STORE']) { 116 return null; 117 } else { 118 var dependencyPackageJSON = path.join(location, "node_modules", name, "package.json"); 119 120 if(fs.existsSync(dependencyPackageJSON)) { 121 var dependencyPackageObj = JSON.parse(fs.readFileSync(dependencyPackageJSON)); 122 123 if(dependencyPackageObj.name == name) { 124 return dependencyPackageObj.version; 125 } 126 } else { 127 return resolveDependencyVersion(path.resolve(location, ".."), name); 128 } 129 } 130 } 131 132 function replaceDependencies(dependencies) { 133 if(typeof dependencies == "object" && dependencies !== null) { 134 for(var dependency in dependencies) { 135 var resolvedVersion = resolveDependencyVersion(process.cwd(), dependency); 136 137 if(resolvedVersion === null) { 138 process.stderr.write("WARNING: cannot pinpoint dependency: "+dependency+", context: "+process.cwd()+"\n"); 139 } else { 140 dependencies[dependency] = resolvedVersion; 141 } 142 } 143 } 144 } 145 146 /* Read the package.json configuration */ 147 var packageObj = JSON.parse(fs.readFileSync('./package.json')); 148 149 /* Pinpoint all dependencies */ 150 replaceDependencies(packageObj.dependencies); 151 if(process.argv[2] == "development") { 152 replaceDependencies(packageObj.devDependencies); 153 } 154 replaceDependencies(packageObj.optionalDependencies); 155 156 /* Write the fixed package.json file */ 157 fs.writeFileSync("package.json", JSON.stringify(packageObj, null, 2)); 158 ''; 159 }; 160 in 161 '' 162 node ${pinpointDependenciesFromPackageJSON} ${if production then "production" else "development"} 163 164 ${stdenv.lib.optionalString (dependencies != []) 165 '' 166 if [ -d node_modules ] 167 then 168 cd node_modules 169 ${stdenv.lib.concatMapStrings (dependency: pinpointDependenciesOfPackage dependency) dependencies} 170 cd .. 171 fi 172 ''} 173 ''; 174 175 # Recursively traverses all dependencies of a package and pinpoints all 176 # dependencies in the package.json file to the versions that are actually 177 # being used. 178 179 pinpointDependenciesOfPackage = { packageName, dependencies ? [], production ? true, ... }@args: 180 '' 181 if [ -d "${packageName}" ] 182 then 183 cd "${packageName}" 184 ${pinpointDependencies { inherit dependencies production; }} 185 cd .. 186 ${stdenv.lib.optionalString (builtins.substring 0 1 packageName == "@") "cd .."} 187 fi 188 ''; 189 190 # Extract the Node.js source code which is used to compile packages with 191 # native bindings 192 nodeSources = runCommand "node-sources" {} '' 193 tar --no-same-owner --no-same-permissions -xf ${nodejs.src} 194 mv node-* $out 195 ''; 196 197 # Builds and composes an NPM package including all its dependencies 198 buildNodePackage = { name, packageName, version, dependencies ? [], production ? true, npmFlags ? "", dontNpmInstall ? false, preRebuild ? "", ... }@args: 199 200 stdenv.lib.makeOverridable stdenv.mkDerivation (builtins.removeAttrs args [ "dependencies" ] // { 201 name = "node-${name}-${version}"; 202 buildInputs = [ tarWrapper python nodejs ] ++ stdenv.lib.optional (stdenv.isLinux) utillinux ++ args.buildInputs or []; 203 dontStrip = args.dontStrip or true; # Striping may fail a build for some package deployments 204 205 inherit dontNpmInstall preRebuild; 206 207 unpackPhase = args.unpackPhase or "true"; 208 209 buildPhase = args.buildPhase or "true"; 210 211 compositionScript = composePackage args; 212 pinpointDependenciesScript = pinpointDependenciesOfPackage args; 213 214 passAsFile = [ "compositionScript" "pinpointDependenciesScript" ]; 215 216 installPhase = args.installPhase or '' 217 # Create and enter a root node_modules/ folder 218 mkdir -p $out/lib/node_modules 219 cd $out/lib/node_modules 220 221 # Compose the package and all its dependencies 222 source $compositionScriptPath 223 224 # Pinpoint the versions of all dependencies to the ones that are actually being used 225 echo "pinpointing versions of dependencies..." 226 source $pinpointDependenciesScriptPath 227 228 # Patch the shebangs of the bundled modules to prevent them from 229 # calling executables outside the Nix store as much as possible 230 patchShebangs . 231 232 # Deploy the Node.js package by running npm install. Since the 233 # dependencies have been provided already by ourselves, it should not 234 # attempt to install them again, which is good, because we want to make 235 # it Nix's responsibility. If it needs to install any dependencies 236 # anyway (e.g. because the dependency parameters are 237 # incomplete/incorrect), it fails. 238 # 239 # The other responsibilities of NPM are kept -- version checks, build 240 # steps, postprocessing etc. 241 242 export HOME=$TMPDIR 243 cd "${packageName}" 244 runHook preRebuild 245 npm --registry http://www.example.com --nodedir=${nodeSources} ${npmFlags} ${stdenv.lib.optionalString production "--production"} rebuild 246 247 if [ "$dontNpmInstall" != "1" ] 248 then 249 # NPM tries to download packages even when they already exist if npm-shrinkwrap is used. 250 rm -f npm-shrinkwrap.json 251 252 npm --registry http://www.example.com --nodedir=${nodeSources} ${npmFlags} ${stdenv.lib.optionalString production "--production"} install 253 fi 254 255 # Create symlink to the deployed executable folder, if applicable 256 if [ -d "$out/lib/node_modules/.bin" ] 257 then 258 ln -s $out/lib/node_modules/.bin $out/bin 259 fi 260 261 # Create symlinks to the deployed manual page folders, if applicable 262 if [ -d "$out/lib/node_modules/${packageName}/man" ] 263 then 264 mkdir -p $out/share 265 for dir in "$out/lib/node_modules/${packageName}/man/"* 266 do 267 mkdir -p $out/share/man/$(basename "$dir") 268 for page in "$dir"/* 269 do 270 ln -s $page $out/share/man/$(basename "$dir") 271 done 272 done 273 fi 274 275 # Run post install hook, if provided 276 runHook postInstall 277 ''; 278 }); 279 280 # Builds a development shell 281 buildNodeShell = { name, packageName, version, src, dependencies ? [], production ? true, npmFlags ? "", dontNpmInstall ? false, ... }@args: 282 let 283 nodeDependencies = stdenv.mkDerivation { 284 name = "node-dependencies-${name}-${version}"; 285 286 buildInputs = [ tarWrapper python nodejs ] ++ stdenv.lib.optional (stdenv.isLinux) utillinux ++ args.buildInputs or []; 287 288 includeScript = includeDependencies { inherit dependencies; }; 289 pinpointDependenciesScript = pinpointDependenciesOfPackage args; 290 291 passAsFile = [ "includeScript" "pinpointDependenciesScript" ]; 292 293 buildCommand = '' 294 mkdir -p $out/lib 295 cd $out/lib 296 source $includeScriptPath 297 298 # Pinpoint the versions of all dependencies to the ones that are actually being used 299 echo "pinpointing versions of dependencies..." 300 source $pinpointDependenciesScriptPath 301 302 # Create fake package.json to make the npm commands work properly 303 cat > package.json <<EOF 304 { 305 "name": "${packageName}", 306 "version": "${version}" 307 } 308 EOF 309 310 # Patch the shebangs of the bundled modules to prevent them from 311 # calling executables outside the Nix store as much as possible 312 patchShebangs . 313 314 export HOME=$PWD 315 npm --registry http://www.example.com --nodedir=${nodeSources} ${npmFlags} ${stdenv.lib.optionalString production "--production"} rebuild 316 317 ${stdenv.lib.optionalString (!dontNpmInstall) '' 318 # NPM tries to download packages even when they already exist if npm-shrinkwrap is used. 319 rm -f npm-shrinkwrap.json 320 321 npm --registry http://www.example.com --nodedir=${nodeSources} ${npmFlags} ${stdenv.lib.optionalString production "--production"} install 322 ''} 323 324 ln -s $out/lib/node_modules/.bin $out/bin 325 ''; 326 }; 327 in 328 stdenv.lib.makeOverridable stdenv.mkDerivation { 329 name = "node-shell-${name}-${version}"; 330 331 buildInputs = [ python nodejs ] ++ stdenv.lib.optional (stdenv.isLinux) utillinux ++ args.buildInputs or []; 332 buildCommand = '' 333 mkdir -p $out/bin 334 cat > $out/bin/shell <<EOF 335 #! ${stdenv.shell} -e 336 $shellHook 337 exec ${stdenv.shell} 338 EOF 339 chmod +x $out/bin/shell 340 ''; 341 342 # Provide the dependencies in a development shell through the NODE_PATH environment variable 343 inherit nodeDependencies; 344 shellHook = stdenv.lib.optionalString (dependencies != []) '' 345 export NODE_PATH=$nodeDependencies/lib/node_modules 346 ''; 347 }; 348in 349{ inherit buildNodeSourceDist buildNodePackage buildNodeShell; }