Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix hre initialization #5485

Merged
merged 5 commits into from
Jul 5, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions v-next/hardhat/.eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
const { createConfig } = require("../../config-v-next/eslint.cjs");

module.exports = createConfig(__filename);

module.exports.rules["no-restricted-imports"][1].paths.push({
// TODO: Rename this once we migrate to the official package names
name: "@ignored/hardhat-vnext-core",
importNames: ["createHardhatRuntimeEnvironment"],
message:
"Use the version of `createHardhatRuntimeEnvironment` found in `hre.js` instead of this one.",
});
23 changes: 15 additions & 8 deletions v-next/hardhat/src/hre.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import type { HardhatUserConfig } from "./types/config.js";
import type { GlobalOptions } from "./types/global-options.js";
import type { HardhatRuntimeEnvironment } from "./types/hre.js";
import type { UnsafeHardhatRuntimeEnvironmentOptions } from "@ignored/hardhat-vnext-core/types/cli";

import {
// eslint-disable-next-line no-restricted-imports -- This is the one place where we allow it
createHardhatRuntimeEnvironment as originalCreateHardhatRuntimeEnvironment,
resolvePluginList,
} from "@ignored/hardhat-vnext-core";
Expand All @@ -20,19 +22,24 @@ import { builtinPlugins } from "./internal/builtin-plugins/index.js";
export async function createHardhatRuntimeEnvironment(
config: HardhatUserConfig,
userProvidedGlobalOptions: Partial<GlobalOptions> = {},
unsafeOptions: UnsafeHardhatRuntimeEnvironmentOptions = {},
): Promise<HardhatRuntimeEnvironment> {
const plugins = [...builtinPlugins, ...(config.plugins ?? [])];
if (unsafeOptions.resolvedPlugins === undefined) {
const plugins = [...builtinPlugins, ...(config.plugins ?? [])];

// We resolve the plugins within npm modules relative to the current working
const basePathForNpmResolution = process.cwd();
const resolvedPlugins = await resolvePluginList(
plugins,
basePathForNpmResolution,
);
// We resolve the plugins within npm modules relative to the current working
const basePathForNpmResolution = process.cwd();
const resolvedPlugins = await resolvePluginList(
plugins,
basePathForNpmResolution,
);

unsafeOptions.resolvedPlugins = resolvedPlugins;
}

return originalCreateHardhatRuntimeEnvironment(
config,
userProvidedGlobalOptions,
{ resolvedPlugins },
unsafeOptions,
);
}
26 changes: 19 additions & 7 deletions v-next/hardhat/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,28 @@ import type { TaskManager } from "./types/tasks.js";
import type { UserInterruptionManager } from "./types/user-interruptions.js";

import { resolveHardhatConfigPath } from "./config.js";
import { createHardhatRuntimeEnvironment } from "./hre.js";
import { importUserConfig } from "./internal/helpers/config-loading.js";
import { getHardhatRuntimeEnvironmentSingleton } from "./internal/hre-singleton.js";
import {
getHardhatRuntimeEnvironmentSingleton,
setHardhatRuntimeEnvironmentSingleton,
} from "./internal/hre-singleton.js";

/* eslint-disable no-restricted-syntax -- Allow top-level await here */
const configPath = await resolveHardhatConfigPath();
const userConfig = await importUserConfig(configPath);
let maybeHre: HardhatRuntimeEnvironment | undefined =
getHardhatRuntimeEnvironmentSingleton();

const hre: HardhatRuntimeEnvironment =
await getHardhatRuntimeEnvironmentSingleton(userConfig);
/* eslint-enable no-restricted-syntax */
if (maybeHre === undefined) {
/* eslint-disable no-restricted-syntax -- Allow top-level await here */
const configPath = await resolveHardhatConfigPath();
const userConfig = await importUserConfig(configPath);

maybeHre = await createHardhatRuntimeEnvironment(userConfig);
/* eslint-enable no-restricted-syntax */

setHardhatRuntimeEnvironmentSingleton(maybeHre);
}

const hre: HardhatRuntimeEnvironment = maybeHre;

export const config: HardhatConfig = hre.config;
export const tasks: TaskManager = hre.tasks;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ const hardhatPlugin: HardhatPlugin = {
})
.build(),
],
globalOptions: [globalFlag({ name: "flag", description: "A flag" })],
globalOptions: [globalFlag({ name: "fooPluginFlag", description: "A flag" })],
};

export default hardhatPlugin;
13 changes: 7 additions & 6 deletions v-next/hardhat/src/internal/cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,10 @@ import { isCi } from "@ignored/hardhat-vnext-utils/ci";
import { kebabToCamelCase } from "@ignored/hardhat-vnext-utils/string";

import { resolveHardhatConfigPath } from "../../config.js";
import { createHardhatRuntimeEnvironment } from "../../hre.js";
import { builtinPlugins } from "../builtin-plugins/index.js";
import { importUserConfig } from "../helpers/config-loading.js";
import { getHardhatRuntimeEnvironmentSingleton } from "../hre-singleton.js";
import { setHardhatRuntimeEnvironmentSingleton } from "../hre-singleton.js";

import { printErrorMessages } from "./error-handler.js";
import { getGlobalHelpString } from "./helpers/getGlobalHelpString.js";
Expand Down Expand Up @@ -84,15 +85,15 @@ export async function main(
usedCliArguments,
);

const hre = await getHardhatRuntimeEnvironmentSingleton(
const hre = await createHardhatRuntimeEnvironment(
userConfig,
userProvidedGlobalOptions,
{
resolvedPlugins,
globalOptionDefinitions,
},
{ resolvedPlugins, globalOptionDefinitions },
);

// This must be the first time we set it, otherwise we let it crash
setHardhatRuntimeEnvironmentSingleton(hre);

const taskOrId = parseTask(cliArguments, usedCliArguments, hre);

if (Array.isArray(taskOrId)) {
Expand Down
27 changes: 16 additions & 11 deletions v-next/hardhat/src/internal/hre-singleton.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,31 @@
import type { HardhatRuntimeEnvironment } from "../types/hre.js";

import { createHardhatRuntimeEnvironment } from "@ignored/hardhat-vnext-core";
import { assertHardhatInvariant } from "@ignored/hardhat-vnext-errors";

let hre: HardhatRuntimeEnvironment | undefined;

/**
* This function returns a singleton instance of the Hardhat Runtime Environment.
* This function returns a singleton instance of the Hardhat Runtime Environment
* if it was already initialized.
*
* It exists so that the CLI and the programmatic API are always using the same HRE instance.
*
* Note: Only the params of the first call are used.
*/
export async function getHardhatRuntimeEnvironmentSingleton(
...params: Parameters<typeof createHardhatRuntimeEnvironment>
): Promise<HardhatRuntimeEnvironment> {
if (hre === undefined) {
hre = await createHardhatRuntimeEnvironment(...params);
}

export function getHardhatRuntimeEnvironmentSingleton():
| HardhatRuntimeEnvironment
| undefined {
return hre;
}

/**
* Sets the singleton instance of the Hardhat Runtime Environment.
*/
export function setHardhatRuntimeEnvironmentSingleton(
newHre: HardhatRuntimeEnvironment,
): void {
assertHardhatInvariant(hre === undefined, "HRE singleton already set");
hre = newHre;
}

/**
* This function resets the singleton instance of the Hardhat Runtime Environment.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import hre from "@ignored/hardhat-vnext";
import maybeHre from "@ignored/hardhat-vnext";

if (!hre.tasks.rootTasks.has("test")) {
if (!maybeHre.tasks.rootTasks.has("test")) {
throw new Error("test task not found");
}
56 changes: 33 additions & 23 deletions v-next/hardhat/test/hre/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import assert from "node:assert/strict";
import { describe, it } from "node:test";
import { afterEach, describe, it } from "node:test";

import { HardhatError } from "@ignored/hardhat-vnext-errors";

Expand All @@ -9,38 +9,47 @@ import { builtinPlugins } from "../../src/internal/builtin-plugins/index.js";
import {
getHardhatRuntimeEnvironmentSingleton,
resetHardhatRuntimeEnvironmentSingleton,
setHardhatRuntimeEnvironmentSingleton,
} from "../../src/internal/hre-singleton.js";
import { useFixtureProject } from "../helpers/project.js";

describe("HRE", () => {
afterEach(() => {
resetHardhatRuntimeEnvironmentSingleton();
});

describe("createHardhatRuntimeEnvironment", () => {
it("should include the built-in plugins", async () => {
const hre = await createHardhatRuntimeEnvironment({});

assert.deepEqual(hre.config.plugins, builtinPlugins);

resetHardhatRuntimeEnvironmentSingleton();
});
});

describe("getHardhatRuntimeEnvironmentSingleton", () => {
it("should return the same instance", async () => {
const hre1 = await getHardhatRuntimeEnvironmentSingleton({
plugins: [{ id: "custom task" }],
});
const hre2 = await getHardhatRuntimeEnvironmentSingleton({});

assert.deepEqual(
hre1.config.plugins.find((p) => p.id === "custom task"),
{ id: "custom task" },
);
assert.deepEqual(
hre2.config.plugins.find((p) => p.id === "custom task"),
{ id: "custom task" },
);
assert.deepEqual(hre1, hre2);

resetHardhatRuntimeEnvironmentSingleton();
it("Should return undefined if it wasn't set", () => {
assert.equal(getHardhatRuntimeEnvironmentSingleton(), undefined);
assert.equal(getHardhatRuntimeEnvironmentSingleton(), undefined);
});

it("should return the same instance after it's set", async () => {
const hre = await createHardhatRuntimeEnvironment({});
setHardhatRuntimeEnvironmentSingleton(hre);

const hre1 = getHardhatRuntimeEnvironmentSingleton();
const hre2 = getHardhatRuntimeEnvironmentSingleton();

assert.ok(hre1 === hre, "The instances are not the same");
assert.ok(hre2 === hre, "The instances are not the same");
});

it("should include the builtin plugins", async () => {
const hre = await createHardhatRuntimeEnvironment({});
setHardhatRuntimeEnvironmentSingleton(hre);
const singletonHre = getHardhatRuntimeEnvironmentSingleton();

assert.ok(singletonHre === hre, "The instances are not the same");
assert.deepEqual(singletonHre.config.plugins, builtinPlugins);
});
});

Expand Down Expand Up @@ -124,9 +133,10 @@ describe("HRE", () => {
it("should load the config file", async () => {
const hre = await import("../../src/index.js");

assert.deepEqual(hre.config.plugins, [{ id: "test-plugin" }]);

resetHardhatRuntimeEnvironmentSingleton();
assert.deepEqual(hre.config.plugins, [
...builtinPlugins,
{ id: "test-plugin" },
]);
});
});
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import type { HardhatRuntimeEnvironment } from "@ignored/hardhat-vnext-core/type
import assert from "node:assert/strict";
import { before, describe, it } from "node:test";

import { createHardhatRuntimeEnvironment } from "@ignored/hardhat-vnext-core";
import { HardhatError } from "@ignored/hardhat-vnext-errors";

import { createHardhatRuntimeEnvironment } from "../../../../src/hre.js";
import runScriptWithHardhat from "../../../../src/internal/builtin-plugins/run/runScriptWithHardhat.js";
import { useFixtureProject } from "../../../helpers/project.js";

Expand Down
4 changes: 2 additions & 2 deletions v-next/hardhat/test/internal/cli/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import assert from "node:assert/strict";
import { afterEach, before, describe, it } from "node:test";
import { pathToFileURL } from "node:url";

import { createHardhatRuntimeEnvironment } from "@ignored/hardhat-vnext-core";
import {
ArgumentType,
globalFlag,
Expand All @@ -25,6 +24,7 @@ import { HardhatError } from "@ignored/hardhat-vnext-errors";
import { isCi } from "@ignored/hardhat-vnext-utils/ci";
import chalk from "chalk";

import { createHardhatRuntimeEnvironment } from "../../../src/hre.js";
import {
main,
parseGlobalOptions,
Expand Down Expand Up @@ -228,7 +228,7 @@ GLOBAL OPTIONS:
--help Shows this message, or a task's help if its name is provided.
--show-stack-traces Show stack traces (always enabled on CI servers).
--version Shows hardhat's version.
--flag A flag
--foo-plugin-flag A flag

To get help for a specific task run: npx hardhat <TASK> [SUBTASK] --help`;

Expand Down