main.js 2.4 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1 2 3 4 5
//脚本文件目录 __dirname
//运行脚本的目录,即:项目的目录 process.cwd()
//配置文件
const fs = require('fs'),
	Hjson = require('hjson'),
6 7 8
	config = Hjson.rt.parse(fs.readFileSync(__dirname+'/config.js', 'utf-8'))
	
	
DCloud_JSON's avatar
DCloud_JSON 已提交
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
const change_after = require('./change_after')
if(process.argv[2] == 'change'){
	change(config,()=>{
		console.log('脚本change已经执行成功');
		change_after()
	})
}else{
	recovery(config)
}

function change(config,callback){
	const total = Object.keys(config).length
	let index = 0;
	for (let fileName in config) {
		let path = process.cwd() + fileName
		let copyPath = __dirname + '/copy' + fileName
		let fileText = fs.readFileSync(path, 'utf-8')
		//保持原文件名先备份一份到/uni_modules_tools/copy目录下,然后再覆盖
		writeFileRecursive(copyPath, fileText, function(err) { //创建目录并写入文件
			if (err) {
29
				return console.log({err});
DCloud_JSON's avatar
DCloud_JSON 已提交
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
			}
			//改写
			let HfileObj = Hjson.rt.parse(fileText)
			//递归合并,为了保留注释内容
			mergeJSON(HfileObj,config[fileName])
			
			fs.writeFile(path, Hjson.rt.stringify(HfileObj, {
				quotes: 'all',
				separator: true,
				multiline: "off",
				bracesSameLine: true
			}), function(err) {
				if (err) {
					return console.log(err);
				}
				index++
				if(index == total){
					callback()
				}
			})
		})
	}
}




function recovery(){
	let paths = Object.keys(config)
	paths.forEach(path=>{
		console.log(__dirname + '/copy' + path);
		let oldFile = fs.readFileSync(__dirname + '/copy' + path)
		fs.writeFile(process.cwd() + path, oldFile, function(err) {
			if (err) {
				console.log(err);
				return
			}
			// fs.unlinkSync(__dirname + path+'.lock')
		})
	})
}






//创建目录并写入文件
function writeFileRecursive(path, buffer, callback) {
	let lastPath = path.substring(0, path.lastIndexOf("/"));
	fs.mkdir(lastPath, {
		recursive: true
	}, (err) => {
		if (err) return callback(err);
		fs.writeFile(path, buffer, function(err) {
			if (err) return callback(err);
			return callback(null);
		});
	});
}

//递归合并,为了保留注释内容
function mergeJSON(minor, main) {
	for (var key in main) {
		if (typeof(main[key]) != 'object' ) {
95
			console.log({key,main});
DCloud_JSON's avatar
DCloud_JSON 已提交
96 97
			minor[key] = main[key];
		}else{
98 99 100 101 102 103
			console.log(9999,{minor,key,main});
			if(minor){
				mergeJSON(minor[key], main[key]);
			}else{
				console.log(minor,'不存在:'+key);
			}
DCloud_JSON's avatar
DCloud_JSON 已提交
104 105 106
		}
	}
}