summary refs log tree commit diff
path: root/scripts/utils.js
blob: b679392b95882f79f40f60913811d433e6106ab1 (plain) (blame)
1
2
3
4
5
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
78
79
80
81
82
83
84
85
86
87
const path = require("path");
const fs = require("fs");
const { env } = require("process");
const { execSync } = require("child_process");
const { argv, stdout, exit } = require("process");

const projectRoot = path.resolve(path.join(__dirname, ".."));

function copyRecursiveSync(src, dest) {
	//if (verbose) console.log(`cpsync: ${src} -> ${dest}`);
	let exists = fs.existsSync(src);
	if (!exists) {
		console.log(src + " doesn't exist, not copying!");
		return;
	}
	let stats = exists && fs.statSync(src);
	let isDirectory = exists && stats.isDirectory();
	if (isDirectory) {
		fs.mkdirSync(dest, { recursive: true });
		fs.readdirSync(src).forEach(function (childItemName) {
			copyRecursiveSync(path.join(src, childItemName), path.join(dest, childItemName));
		});
	} else {
		fs.copyFileSync(src, dest);
	}
}

function execIn(cmd, workdir, opts) {
	try {
		return execSync(cmd, {
			cwd: workdir,
			shell: true,
			env: process.env,
			encoding: "utf-8",
			...opts
		});
	} catch (error) {
		return error.stdout;
	}
}

function getLines(output) {
	return output.split("\n").length;
}

function getDirs(dir) {
	return fs.readdirSync(dir).filter((x) => {
		try {
			fs.readdirSync(dir.join(dir, x));
			return true;
		} catch (e) {
			return false;
		}
	});
}

function walk(dir) {
	let results = [];
	let list = fs.readdirSync(dir);
	list.forEach(function (file) {
		file = dir + "/" + file;
		let stat = fs.statSync(file);
		if (stat && stat.isDirectory()) {
			/* Recurse into a subdirectory */
			results = results.concat(walk(file));
		} else {
			results.push(file);
		}
	});
	return results;
}

function sanitizeVarName(str) {
	return str.replace("-", "_").replace(/[^\w\s]/gi, "");
}

module.exports = {
	//consts
	projectRoot,
	//functions
	copyRecursiveSync,
	execIn,
	getLines,
	getDirs,
	walk,
	sanitizeVarName
};