embark-area-51/lib/modules/scaffolding-solidity/index.js

58 lines
2.1 KiB
JavaScript
Raw Normal View History

const Handlebars = require('handlebars');
const fs = require('../../core/fs');
2018-10-17 20:18:24 +00:00
const utils = require('../../utils/utils');
2018-10-12 19:07:59 +00:00
const capitalize = string => string.charAt(0).toUpperCase() + string.slice(1);
class ScaffoldingSolidity {
constructor(embark, options){
this.embark = embark;
this.options = options;
this.embark.registerDappGenerator('solidity', this.build.bind(this));
}
_generateFile(contract, templateFilename, extension, data, overwrite){
2018-10-15 12:36:59 +00:00
const filename = capitalize(contract.className.toLowerCase()) + '.' + extension;
2018-10-17 19:08:36 +00:00
const contractDirs = this.embark.config.embarkConfig.contracts;
const contractDir = Array.isArray(contractDirs) ? contractDirs[0] : contractDirs;
const filePath = fs.dappPath(contractDir.replace(/\*/g, ''), filename);
if (!overwrite && fs.existsSync(filePath)){
throw new Error("file '" + filePath + "' already exists");
}
2018-10-17 20:18:24 +00:00
const templatePath = utils.joinPath(__dirname, 'templates/' + templateFilename);
const source = fs.readFileSync(templatePath).toString();
const template = Handlebars.compile(source);
// Write template
const result = template(data);
fs.writeFileSync(filePath, result);
return filePath;
}
build(contract, overwrite, cb){
try {
2018-10-12 19:07:59 +00:00
contract.className = capitalize(contract.className);
const filename = contract.className;
2018-10-17 20:18:24 +00:00
const filePath = this._generateFile(contract, 'contract.sol.hbs', 'sol', {
'contractName': contract.className,
'structName': contract.className + "Struct",
'fields': Object.keys(contract.fields).map(f => {
return {name:f, type: contract.fields[f]};
})
}, overwrite);
this.embark.logger.info("contracts/" + filename + ".sol generated");
cb(null, filePath);
} catch(error) {
this.embark.logger.error(error.message);
process.exit(1);
}
}
}
module.exports = ScaffoldingSolidity;