-
-
Notifications
You must be signed in to change notification settings - Fork 376
/
util.js
82 lines (70 loc) 路 2.07 KB
/
util.js
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
const { blue, yellow, red } = require('kleur');
const { normalize, resolve } = require('path');
const { statSync, existsSync } = require('fs');
const symbols = require('./symbols');
const which = require('which');
const net = require('net');
exports.isDir = function (str) {
return existsSync(str) && statSync(str).isDirectory();
};
exports.dirExists = function (workingDir, destDir) {
if (workingDir && destDir) {
const target = resolve(workingDir, destDir);
return exports.isDir(target);
}
return false;
};
exports.hasCommand = function (str) {
return !!which.sync(str, { nothrow: true });
};
exports.trim = function (str) {
return str.trim().replace(/^\t+/gm, '');
};
exports.info = function (text, code) {
process.stderr.write(symbols.info + blue(' INFO ') + text + '\n');
code && process.exit(code);
};
exports.warn = function (text, code) {
process.stdout.write(symbols.warning + yellow(' WARN ') + text + '\n');
code && process.exit(code);
};
exports.error = function (text, code = 1) {
process.stderr.write(symbols.error + red(' ERROR ') + text + '\n');
code && process.exit(code);
};
exports.normalizePath = function (str) {
return normalize(str).replace(/\\/g, '/');
};
exports.normalizeTemplatesResponse = function (repos = []) {
return repos.map(repo => ({
title: repo.name || '',
value: repo.full_name || '',
description: repo.description || '',
}));
};
exports.toBool = function (val) {
return val === void 0 || (val === 'false' ? false : val);
};
exports.esmImport = require('esm')(module);
/**
* Taken from: https://github.com/preactjs/wmr/blob/3401a9bfa6491d25108ad68688c067a7e17d0de5/packages/wmr/src/lib/net-utils.js#L4-Ll4
* Check if a port is free
* @param {number} port
* @returns {Promise<boolean>}
*/
exports.isPortFree = async function (port) {
try {
await new Promise((resolve, reject) => {
const server = net.createServer();
server.unref();
server.on('error', reject);
server.listen({ port }, () => {
server.close(resolve);
});
});
return true;
} catch (err) {
if (err.code !== 'EADDRINUSE') throw err;
return false;
}
};