main.js 2.5 KB
Newer Older
DCloud_JSON's avatar
DCloud_JSON 已提交
1 2 3
//脚本文件目录 __dirname
//运行脚本的目录,即:项目的目录 process.cwd()

4
//配置文件
DCloud_JSON's avatar
DCloud_JSON 已提交
5
const fs = require('fs'),
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 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
	Hjson = require('hjson'),
	config = Hjson.rt.parse(fs.readFileSync(__dirname + '/config.js', 'utf-8'))
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) {
				return console.log(err);
			}
			//改写
			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)
	console.log(paths);
	paths.forEach(path => {
		console.log(__dirname + '/copy' + path);
		let oldFile = fs.readFileSync(__dirname + '/copy' + path)
		console.log(process.cwd() + path);
		fs.writeFile(process.cwd() + path, oldFile, function(err) {
			if (err) {
				console.log(err);
				return
			}
			// fs.unlinkSync(__dirname + path+'.lock')
		})
	})
}





DCloud_JSON's avatar
DCloud_JSON 已提交
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95

//创建目录并写入文件
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) {
96 97 98 99 100 101 102 103 104
		if (typeof(main[key]) != 'object') {
			minor[key] = main[key];
		} else {
			if(minor&&main){
				console.log('[', minor[key], main[key], ']');
				mergeJSON(minor[key], main[key]);
			}else{
				console.log({minor,main});
			}
DCloud_JSON's avatar
DCloud_JSON 已提交
105
		}
106 107
	}
}