Skip to content

Instantly share code, notes, and snippets.

@note
Last active May 8, 2022 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save note/49005aa90466a289bc936e7d3c434298 to your computer and use it in GitHub Desktop.
Save note/49005aa90466a289bc936e7d3c434298 to your computer and use it in GitHub Desktop.
Automate creating nix-shell environments with node2nix
#!/bin/bash
# Exit on any failure
set -e
if [ "$#" -lt 1 ]; then
echo "Expected at least one parameter (npm package name)"
exit 1
fi
NPM_PACKAGE_NAME="$1"
NPM_PACKAGE_VERSION="${2:-latest}"
echo "creating env for $NPM_PACKAGE_NAME:$NPM_PACKAGE_VERSION"
function fail_if_exists () {
local FILE_NAME="$1"
if [ -f "$FILE" ]; then
echo "$FILE exists. Aborting to avoid overwriting it. Remove and retry if that's your intention"
exit 1
fi
}
fail_if_exists "default.nix"
fail_if_exists "node-env.nix"
fail_if_exists "node-packages.nix"
fail_if_exists "generated.nix"
cat <<EOT >> node2nix.nix
with import <nixpkgs> {};
stdenv.mkDerivation rec {
name = "node2nix";
buildInputs = [ nodePackages.node2nix ];
}
EOT
cat <<EOT >> package.json
{
"name": "$NPM_PACKAGE_NAME",
"version": "$NPM_PACKAGE_VERSION",
"devDependencies": {
"$NPM_PACKAGE_NAME": "$NPM_PACKAGE_VERSION"
}
}
EOT
# Running it will create: default.nix, node-env.nix and node-package.nix
nix-shell node2nix.nix --run "node2nix --development"
mv default.nix generated.nix
cat <<EOT >> default.nix
let
gen = import ./generated.nix;
in (gen { }).shell
EOT
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment