Skip to content
This repository was archived by the owner on May 5, 2021. It is now read-only.

PoC: Add support for templating #148

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
40 changes: 38 additions & 2 deletions src/util/localfs.js
Original file line number Diff line number Diff line change
@@ -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');
Expand All @@ -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);
};

Expand Down Expand Up @@ -83,7 +119,7 @@ LocalFS.prototype.writeStream = function(name) {
};

LocalFS.prototype.getFileName = function(fileNameWithExtension) {
return fileNameWithExtension.replace(/\.[^/.]+$/, '');
return fileNameWithExtension.replace(/\..+$/, '');
};

module.exports = LocalFS;