UNPKG

savant-cli

Version:
80 lines (73 loc) 2.32 kB
'use strict'; var crypto = require('crypto') , fs = require('fs') , path = require('path') , _ = require('underscore') , mkdirp = require('mkdirp') , async = require('async'); exports.sha256 = function(str) { var p = crypto.createHash('sha256'); p.update(str, 'utf-8'); return p.digest('hex'); }; exports.randomString = function(length) { var CHARS = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890_'; var result = ''; for (var i = 0; i < length; i++) result += CHARS[Math.floor(Math.random() * CHARS.length)]; return result; }; exports.ls = function ls(root, cb) { var tree = { name: '/', relPath: '', files: [] }; _ls('', tree, function(err) { if (err) return cb(err); return cb(null, tree); }); function _ls(dir, subtree, cb) { fs.readdir(path.join(root, dir), function(err, files) { if (err) return cb(err); async.each(files, function(file, cb) { fs.stat(path.join(root, dir, file), function(err, stat) { if (err) return cb(err); var relPath = path.join(dir, file); if (stat.isDirectory()) { var _tree = { name: file, relPath: relPath, files: [] }; subtree.files.push(_tree); _ls(path.join(dir, file), _tree, cb); } else { subtree.files.push({ name: file, relPath: relPath, ext: path.extname(relPath).replace(/^\./g, '') }); cb(null); } }); }, cb); }); } }; exports.copy = function(src, dst, data, cb) { fs.stat(src, function(err, stat) { if (err) return cb(err); if (stat.isDirectory()) { return mkdirp(dst, function(err) { if (err) return cb(err); fs.readdir(src, function(err, files) { if (err) return cb(err); async.each(files, function(file, cb) { exports.copy(path.join(src, file), path.join(dst, file), data, cb); }, cb); }); }); } else if (stat.isFile()) exports.compileFile(src, dst, data, cb); }); }; exports.compileFile = function(src, dst, data, cb) { fs.readFile(src, 'utf-8', function(err, text) { if (err) return cb(err); var compiled = _.template(text)(data); fs.writeFile(dst, compiled, 'utf-8', cb); }); };