fdm
Version:
基于gulp的1688前端集成化工具
311 lines (270 loc) • 8.59 kB
JavaScript
var path = require('path');
var fs = require('fs');
var fs = require('fs');
var spawn = require('win-spawn');
var ncp = require('ncp').ncp;
var grunt = require('grunt');
var stripJsonComments = require('strip-json-comments');
var fsync = require('fs-sync');
require('colors');
ncp.limit = 16;
exports.test = function(){
spawn('npm', ['ls'],{
stdio: 'inherit'
});
}
// Get template from git
exports.getFromGit = function(url, dest) {
console.log("Start getting files from github ".green);
var args = ['clone', url];
if(dest){
args.push(dest);
}
return spawn('git', args, {
stdio: 'inherit'
});
// if (!fs.existsSync(dest)) {
// console.log(url);
// return spawn('git', ['clone', url, dest], {stdio: 'inherit'});
// } else {
// return spawn('git', ['pull', 'origin', 'master'], {stdio: 'inherit', 'cwd': dest});
// }
}
exports.getFromNPM = function(name,dest) {
console.log();
console.log("Start getting files from npm ".green);
return spawn('npm', ['install', name], {
stdio: 'inherit',
cwd:dest
});
}
// Get template dir
exports.getTempDir = function(templatePath) {
var pathType = this.parsePath(templatePath);
var templateDir = '';
if (pathType != 'local') {
var homeDir = this.getHomeDir();
var templatePath = templatePath.replace('fdm-init-','').split('/');
templatePath = templatePath[templatePath.length - 1].replace(/(.*\/){0,}([^.]+).*/ig, '$2');
templateDir = path.join(homeDir, 'neat.fdm', 'init', 'templates', templatePath);
if (fs.existsSync(templateDir)) {
return templateDir;
}
var arr = templateDir.split(path.sep);
for (var i = 2, l = arr.length; i <= l; i++) {
var p = arr.slice(0, i).join(path.sep);
if (fs.existsSync(p)) continue;
fs.mkdirSync(p);
}
} else {
templateDir = templatePath;
}
return templateDir;
};
// get fdm dir
exports.getFdmDir = function(){
return path.join(this.getHomeDir(), 'neat.fdm');
}
// Get home dir
exports.getHomeDir = function() {
var homeDir = process.env.HOME || process.env.USERPROFILE;
if (!homeDir) {
homeDir = process.env.HOMEDRIVE + process.env.HOMEPATH;
}
return homeDir;
}
exports.getConfig = function() {
var configPath = path.join(this.getHomeDir(), 'neat.fdm', 'config.json');
if (fs.existsSync(configPath)) {
var data = fs.readFileSync(configPath, {
encoding: 'utf8'
});
// 对去除json文件注释
try{
return JSON.parse(stripJsonComments(data));
}catch(e){
console.log("配置文件格式错误".red);
console.log(e);
console.log("请前往"+configPath+"修改配置");
process.exit(1);
}
} else {
this.setConfig();
this.getConfig();
}
}
exports.setConfig = function(callback) {
var fdmPath = path.join(this.getHomeDir(), 'neat.fdm');
var configPath = path.join(this.getHomeDir(), 'neat.fdm', 'config.json');
var me = this;
if(!fs.existsSync(fdmPath)){
fs.mkdirSync(fdmPath);
}
if (!fs.existsSync(configPath)) {
var data = require('../package.json').fdmConfig;
data.fdserver.config = fdmPath+'/server.config.js';
this.throw (function() {
fs.writeFileSync(configPath, JSON.stringify(data, null, '\t'), {
encoding: 'utf8'
});
console.log('Created '.green + configPath + ' successfully'.green);
})
}
// 初始化sever配置文件
if(!fs.existsSync(fdmPath+'/server.config.js')){
fsync.copy(path.join(me.baseModulePath(),'fdserver','config.js.sample'),fdmPath+'/server.config.js');
}
}
exports.throw = function(func) {
try {
func();
} catch (e) {
console.error(e);
process.exit();
}
}
// 获取fdm的node_module路径
exports.baseModulePath = function(){
return path.resolve(__dirname,'../','node_modules');
}
exports.parsePath = function(arg) {
if (/^(.{1,2})\//.test(arg.replace('\\','/'))) {
return 'local';
} else if (/(^https:\/\/git)|(^git@git)/g.test(arg)) {
return 'github';
} else if (/^[0-9a-zA-Z]/.test(arg)) {
return 'alias';
} else {
return 'other';
}
}
// 文件异步复制,同步可用fsync.copy();
exports.copyFile = function(from, to, done) {
ncp(from, to, {
filter: /^(?!\.git)/
}, function(err) {
if (err) {
return console.error(err);
}
console.log();
console.log('复制文件到 '.green + path.resolve(to) + ' 成功'.green);
if (done) {
done();
}
});
}
// 删除目录
exports.deleteFolder = function(path) {
var me = this;
if( fs.existsSync(path) ) {
fs.readdirSync(path).forEach(function(file,index){
var curPath = path + "/" + file;
if(fs.lstatSync(curPath).isDirectory()) { // recurse
me.deleteFolder(curPath);
} else { // delete file
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(path);
console.log('删除 '+path+' 成功');
}
};
exports.getFdmRepo = function(keyword,callback) {
var keyword = keyword||'fdmplugin';
var http = require('http');
var reqUrl = 'http://registry.npmjs.org/-/_view/byKeyword?startkey=[%22'+keyword+'%22]&endkey=[%22'+keyword+'%22,{}]&group_level=3';
var buffers = '';
http.get(reqUrl, function(res) {
if (res.statusCode == 200) {
res.on('data', function(data) {
buffers += data;
});
res.on("end", function() {
var data = JSON.parse(buffers.toString());
console.log();
console.log(keyword=="fdmplugin"?"插件列表":"模板列表");
data.rows.forEach(function(d) {
console.log(' ' + d.key[1].green + ' ' + d.key[2]);
});
if(callback){
callback(data);
}
});
} else {
console.log("Request failed".red);
}
}).on('error', function(e) {
console.log("Error: " + e.message.red);
});
}
exports.deleteFile = function(filepath,callback){
var files = [];
var me = this;
if( fs.existsSync(filepath) ) {
console.log("Start deleting ".green+filepath);
try{
files = fs.readdirSync(filepath);
files.forEach(function(file,index){
var curPath = filepath + "/" + file;
if(fs.statSync(curPath).isDirectory()) {
me.deleteFile(curPath);
} else {
fs.unlinkSync(curPath);
}
});
fs.rmdirSync(filepath);
}catch(e){
console.error(e);
}
}
}
exports.getStampOfNow = function() {
var date = new Date();
var year = date.getFullYear();
var month = date.getMonth() + 1;
var day = date.getDate();
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
return year + '_' + month + '_' + day + '_' + hours + '_' + minutes + '_' + seconds;
}
exports.parseArgs = function( argv ) {
var result = {},
options = {},
key = null;
for (var i = 3, c = argv.length; i < c; i++) {
var arg = argv[i];
if (arg.indexOf('-') === 0) {
key = arg.replace(/^-+/, '');
options[key] = true;
} else {
if (key) {
options[key] = arg;
key = null;
} else {
result.action = arg;
}
}
}
result.options = options;
return result;
}
// 查询包信息
exports.getNPMInfo = function(name,callback){
var reqUrl = 'http://registry.npmjs.org/'+name;
http.get(reqUrl, function(res) {
if (res.statusCode == 200) {
res.on('data', function(data) {
buffers += data;
});
res.on("end", function() {
var data = JSON.parse(buffers.toString());
callback && callback.call(this,data);
});
} else {
console.log("Request failed".red);
}
}).on('error', function(e) {
console.log("Error: " + e.message.red);
});
}