titan-cli
Version:
Command Line Interface for TitanJS Scaffolding
88 lines (75 loc) • 3.08 kB
JavaScript
var views = function(viewname, binpath) {
//noinspection JSUnresolvedFunction
var path = require('path'),
fs = require('fs'),
mu = require('mu2'),
viewTemplateName = "vtemplate.html",
viewmodelTemplateName = "vmtemplate.js",
templatesPath = path.join(binpath, 'lib', 'node_modules', 'titan-cli', 'templates'),
encoding = 'utf-8';
function attempt(todo) {
if (typeof (todo) !== 'undefined') {
todo();
}
}
/**
* @public
* @async
* @method
* @param {String} templatename The template to scaffold based on
* @param {String} scaffoldFilename The new file name to scaffold to
* @param {String} projectRelativePath The relative path from the project root where the file should be saved
* @param {Object} hashmap The map from the data should be based on when compiling the scaffold origin template
* @param {Function} atSuccess The action to be executed when operation is succeed
*/
function scaffold(templatename, scaffoldFilename, projectRelativePath, hashmap, atSuccess) {
var compiledText = "";
mu.root = templatesPath;
var stream = mu.compileAndRender(templatename, hashmap);
stream.on('data', function(data) {
compiledText += data.toString();
});
stream.on('end', function() {
var newFilePath = path.join(projectRelativePath, scaffoldFilename);
fs.exists(projectRelativePath, function(exists) {
function writeProcess() {
fs.writeFile(newFilePath, compiledText, function(error) {
if (error) throw error;
console.log("Success!");
attempt(atSuccess);
});
}
if (exists) {
writeProcess();
} else {
console.log("'" + projectRelativePath + "' directory doesn't exist");
fs.mkdir(projectRelativePath, function() {
console.log("'" + projectRelativePath + "' directory has been created. Trying again...");
writeProcess();
});
}
});
});
}
function createView() {
var hashMap = {
'chaptername': viewname.toLowerCase()
};
console.log("Creating view for '" + viewname + "'");
scaffold(viewTemplateName, viewname.toLowerCase() + ".html", "views", hashMap, function() {
createViewModel();
});
}
function createViewModel() {
var hashMap = {
'chaptername': viewname
};
console.log("Creating viewmodel for '" + viewname + "'");
scaffold(viewmodelTemplateName, viewname + "ViewModel.js", "viewmodels", hashMap, function() {
console.log("The chapter has been created successfully");
});
}
createView();
};
//noinspection JSUnresolvedVariable
module.exports = views;