Skip to content

Instantly share code, notes, and snippets.

@hayesgm
Last active September 9, 2020 20:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hayesgm/cbfc26a2ba9a7a6ce38febeb7bf6a5f8 to your computer and use it in GitHub Desktop.
Save hayesgm/cbfc26a2ba9a7a6ce38febeb7bf6a5f8 to your computer and use it in GitHub Desktop.
#!env node
let path = require('path');
let fs = require('fs').promises;
async function run(build, contract) {
let buildJson = JSON.parse(await fs.readFile(build, 'utf8'));
let contracts = buildJson['contracts'];
let contractPair = Object.entries(contracts).find(([k, v]) => k.split(':')[1] === contract);
if (!contractPair) {
throw new Error(`Could not find contract \`${contract}\` in build \`${build}\``);
}
let [contractFilePair, contractData] = contractPair;
let metadata = JSON.parse(contractData.metadata);
let sources = metadata['sources'];
let contractFile = contractFilePair.split(':')[0];
let target = sources[contractFile].content;
function resolveImports(current, currentFile, included) {
if (!current.includes('import')) {
return [current, included];
}
let importRegex = /import\s+["']([^"']+)["']\s*;/im;
let nextIncluded = [];
let next = current.replace(importRegex, (match, contractName) => {
let resolvedContract = path.join(currentFile, '..', contractName);
// Uck, we have to change the relative resolves here
if (included.includes(resolvedContract)) {
return "";
} else {
let content = sources[resolvedContract].content;
let [res, newIncluded] = resolveImports(
content
.replace(/pragma[^;]*;\n+/g, '')
.replace(/\/\/\s*SPDX-License-Identifier[^\n]*\n+/g, ''),
resolvedContract,
included,
false);
nextIncluded = [resolvedContract, ...newIncluded];
return res;
}
});
return resolveImports(next, currentFile, nextIncluded);
}
let [file, _included] = resolveImports(target, contractFile, [contractFile]);
console.log(file);
}
let [_n, _f, build, contract] = process.argv;
if (!build || !contract) {
console.error(`usage: ${path.relative(process.cwd(), _f)} <build file> <contract name>`);
process.exit(1);
}
run(build, contract);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment