UNPKG

2.81 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const config_env_1 = require("../internal/core/config/config-env");
4const errors_1 = require("../internal/core/errors");
5const errors_list_1 = require("../internal/core/errors-list");
6const packageInfo_1 = require("../internal/util/packageInfo");
7const task_names_1 = require("./task-names");
8function getSortedFiles(dependenciesGraph) {
9 const tsort = require("tsort");
10 const graph = tsort();
11 const filesMap = {};
12 const resolvedFiles = dependenciesGraph.getResolvedFiles();
13 resolvedFiles.forEach((f) => (filesMap[f.globalName] = f));
14 for (const [from, deps] of dependenciesGraph.dependenciesPerFile.entries()) {
15 for (const to of deps) {
16 graph.add(to.globalName, from.globalName);
17 }
18 }
19 try {
20 const topologicalSortedNames = graph.sort();
21 // If an entry has no dependency it won't be included in the graph, so we
22 // add them and then dedup the array
23 const withEntries = topologicalSortedNames.concat(resolvedFiles.map((f) => f.globalName));
24 const sortedNames = [...new Set(withEntries)];
25 return sortedNames.map((n) => filesMap[n]);
26 }
27 catch (error) {
28 if (error.toString().includes("Error: There is a cycle in the graph.")) {
29 throw new errors_1.BuidlerError(errors_list_1.ERRORS.BUILTIN_TASKS.FLATTEN_CYCLE, error);
30 }
31 // tslint:disable-next-line only-buidler-error
32 throw error;
33 }
34}
35function getFileWithoutImports(resolvedFile) {
36 const IMPORT_SOLIDITY_REGEX = /^\s*import(\s+).*$/gm;
37 return resolvedFile.content.replace(IMPORT_SOLIDITY_REGEX, "").trim();
38}
39function default_1() {
40 config_env_1.internalTask(task_names_1.TASK_FLATTEN_GET_FLATTENED_SOURCE, "Returns all contracts and their dependencies flattened", async (_, { run }) => {
41 let flattened = "";
42 const graph = await run(task_names_1.TASK_COMPILE_GET_DEPENDENCY_GRAPH);
43 if (graph.getResolvedFiles().length === 0) {
44 return flattened;
45 }
46 const packageJson = await packageInfo_1.getPackageJson();
47 flattened += `// Sources flattened with buidler v${packageJson.version} https://buidler.dev`;
48 const sortedFiles = getSortedFiles(graph);
49 for (const file of sortedFiles) {
50 flattened += `\n\n// File ${file.getVersionedName()}\n`;
51 flattened += `\n${getFileWithoutImports(file)}\n`;
52 }
53 return flattened.trim();
54 });
55 config_env_1.task(task_names_1.TASK_FLATTEN, "Flattens and prints all contracts and their dependencies", async (_, { run }) => {
56 console.log(await run(task_names_1.TASK_FLATTEN_GET_FLATTENED_SOURCE));
57 });
58}
59exports.default = default_1;
60//# sourceMappingURL=flatten.js.map
\No newline at end of file