diff --git a/package.json b/package.json index 1edbc70..eb094d1 100644 --- a/package.json +++ b/package.json @@ -30,6 +30,7 @@ "commander": "2.11.0", "fs": "0.0.1-security", "gifencoder": "^1.1.0", + "handlebars": "^4.1.2", "lodash": "^4.17.15", "nconf": "^0.8.5", "png-file-stream": "^1.2.1", diff --git a/src/util/localfs.js b/src/util/localfs.js index b8b9357..03c3855 100644 --- a/src/util/localfs.js +++ b/src/util/localfs.js @@ -1,6 +1,7 @@ const _ = require('lodash'); const fs = require('fs'); +const Handlebars = require('handlebars'); const Logger = require('./logger.js'); const logger = new Logger('localfs'); @@ -27,23 +28,58 @@ LocalFS.prototype.checkExists = function(name, output, showOutput) { } return true; } + + if (fs.existsSync(`${name}.hbs`)) { + if (showOutput) { + logger.showResult(`A template file exists for ${output}.`); + } + return true; + } + if (showOutput) { logger.justShow(`${output} does not exists.`); } + return false; }; LocalFS.prototype.readFile = function(name, _showOnError) { - return fs.readFileSync(name, 'utf8', (error, _data) => { + let useTemplating = false; + + // if a file with a .hbs exist, use it for templating + if (fs.existsSync(`${name}.hbs`)) { + name = `${name}.hbs`; + useTemplating = true; + } + + // Read the 'name' file (or the 'name.tml') + const src = fs.readFileSync(name, 'utf8', (error, _data) => { if (!error) { logger.showResult(`Read file ${name} successfully.`); } else { logger.showError(`Error in reading file ${name}`); } }); + + // If the file was not found (or cannot be read) + if (src === null) { + return null; + } + + // if the file is not a template file + if (!useTemplating) { + return src; + } + logger.showResult(`Running templating engine on ${name}`); + // If the file is a template file, let handlebars do its magic + const template = Handlebars.compile(src); + return template(process.env); }; LocalFS.prototype.writeFile = function(name, content) { + if (fs.existsSync(`${name}.hbs`)) { + logger.showError(`The ${name} file will be ignored since ${name}.hbs exists`); + } fs.writeFileSync(name, content); }; @@ -83,7 +119,7 @@ LocalFS.prototype.writeStream = function(name) { }; LocalFS.prototype.getFileName = function(fileNameWithExtension) { - return fileNameWithExtension.replace(/\.[^/.]+$/, ''); + return fileNameWithExtension.replace(/\..+$/, ''); }; module.exports = LocalFS;