-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
config-loading.ts
322 lines (269 loc) · 9.41 KB
/
config-loading.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
import type StackTraceParserT from "stacktrace-parser";
import chalk from "chalk";
import debug from "debug";
import fsExtra from "fs-extra";
import path from "path";
import semver from "semver";
import {
HardhatArguments,
HardhatConfig,
HardhatUserConfig,
} from "../../../types";
import { HardhatContext } from "../../context";
import { findClosestPackageJson } from "../../util/packageInfo";
import { HardhatError } from "../errors";
import { ERRORS } from "../errors-list";
import { getUserConfigPath } from "../project-structure";
import { SUPPORTED_SOLIDITY_VERSION_RANGE } from "../../hardhat-network/stack-traces/constants";
import { resolveConfig } from "./config-resolution";
import { validateConfig } from "./config-validation";
import { DEFAULT_SOLC_VERSION } from "./default-config";
const log = debug("hardhat:core:config");
function importCsjOrEsModule(filePath: string): any {
const imported = require(filePath);
return imported.default !== undefined ? imported.default : imported;
}
export function resolveConfigPath(configPath: string | undefined) {
if (configPath === undefined) {
configPath = getUserConfigPath();
} else {
if (!path.isAbsolute(configPath)) {
configPath = path.join(process.cwd(), configPath);
configPath = path.normalize(configPath);
}
}
return configPath;
}
export function loadConfigAndTasks(
hardhatArguments?: Partial<HardhatArguments>,
{
showEmptyConfigWarning = false,
showSolidityConfigWarnings = false,
}: {
showEmptyConfigWarning?: boolean;
showSolidityConfigWarnings?: boolean;
} = {
showEmptyConfigWarning: false,
showSolidityConfigWarnings: false,
}
): { resolvedConfig: HardhatConfig; userConfig: HardhatUserConfig } {
let configPath =
hardhatArguments !== undefined ? hardhatArguments.config : undefined;
configPath = resolveConfigPath(configPath);
log(`Loading Hardhat config from ${configPath}`);
// Before loading the builtin tasks, the default and user's config we expose
// the config env in the global object.
const configEnv = require("./config-env");
const globalAsAny: any = global;
Object.entries(configEnv).forEach(
([key, value]) => (globalAsAny[key] = value)
);
const ctx = HardhatContext.getHardhatContext();
ctx.setConfigLoadingAsStarted();
let userConfig;
try {
require("../tasks/builtin-tasks");
userConfig = importCsjOrEsModule(configPath);
} catch (e) {
analyzeModuleNotFoundError(e, configPath);
// eslint-disable-next-line @nomiclabs/hardhat-internal-rules/only-hardhat-error
throw e;
} finally {
ctx.setConfigLoadingAsFinished();
}
if (showEmptyConfigWarning) {
checkEmptyConfig(userConfig, { showSolidityConfigWarnings });
}
validateConfig(userConfig);
if (showSolidityConfigWarnings) {
checkMissingSolidityConfig(userConfig);
}
// To avoid bad practices we remove the previously exported stuff
Object.keys(configEnv).forEach((key) => (globalAsAny[key] = undefined));
const frozenUserConfig = deepFreezeUserConfig(userConfig);
const resolved = resolveConfig(configPath, userConfig);
for (const extender of HardhatContext.getHardhatContext().configExtenders) {
extender(resolved, frozenUserConfig);
}
if (showSolidityConfigWarnings) {
checkUnsupportedSolidityConfig(resolved);
checkUnsupportedRemappings(resolved);
}
return { resolvedConfig: resolved, userConfig: frozenUserConfig };
}
function deepFreezeUserConfig(
config: any,
propertyPath: Array<string | number | symbol> = []
) {
if (typeof config !== "object" || config === null) {
return config;
}
return new Proxy(config, {
get(target: any, property: string | number | symbol, receiver: any): any {
return deepFreezeUserConfig(Reflect.get(target, property, receiver), [
...propertyPath,
property,
]);
},
set(
target: any,
property: string | number | symbol,
_value: any,
_receiver: any
): boolean {
throw new HardhatError(ERRORS.GENERAL.USER_CONFIG_MODIFIED, {
path: [...propertyPath, property]
.map((pathPart) => pathPart.toString())
.join("."),
});
},
});
}
/**
* Receives an Error and checks if it's a MODULE_NOT_FOUND and the reason that
* caused it.
*
* If it can infer the reason, it throws an appropiate error. Otherwise it does
* nothing.
*/
export function analyzeModuleNotFoundError(error: any, configPath: string) {
const stackTraceParser =
require("stacktrace-parser") as typeof StackTraceParserT;
if (error.code !== "MODULE_NOT_FOUND") {
return;
}
const stackTrace = stackTraceParser.parse(error.stack);
const throwingFile = stackTrace
.filter((x) => x.file !== null)
.map((x) => x.file!)
// ignore frames related to source map support
.filter((x) => !x.includes(path.join("@cspotcode", "source-map-support")))
.find((x) => path.isAbsolute(x));
if (throwingFile === null || throwingFile === undefined) {
return;
}
// if the error comes from the config file, we ignore it because we know it's
// a direct import that's missing
if (throwingFile === configPath) {
return;
}
const packageJsonPath = findClosestPackageJson(throwingFile);
if (packageJsonPath === null) {
return;
}
const packageJson = fsExtra.readJsonSync(packageJsonPath);
const peerDependencies: { [name: string]: string } =
packageJson.peerDependencies ?? {};
if (peerDependencies["@nomiclabs/buidler"] !== undefined) {
throw new HardhatError(ERRORS.PLUGINS.BUIDLER_PLUGIN, {
plugin: packageJson.name,
});
}
// if the problem doesn't come from a hardhat plugin, we ignore it
if (peerDependencies.hardhat === undefined) {
return;
}
const missingPeerDependencies: { [name: string]: string } = {};
for (const [peerDependency, version] of Object.entries(peerDependencies)) {
const peerDependencyPackageJson = readPackageJson(peerDependency);
if (peerDependencyPackageJson === undefined) {
missingPeerDependencies[peerDependency] = version;
}
}
const missingPeerDependenciesNames = Object.keys(missingPeerDependencies);
if (missingPeerDependenciesNames.length > 0) {
throw new HardhatError(ERRORS.PLUGINS.MISSING_DEPENDENCIES, {
plugin: packageJson.name,
missingDependencies: missingPeerDependenciesNames.join(", "),
missingDependenciesVersions: Object.entries(missingPeerDependencies)
.map(([name, version]) => `"${name}@${version}"`)
.join(" "),
});
}
}
interface PackageJson {
name: string;
version: string;
peerDependencies?: {
[name: string]: string;
};
}
function readPackageJson(packageName: string): PackageJson | undefined {
try {
const packageJsonPath = require.resolve(
path.join(packageName, "package.json")
);
return require(packageJsonPath);
} catch {
return undefined;
}
}
function checkEmptyConfig(
userConfig: any,
{ showSolidityConfigWarnings }: { showSolidityConfigWarnings: boolean }
) {
if (userConfig === undefined || Object.keys(userConfig).length === 0) {
let warning = `Hardhat config is returning an empty config object, check the export from the config file if this is unexpected.\n`;
// This 'learn more' section is also printed by the solidity config warning,
// so we need to check to avoid printing it twice
if (!showSolidityConfigWarnings) {
warning += `\nLearn more about configuring Hardhat at https://hardhat.org/config\n`;
}
console.warn(chalk.yellow(warning));
}
}
function checkMissingSolidityConfig(userConfig: any) {
if (userConfig.solidity === undefined) {
console.warn(
chalk.yellow(
`Solidity compiler is not configured. Version ${DEFAULT_SOLC_VERSION} will be used by default. Add a 'solidity' entry to your configuration to suppress this warning.
Learn more about compiler configuration at https://hardhat.org/config
`
)
);
}
}
function checkUnsupportedSolidityConfig(resolvedConfig: HardhatConfig) {
const compilerVersions = resolvedConfig.solidity.compilers.map(
(x) => x.version
);
const overrideVersions = Object.values(resolvedConfig.solidity.overrides).map(
(x) => x.version
);
const solcVersions = [...compilerVersions, ...overrideVersions];
const unsupportedVersions: string[] = [];
for (const solcVersion of solcVersions) {
if (!semver.satisfies(solcVersion, SUPPORTED_SOLIDITY_VERSION_RANGE)) {
unsupportedVersions.push(solcVersion);
}
}
if (unsupportedVersions.length > 0) {
console.warn(
chalk.yellow(
`Solidity ${unsupportedVersions.join(", ")} ${
unsupportedVersions.length === 1 ? "is" : "are"
} not fully supported yet. You can still use Hardhat, but some features, like stack traces, might not work correctly.
Learn more at https://hardhat.org/hardhat-runner/docs/reference/solidity-support
`
)
);
}
}
function checkUnsupportedRemappings({ solidity }: HardhatConfig) {
const solcConfigs = [
...solidity.compilers,
...Object.values(solidity.overrides),
];
const remappings = solcConfigs.filter(
({ settings }) => settings.remappings !== undefined
);
if (remappings.length > 0) {
console.warn(
chalk.yellow(
`Solidity remappings are not currently supported; you may experience unexpected compilation results. Remove any 'remappings' fields from your configuration to suppress this warning.
Learn more about compiler configuration at https://hardhat.org/config
`
)
);
}
}