diff --git a/flake.nix b/flake.nix index 6ebe2d3b..ceeff35b 100644 --- a/flake.nix +++ b/flake.nix @@ -181,6 +181,11 @@ packages.x86_64-linux = import ./pkgs { inherit pkgs self; }; + shellPackages.x86_64-linux = pkgs.lib.mapAttrs (_: module: module.shellPackage) self.modules; + deploymentShellPackages.x86_64-linux = pkgs.lib.mapAttrs (_: module: module.shellPackage) self.deploymentModules; + lib.mkBundle = import ./pkgs/bundle/api.nix { inherit pkgs self; }; + lib.mkToolchain = import ./pkgs/toolchain { inherit pkgs self; }; + checks.x86_64-linux.flake-toolchain = import ./pkgs/toolchain/tests.nix { inherit pkgs; }; checks.x86_64-linux.module-registry = assert import ./scripts/module-registry-test.nix; assert builtins.attrNames self.modules == builtins.attrNames self.deploymentModules; diff --git a/pkgs/bundle/api.nix b/pkgs/bundle/api.nix new file mode 100644 index 00000000..eaeba58b --- /dev/null +++ b/pkgs/bundle/api.nix @@ -0,0 +1,9 @@ +{ pkgs, self }: +{ moduleIds ? null, deployment ? false }: +let + modules = if deployment then self.deploymentModules else self.modules; +in +assert moduleIds == null || builtins.all + (id: builtins.hasAttr id modules || throw "Unknown nixmodule: ${id}") + moduleIds; +pkgs.callPackage ./default.nix { inherit self; } { inherit moduleIds deployment; } diff --git a/pkgs/bundle/default.nix b/pkgs/bundle/default.nix index 7338603d..c9303753 100644 --- a/pkgs/bundle/default.nix +++ b/pkgs/bundle/default.nix @@ -11,9 +11,9 @@ { pkgs, lib, self, ... }: with builtins; with pkgs.lib; -{ moduleIds ? null }: +{ moduleIds ? null, deployment ? false }: let - modules = self.modules; + modules = if deployment then self.deploymentModules else self.modules; filteredModules = if moduleIds == null then modules else diff --git a/pkgs/default.nix b/pkgs/default.nix index 95f7adc6..9b02a267 100644 --- a/pkgs/default.nix +++ b/pkgs/default.nix @@ -100,4 +100,6 @@ rec { deploymentModules = self.deploymentModules; } - // modules +// modules +// mapAttrs' (id: module: nameValuePair "shell.${id}" module.shellPackage) self.modules + // mapAttrs' (id: module: nameValuePair "deployment-shell.${id}" module.shellPackage) self.deploymentModules diff --git a/pkgs/moduleit/entrypoint.nix b/pkgs/moduleit/entrypoint.nix index 964d74b7..42469530 100644 --- a/pkgs/moduleit/entrypoint.nix +++ b/pkgs/moduleit/entrypoint.nix @@ -16,8 +16,23 @@ let modulesPath = builtins.toString ./.; }; }); + result = + if deployment then module.config.replit.buildDeploymentModule + else module.config.replit.buildModule; + packages = module.config.replit.packages + ++ pkgs.lib.optionals (!deployment) module.config.replit.dev.packages; in -if deployment then - module.config.replit.buildDeploymentModule -else - module.config.replit.buildModule +pkgs.lib.lazyDerivation { + derivation = result; + passthru = { + moduleId = module.config.id; + moduleConfig = result.moduleConfig; + runtimePackages = packages; + shellPackage = pkgs.callPackage ./shell-package.nix { + name = "replit-${if deployment then "deployment-" else ""}shell-${module.config.id}"; + inherit packages; + env = result.moduleConfig.env; + passthru.module = result; + }; + }; +} diff --git a/pkgs/moduleit/module-definition.nix b/pkgs/moduleit/module-definition.nix index d0528f67..e361a066 100644 --- a/pkgs/moduleit/module-definition.nix +++ b/pkgs/moduleit/module-definition.nix @@ -718,7 +718,9 @@ in }; in - pkgs.writeText "replit-module-${config.id}" (builtins.toJSON moduleJSON); + pkgs.writeText "replit-module-${config.id}" (builtins.toJSON moduleJSON) // { + moduleConfig = moduleJSON; + }; replit.buildDeploymentModule = let @@ -746,6 +748,8 @@ in }; in - pkgs.writeText "replit-deployment-module-${config.id}" (builtins.toJSON moduleJSON); + pkgs.writeText "replit-deployment-module-${config.id}" (builtins.toJSON moduleJSON) // { + moduleConfig = moduleJSON; + }; }; } diff --git a/pkgs/moduleit/shell-package.nix b/pkgs/moduleit/shell-package.nix new file mode 100644 index 00000000..1f310777 --- /dev/null +++ b/pkgs/moduleit/shell-package.nix @@ -0,0 +1,46 @@ +{ lib +, runCommand +, writeText +, name +, packages +, env +, passthru ? { } +}: +let + variablePattern = "[a-zA-Z_][a-zA-Z0-9_]*"; + splitValue = value: builtins.split "[$]([{]${variablePattern}[}]|${variablePattern})" value; + variableName = match: lib.removeSuffix "}" (lib.removePrefix "{" (builtins.head match)); + references = value: map variableName (builtins.filter builtins.isList (splitValue value)); + names = builtins.attrNames env; + ordered = lib.toposort + (a: b: a != b && builtins.elem a (references env.${b})) + names; + # Expand only environment references, never shell substitutions or operators. + shellValue = value: lib.concatMapStrings + (part: + if builtins.isString part then lib.escapeShellArg part + else "\"\${${variableName part}-}\"") + (splitValue value); + hook = + assert lib.assertMsg + (builtins.all (key: builtins.match variablePattern key != null) names) + "Module environment keys must be shell variable names"; + assert lib.assertMsg (!(ordered ? cycle)) "Module environment contains a variable cycle"; + '' + export REPL_HOME="''${REPL_HOME:-$PWD}" + '' + lib.concatMapStringsSep "\n" + (key: "export ${key}=${shellValue env.${key}}" + + lib.optionalString (key == "PATH") "\${PATH:+:}\"$PATH\"") + ordered.result + "\n"; +in +runCommand name +{ + inherit passthru; +} + '' + mkdir -p "$out/nix-support" + cp ${writeText "${name}-hook" hook} "$out/nix-support/setup-hook" + # Keep runtime references without running their compiler build hooks. + printf '%s\n' ${lib.escapeShellArg (lib.concatMapStringsSep "\n" toString packages)} \ + > "$out/nix-support/runtime-dependencies" + '' diff --git a/pkgs/modules/default.nix b/pkgs/modules/default.nix index e41837c4..b4615964 100644 --- a/pkgs/modules/default.nix +++ b/pkgs/modules/default.nix @@ -192,19 +192,8 @@ let modules = apply-upgrade-map (developmentModuleSet allModulesList); deploymentModules = apply-upgrade-map (deploymentModuleSet allModulesList); - get-module-id = - module: - let - match = builtins.match "^\/nix\/store\/([^-]+)-replit-module-(.+)$" module.outPath; - in - builtins.elemAt match 1; - - get-deployment-module-id = - module: - let - match = builtins.match "^\/nix\/store\/([^-]+)-replit-deployment-module-(.+)$" module.outPath; - in - builtins.elemAt match 1; + get-module-id = module: module.moduleId; + get-deployment-module-id = module: module.moduleId; in { inherit diff --git a/pkgs/toolchain/default.nix b/pkgs/toolchain/default.nix new file mode 100644 index 00000000..c44cfd9e --- /dev/null +++ b/pkgs/toolchain/default.nix @@ -0,0 +1,64 @@ +{ pkgs, self }: +{ moduleIds +, deployment ? false +}: +let + inherit (pkgs) lib; + available = if deployment then self.deploymentModules else self.modules; + selected = map + (id: available.${id} or (throw "Unknown nixmodule: ${id}")) + moduleIds; + env = lib.foldl' + (acc: module: + let + next = module.moduleConfig.env; + paths = builtins.filter (path: path != "") [ (acc.PATH or "") (next.PATH or "") ]; + in + acc // next // { PATH = lib.concatStringsSep ":" paths; }) + { } + selected; + shellPackage = pkgs.callPackage ../moduleit/shell-package.nix { + name = "replit-toolchain-shell"; + inherit env; + packages = lib.concatMap (module: module.runtimePackages) selected; + }; + environmentProgram = pkgs.writeShellScript "replit-toolchain-env" '' + set -euo pipefail + source ${shellPackage}/nix-support/setup-hook + ${lib.concatMapStringsSep "\n" + (key: "printf '%s=%s\\0' ${lib.escapeShellArg key} \"\${${key}}\"") + (builtins.attrNames (env // { REPL_HOME = ""; }))} + ''; + moduleConfigs = builtins.listToAttrs (lib.zipListsWith + (id: module: { name = id; value = module.moduleConfig; }) + moduleIds + selected); + metadata = { + schemaVersion = 1; + system = pkgs.stdenv.hostPlatform.system; + inherit moduleIds deployment; + resolvedModules = lib.zipListsWith + (id: module: { + inherit id; + moduleId = module.moduleId; + modulePath = module.outPath; + shellPath = module.shellPackage.outPath; + }) + moduleIds + selected; + }; +in +assert lib.assertMsg + (builtins.isList moduleIds && builtins.all builtins.isString moduleIds) + "moduleIds must be a list of strings"; +assert lib.assertMsg + (builtins.length moduleIds == builtins.length (lib.unique moduleIds)) + "Duplicate nixmodule IDs"; +(pkgs.linkFarm "replit-toolchain" [ + { name = "modules.json"; path = pkgs.writeText "modules.json" (builtins.toJSON moduleConfigs); } + { name = "metadata.json"; path = pkgs.writeText "metadata.json" (builtins.toJSON metadata); } + { name = "shell"; path = shellPackage; } + { name = "bin/replit-toolchain-env"; path = environmentProgram; } +]) // { + inherit shellPackage moduleConfigs metadata; +} diff --git a/pkgs/toolchain/tests.nix b/pkgs/toolchain/tests.nix new file mode 100644 index 00000000..13a50cd0 --- /dev/null +++ b/pkgs/toolchain/tests.nix @@ -0,0 +1,213 @@ +{ pkgs }: +let + inherit (pkgs) lib; + runtime = pkgs.runCommand "toolchain-test-runtime" { } '' + mkdir -p "$out/bin" "$out/nix-support" + printf '#!/bin/sh\nexit 0\n' > "$out/bin/runtime" + chmod +x "$out/bin/runtime" + cat > "$out/nix-support/setup-hook" <<'HOOK' + : "$NIX_CC" + echo "A runtime-only build hook was sourced" >&2 + return 1 + HOOK + ''; + ide = pkgs.writeText "toolchain-test-ide" "IDE-only dependency"; + definition = { + id = "fixture"; + name = "Fixture"; + replit = { + packages = [ runtime ]; + env = { + A_DEPENDENT = "$Z_BASE/child"; + Z_BASE = "$REPL_HOME/base"; + BRACED = "\${Z_BASE}/braced"; + LITERAL = "$(touch /tmp/nixmodules-shell-injection) `false` \" ' \\"; + PYTHONPATH = "$PYTHONPATH/suffix"; + MISSING = "$NOT_PRESENT"; + EMPTY = ""; + MULTILINE = "first=line\nsecond=line"; + MODE = "deployment"; + PATH = "$Z_BASE/bin"; + }; + runners.fixture = { + name = "Fixture"; + language = "fixture"; + start = "${runtime}/bin/runtime $file"; + }; + dev = { + env.MODE = "development"; + languageServers.fixture = { + name = "Fixture server"; + language = "fixture"; + start = "${ide} $file"; + }; + }; + }; + }; + mkModule = deployment: configPath: pkgs.callPackage ../moduleit/entrypoint.nix { + inherit deployment configPath; + pkgs-23_05 = pkgs; + pkgs-24_11 = pkgs; + }; + development = mkModule false definition; + deployment = mkModule true definition; + applyAliases = import ../upgrade-map/apply.nix { alias = "fixture"; }; + self = { + modules = applyAliases { + fixture = development; + override = mkModule false { + id = "override"; + name = "Override"; + replit.env.MODE = "last"; + }; + }; + deploymentModules = applyAliases { fixture = deployment; }; + }; + mkToolchain = import ./default.nix { inherit pkgs self; }; + legacyBundle = pkgs.callPackage ../bundle { inherit self; }; + mkBundle = import ../bundle/api.nix { inherit pkgs self; }; + deploymentBundle = mkBundle { moduleIds = [ "alias" ]; deployment = true; }; + toolchain = mkToolchain { moduleIds = [ "fixture" "alias" ]; }; + overridden = mkToolchain { moduleIds = [ "alias" "override" ]; }; + deploymentToolchain = mkToolchain { moduleIds = [ "fixture" ]; deployment = true; }; + closure = pkgs.closureInfo { rootPaths = [ toolchain ]; }; + deploymentClosure = pkgs.closureInfo { rootPaths = [ deploymentToolchain ]; }; + fails = value: !(builtins.tryEval (builtins.deepSeq value true)).success; + lazyModule = mkModule false { + id = "lazy"; + name = "Lazy"; + replit.packages = throw "moduleId must not evaluate packages or output paths"; + }; + cycle = pkgs.callPackage ../moduleit/shell-package.nix { + name = "cycle"; + packages = [ ]; + env = { A = "$B"; B = "$A"; }; + }; + shellSmoke = pkgs.runCommand "toolchain-shell-check" + { + nativeBuildInputs = [ toolchain.shellPackage ]; + REPL_HOME = "/tmp/project with spaces"; + } '' + test "$MODE" = development + test "$A_DEPENDENT" = "$REPL_HOME/base/child" + test "$(command -v runtime)" = "${runtime}/bin/runtime" + touch "$out" + ''; + environmentInput = { + REPL_HOME = "/tmp/project with spaces"; + PATH = "/original/path"; + PYTHONPATH = "/inherited"; + }; + environmentArgs = lib.concatStringsSep " " + (lib.mapAttrsToList (key: value: lib.escapeShellArg "${key}=${value}") environmentInput); + decodeEnvironment = '' + split("\u0000") + | if last != "" then error("Missing trailing NUL") else .[:-1] end + | map(index("=") as $separator | {key: .[:$separator], value: .[$separator + 1:]}) + | from_entries + ''; + fixtures = { + development = toolchain; + deployment = deploymentToolchain; + override = overridden; + }; +in +assert lazyModule.moduleId == "lazy"; +assert toolchain.metadata.moduleIds == [ "fixture" "alias" ]; +assert map (entry: entry.id) toolchain.metadata.resolvedModules == [ "fixture" "alias" ]; +assert map (entry: entry.moduleId) toolchain.metadata.resolvedModules == [ "fixture" "fixture" ]; +assert toolchain.moduleConfigs.alias == development.moduleConfig; +assert deploymentToolchain.moduleConfigs.fixture == deployment.moduleConfig; +assert deployment.moduleConfig.languageServers == { }; +assert development.moduleConfig.env.MODE == "development"; +assert deployment.moduleConfig.env.MODE == "deployment"; +assert fails (mkToolchain { moduleIds = [ "missing" ]; }).outPath; +assert fails (mkToolchain { moduleIds = [ "fixture" "fixture" ]; }).outPath; +assert fails (mkBundle { moduleIds = [ "missing" ]; }).outPath; +assert fails (mkBundle { moduleIds = [ "fixture" "missing" ]; }).outPath; +assert fails (mkBundle { moduleIds = [ "missing" ]; deployment = true; }).outPath; +assert (legacyBundle { moduleIds = [ "fixture" "missing" ]; }).outPath + == (legacyBundle { moduleIds = [ "fixture" ]; }).outPath; +assert (legacyBundle { moduleIds = [ "missing" ]; }).outPath + == (legacyBundle { moduleIds = [ ]; }).outPath; +assert (legacyBundle { moduleIds = [ "alias" "missing" ]; deployment = true; }).outPath + == deploymentBundle.outPath; +assert fails cycle.outPath; +pkgs.runCommand "flake-toolchain-check" +{ + nativeBuildInputs = [ pkgs.jq ]; +} '' + test -f ${shellSmoke} + test "$(readlink ${deploymentBundle}/alias)" = "${deployment}" + jq -e --arg path "${deployment}" '.alias.path == $path' ${deploymentBundle}/etc/nixmodules/modules.json + test -d ${toolchain}/shell/nix-support + jq -e '.schemaVersion == 1 and .system == "x86_64-linux" + and .moduleIds == ["fixture", "alias"] and .deployment == false + and .resolvedModules[0].id == "fixture" + and .resolvedModules[0].moduleId == "fixture"' ${toolchain}/metadata.json + jq -e '.deployment == true and .moduleIds == ["fixture"]' ${deploymentToolchain}/metadata.json + jq -S . ${development} > expected.json + jq -S .alias ${toolchain}/modules.json > actual.json + cmp expected.json actual.json + jq -S . ${deployment} > expected.json + jq -S .fixture ${deploymentToolchain}/modules.json > actual.json + cmp expected.json actual.json + grep -Fx ${runtime} ${closure}/store-paths + grep -Fx ${ide} ${closure}/store-paths + if grep -Fx ${pkgs.jq} ${closure}/store-paths; then + echo "Toolchain includes a JSON encoder dependency" + exit 1 + fi + if grep -Fx ${ide} ${deploymentClosure}/store-paths; then + echo "Deployment includes a development-only IDE dependency" >&2 + exit 1 + fi + ( + export REPL_HOME="/tmp/project with spaces" + export PATH="/original/path" + source ${toolchain}/shell/nix-support/setup-hook + test "$A_DEPENDENT" = "$REPL_HOME/base/child" + test "$BRACED" = "$REPL_HOME/base/braced" + test "$LITERAL" = ${lib.escapeShellArg definition.replit.env.LITERAL} + test "$MODE" = development + test "$PATH" = "$REPL_HOME/base/bin:${runtime}/bin:$REPL_HOME/base/bin:${runtime}/bin:/original/path" + ) + ( + source ${deployment.shellPackage}/nix-support/setup-hook + test "$MODE" = deployment + ) + ( + source ${overridden}/shell/nix-support/setup-hook + test "$MODE" = last + ) + ${lib.concatStringsSep "\n" (lib.mapAttrsToList (name: fixture: '' + mkdir -p "$out/${name}" + cp ${fixture}/metadata.json "$out/${name}/metadata.json" + cp ${fixture}/modules.json "$out/${name}/modules.json" + cp ${pkgs.writeText "environment-input.json" (builtins.toJSON environmentInput)} "$out/${name}/environment-input.json" + env -i ${environmentArgs} UNRELATED=not-exported \ + ${fixture}/bin/replit-toolchain-env > "$out/${name}/environment.env0" + jq -RsS ${lib.escapeShellArg decodeEnvironment} "$out/${name}/environment.env0" \ + > "$out/${name}/environment.json" + jq -e --arg literal ${lib.escapeShellArg definition.replit.env.LITERAL} ' + .REPL_HOME == "/tmp/project with spaces" + and .A_DEPENDENT == "/tmp/project with spaces/base/child" + and .BRACED == "/tmp/project with spaces/base/braced" + and .PYTHONPATH == "/inherited/suffix" + and .MISSING == "" + and .EMPTY == "" + and .MULTILINE == "first=line\nsecond=line" + and .LITERAL == $literal + and (has("UNRELATED") | not) + and (has("HOME") | not) + ' "$out/${name}/environment.json" + '') fixtures)} + jq -e --arg path "/tmp/project with spaces/base/bin:${runtime}/bin:/tmp/project with spaces/base/bin:${runtime}/bin:/original/path" \ + '.MODE == "development" and .PATH == $path' "$out/development/environment.json" + jq -e --arg path "/tmp/project with spaces/base/bin:${runtime}/bin:/original/path" \ + '.MODE == "deployment" and .PATH == $path' "$out/deployment/environment.json" + jq -e '.MODE == "last"' "$out/override/environment.json" + env -i PATH="" ${toolchain}/bin/replit-toolchain-env \ + | jq -RsS ${lib.escapeShellArg decodeEnvironment} > fallback-environment.json + jq -e --arg home "$PWD" '.REPL_HOME == $home and .PYTHONPATH == "/suffix"' fallback-environment.json +'' diff --git a/scripts/ci_check.sh b/scripts/ci_check.sh index 13dcab24..5a70c63d 100755 --- a/scripts/ci_check.sh +++ b/scripts/ci_check.sh @@ -17,6 +17,7 @@ nix eval "${NIX_FLAGS[@]}" --file scripts/module-registry-test.nix nix eval "${NIX_FLAGS[@]}" .#modules --json nix eval "${NIX_FLAGS[@]}" .#deploymentModules --json nix build "${NIX_FLAGS[@]}" .#checks.x86_64-linux.module-registry --no-link +nix build "${NIX_FLAGS[@]}" .#checks.x86_64-linux.flake-toolchain --no-link nix build "${NIX_FLAGS[@]}" .#checks.x86_64-linux.pip-user-site --no-link # The standalone lockfile OCI helper reconstructs old bundles, not current implementations.