forked from Vincent0700/homebrew-brm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
executable file
·344 lines (318 loc) · 10.2 KB
/
cli.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
/**
* brm (Homebrew Registry Manager)
* @description https://github.com/Vincent0700/homebrew-brm/blob/master/README.md
* @author vincent0700 (https://vincentstudio.info)
* @email wang.yuanqiu007@gmail.com
*/
require('colors');
const fs = require('fs');
const path = require('path');
const shell = require('shelljs');
const dns = require('dns');
const tcpp = require('tcp-ping');
const inquirer = require('inquirer');
const program = require('commander');
const Table = require('cli-table');
/* ---- PUBLIC VARIABLES ---- */
const REG_DOMAIN = /^http[s]?:\/\/(.*?)\//;
const SHELL = process.env.SHELL.match(/[^/]+$/)[0].trim();
const PATH_RCFILE = path.resolve(process.env.HOME, `./.${SHELL}rc`);
const pkg = require('./package.json');
const registries = require('./registries.json');
const MSG_TYPE = {
INFO: Symbol(),
WARN: Symbol(),
ERROR: Symbol()
};
/* ---- CLI ---- */
program.version(pkg.version);
program.description(pkg.description);
program
.command('ls')
.description('List all the registries')
.action(showList);
program
.command('current')
.description('Show current registry and URL')
.action(showCurrent);
program
.command('use <registry>')
.description('Change homebrew registry')
.action(onUse);
program
.command('test [registry]')
.description('Show response time for specific or all registries')
.action(onTest);
(async function() {
_updateEnvironment();
await _checkDependencies();
program.parse(process.argv);
})();
/* ---- ACTION_HANDLERS ---- */
function showList() {
const urls = _getCurrentRegistries();
const obj = ['brew', 'homebrew/core', 'homebrew/cask', 'homebrew/bottles'];
const table = new Table({
colWidths: [10, 18, 18, 18, 18],
colAligns: ['left', 'middle', 'middle', 'middle', 'middle']
});
table.push(['', ...obj].map((s) => s.brightCyan));
for (let name in registries) {
const registry = registries[name];
const arr = [...Array(obj.length)].map(() => '✘'.brightRed);
for (let item in registry) {
const url = registry[item];
const flag = url.trim() === urls[item].trim();
const index = obj.indexOf(item.trim());
if (index >= 0 && index < arr.length) {
arr[index] = flag ? 'Use'.italic.bold.brightGreen : '✔'.brightGreen;
}
}
table.push([name.brightYellow, ...arr]);
}
console.log(table.toString());
}
function showCurrent() {
const table = new Table();
const urls = _getCurrentRegistries();
table.push(['brew'.brightYellow, _getRegistryName(urls['brew']).brightCyan, urls['brew'].trim()]);
table.push(['homebrew/core'.brightYellow, _getRegistryName(urls['homebrew/core']).brightCyan, urls['homebrew/core'].trim()]);
table.push(['homebrew/cask'.brightYellow, _getRegistryName(urls['homebrew/cask']).brightCyan, urls['homebrew/cask'].trim()]);
table.push(['homebrew/bottles'.brightYellow, _getRegistryName(urls['homebrew/bottles']).brightCyan, urls['homebrew/bottles'].trim()]);
console.log(table.toString());
}
function onUse(name) {
if (!Object.keys(registries).includes(name)) {
_log(`Not find registry: ${name.brightCyan}`, MSG_TYPE.WARN);
shell.exit(1);
}
inquirer
.prompt([
{
type: 'checkbox',
message: 'Select registry',
name: 'arr',
choices: [
...Object.keys(registries[name]).map((item) => ({
name: item,
checked: true
}))
]
}
])
.then(({ arr }) => {
arr.forEach((item) => {
_setRegistry(item, registries[name][item]);
});
_log(`Executing ${'brew cleanup'.brightYellow}`);
shell.exec('brew cleanup');
_log(`Executing ${'brew update'.brightYellow}`);
shell.exec('brew update');
_log(`Done.`);
});
}
function onTest(mirror) {
const list = [];
if (mirror) {
if (registries[mirror] && registries[mirror]['brew']) {
const domain = registries[mirror]['brew'].match(REG_DOMAIN)[1];
list.push({ mirror, domain });
}
} else {
for (let mirror in registries) {
if (registries[mirror]['brew']) {
const domain = registries[mirror]['brew'].match(REG_DOMAIN)[1];
list.push({ mirror, domain });
}
}
}
if (list.length > 0) {
const promises = [];
_log(`Testing speed of ${list.map((item) => item.mirror.brightCyan).join(', ')}...`);
list.forEach((item) => {
promises.push(_pingHost(item.domain));
});
Promise.all(promises).then((result) => {
for (let i = 0; i < result.length; ++i) {
list[i].latency = result[i];
}
list.sort((a, b) => a.latency - b.latency);
const MAX_LEN = 30;
for (let i = 0; i < list.length; ++i) {
let str = `${list[i].mirror.brightYellow} `;
str += [...Array(MAX_LEN - list[i].mirror.length)].map(() => '-').join('') + ' ';
str += list[i].latency !== Number.MAX_SAFE_INTEGER ? list[i].latency.toString().brightGreen + ' ms'.bold : 'timeout'.brightRed;
console.log(str);
}
});
}
}
/* ---- PRIVATE_FUNCTIONS ---- */
/**
* @name _log
* @description Print log message
* @param {String} msg Log message
* @param {MSG_TYPE} type Type of log message
*/
function _log(msg, type = MSG_TYPE.INFO) {
let typeStr = '';
if (type === MSG_TYPE.INFO) {
typeStr = '[BRM]'.brightGreen;
} else if (type === MSG_TYPE.WARN) {
typeStr = '[BRM][WARN]'.brightYellow;
} else if (type === MSG_TYPE.ERROR) {
typeStr = '[BRM][ERROR]'.brightRed;
}
console.log(`${typeStr} ${msg}`);
}
/**
* @name _checkDependencies
* @description Check & install dependencies: homenbrew, git.
*/
async function _checkDependencies() {
const dependencies = [
{
cmd: 'brew',
name: 'Homebrew',
script: 'ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"'
},
{
cmd: 'git',
name: 'Git',
script: 'brew install git'
}
];
let promises = [];
dependencies.forEach(({ cmd, name, script }) => {
if (!shell.which(cmd)) {
_log(`Missing dependency - ${name.brightCyan}`, MSG_TYPE.WARN);
promises.push(
new Promise((resolve) => {
inquirer
.prompt({
type: 'confirm',
name: 'flag',
message: `Press <Enter> to install ${name.brightCyan}?`,
default: true
})
.then(({ flag }) => {
if (flag) {
shell.exec(script);
shell.exit(1);
}
resolve();
});
})
);
}
});
return Promise.all(promises);
}
/**
* @name _getRegistryName
* @description Get registry name by url
* @param {String} url Registry url
* @returns {String}
*/
function _getRegistryName(url) {
for (let name in registries) {
const registry = registries[name];
for (let item in registry) {
if (registry[item].trim() === url.trim()) {
return name;
}
}
}
return '';
}
/**
* @name _getCurrentRegistries
* @description Get urls of current registries
* @returns {Object}
*/
function _getCurrentRegistries() {
const brewUrl = shell.exec('git -C $(brew --repo) remote get-url origin', { silent: true }).stdout || '';
const homebrewCoreUrl = shell.exec('git -C $(brew --repo homebrew/core) remote get-url origin', { silent: true }).stdout || '';
const homebrewCaskUrl = shell.exec('git -C $(brew --repo homebrew/cask) remote get-url origin', { silent: true }).stdout || '';
const homebrewBottlesUrl = shell.env.HOMEBREW_BOTTLE_DOMAIN || '';
return {
brew: brewUrl,
'homebrew/core': homebrewCoreUrl,
'homebrew/cask': homebrewCaskUrl,
'homebrew/bottles': homebrewBottlesUrl
};
}
/**
* @name _setRegistry
* @description Set Homebrew registries
* @param {String} name Registry name
* @param {String} url Registry url
*/
function _setRegistry(name, url) {
const cb = (err) => {
if (err) _log(err, MSG_TYPE.WARN);
else _log(`Set ${name.brightCyan} registry to ${url.magenta}`);
};
if (name === 'brew') {
cb(shell.exec(`git -C "$(brew --repo)" remote set-url origin ${url}`, { silent: true }).stderr);
} else if (name === 'homebrew/core') {
cb(shell.exec(`git -C "$(brew --repo homebrew/core)" remote set-url origin ${url}`, { silent: true }).stderr);
} else if (name === 'homebrew/cask') {
cb(shell.exec(`git -C "$(brew --repo homebrew/cask)" remote set-url origin ${url}`, { silent: true }).stderr);
} else if (name === 'homebrew/bottles') {
try {
let content = fs.readFileSync(PATH_RCFILE, { encoding: 'utf8' });
let arr = content.split('\n');
let deleteIndicies = [];
for (let i = 0; i < arr.length; ++i) {
if (arr[i].match(/export[\s]+HOMEBREW_BOTTLE_DOMAIN=[\S]*/)) deleteIndicies.push(i);
}
deleteIndicies.reverse().forEach((index) => arr.splice(index, 1));
content = arr.join('\n');
content = content.trimRight('\n');
content += `\n\nexport HOMEBREW_BOTTLE_DOMAIN=${url}`;
fs.writeFileSync(PATH_RCFILE, content);
shell.env.HOMEBREW_BOTTLE_DOMAIN = url;
cb(false);
} catch (err) {
cb(err);
}
}
}
/**
* @name _pingHost
* @description Get network latency
* @param {Object} session Ping session
* @param {String} domain Domain to test
* @returns {Promise<Number>} Latency(ms), Number.MAX_SAFE_INTEGER means timeout
*/
async function _pingHost(domain) {
const TIMEOUT = Number.MAX_SAFE_INTEGER;
return new Promise((resolve) => {
dns.lookup(domain, function(err, address) {
if (err) resolve(TIMEOUT);
tcpp.ping({ address, port: 443, timeout: 3000, attempts: 3 }, (error, data) => {
if (error) resolve(TIMEOUT);
if (data && data.results && Array.isArray(data.results) && data.results.length > 0) {
const latency = data.avg;
if (isNaN(latency)) resolve(TIMEOUT);
resolve(parseInt(latency));
} else {
resolve(TIMEOUT);
}
});
});
});
}
/**
* @name _updateEnvironment
* @description Update environment from rcfile
*/
async function _updateEnvironment() {
const content = fs.readFileSync(PATH_RCFILE, { encoding: 'utf8' });
const match = content.match(/export[\s]+HOMEBREW_BOTTLE_DOMAIN=([\S]*)/);
if (match && match.length > 1) {
const HOMEBREW_BOTTLE_DOMAIN = match[1];
shell.env.HOMEBREW_BOTTLE_DOMAIN = HOMEBREW_BOTTLE_DOMAIN;
}
}