-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
executable file
·571 lines (511 loc) · 18.6 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
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
#!/usr/bin/env node
const path = require('path');
const fs = require('fs');
const program = require('commander');
const npm = require('npm');
const ini = require('ini');
const extend = require('extend');
const open = require('open');
const async = require('async');
const request = require('request');
const only = require('only');
const humps = require('humps');
const registries = require('./registries.json');
const PKG = require('./package.json');
const NRMRC = path.join(process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'], '.nrmrc');
const NPMRC = path.join(process.env.HOME, '.npmrc');
const FIELD_AUTH = '_auth';
const FIELD_ALWAYS_AUTH = 'always-auth';
const FIELD_IS_CURRENT = 'is-current';
const FIELD_REPOSITORY = 'repository';
const FIELD_REGISTRY = 'registry';
const FIELD_HOME = 'home';
const FIELD_EMAIL = 'email';
const FIELD_SHOW_URL = "show-url"
const REGISTRY_ATTRS = [FIELD_REGISTRY, FIELD_HOME, FIELD_AUTH, FIELD_ALWAYS_AUTH];
const IGNORED_ATTRS = [FIELD_IS_CURRENT, FIELD_REPOSITORY];
program
.version(PKG.version);
program
.command('ls')
.description('List all the registries')
.action(onList);
program
.command('current')
.option('-u, --show-url', 'Show the registry URL instead of the name')
.description('Show current registry name or URL')
.action(showCurrent);
program
.command('use <registry>')
.description('Change registry to registry')
.action(onUse);
program
.command('add <registry> <url> [home]')
.description('Add one custom registry')
.action(onAdd);
program
.command('login <registryName> [value]')
.option('-a, --always-auth', 'Set is always auth')
.option('-u, --username <username>', 'Your user name for this registry')
.option('-p, --password <password>', 'Your password for this registry')
.option('-e, --email <email>', 'Your email for this registry')
.description('Set authorize information for a custom registry with a base64 encoded string or username and pasword')
.action(onLogin);
program
.command('set-hosted-repo <registry> <value>')
.description('Set hosted npm repository for a custom registry to publish packages')
.action(onSetRepository);
program
.command('set-scope <scopeName> <value>')
.description('Associating a scope with a registry')
.action(onSetScope);
program
.command('del-scope <scopeName>')
.description('remove a scope')
.action(onDelScope);
program
.command('set <registryName>')
.option('-a,--attr <attr>', 'set custorm registry attribute')
.option('-v,--value <value>', 'set custorm registry value')
.description('Set custom registry attribute')
.action(onSet);
program
.command('rename <registryName> <newName>')
.description('Set custom registry name')
.action(onRename);
program
.command('del <registry>')
.description('Delete one custom registry')
.action(onDel);
program
.command('home <registry> [browser]')
.description('Open the homepage of registry with optional browser')
.action(onHome);
program
.command('publish [<tarball>|<folder>]')
.option('-t, --tag [tag]', 'Add tag')
.option('-a, --access <public|restricted>', 'Set access')
.option('-o, --otp [otpcode]', 'Set otpcode')
.option('-dr, --dry-run', 'Set is dry run')
.description('Publish package to current registry if current registry is a custom registry.\n if you\'re not using custom registry, this command will run npm publish directly')
.action(onPublish);
program
.command('test [registry]')
.description('Show response time for specific or all registries')
.action(onTest);
program
.command('help', { isDefault: true })
.description('Print this help \n if you want to clear the NRM configuration when uninstall you can execute "npm uninstall nrm -g -C or npm uninstall nrm -g --clean"')
.action(function () {
program.outputHelp();
});
program
.parse(process.argv);
if (process.argv.length === 2) {
program.outputHelp();
}
/*//////////////// cmd methods /////////////////*/
function onList () {
getCurrentRegistry(function (cur) {
var info = [''];
var allRegistries = getAllRegistry();
const keys = Object.keys(allRegistries);
const len = Math.max(...keys.map(key => key.length)) + 3;
Object.keys(allRegistries).forEach(function (key) {
var item = allRegistries[key];
var prefix = equalsIgnoreCase(item.registry, cur) && item[FIELD_IS_CURRENT] ? '* ' : ' ';
info.push(prefix + key + line(key, len) + item.registry);
});
info.push('');
printMsg(info);
});
}
function showCurrent (cmd) {
getCurrentRegistry(function (cur) {
var allRegistries = getAllRegistry();
Object.keys(allRegistries).forEach(function (key) {
var item = allRegistries[key];
if (item[FIELD_IS_CURRENT] && equalsIgnoreCase(item.registry, cur)) {
const showUrl = cmd[humps.camelize(FIELD_SHOW_URL, { separator: '-' })];
printMsg([showUrl ? item.registry : key]);
return;
}
});
});
}
function config (attrArray, registry, index = 0) {
return new Promise((resolve, reject) => {
const attr = attrArray[index];
const command = registry.hasOwnProperty(attr) ? ['set', attr, String(registry[attr])] : ['delete', attr];
npm.load(function (err) {
if (err) return reject(err);
npm.commands.config(command, function (err, data) {
return err ? reject(err) : resolve(index + 1);
});
});
}).then(next => {
if (next < attrArray.length) {
return config(attrArray, registry, next);
} else {
return Promise.resolve();
}
});
}
function onUse (name) {
var allRegistries = getAllRegistry();
if (allRegistries.hasOwnProperty(name)) {
getCurrentRegistry(function (cur) {
let currentRegistry, item;
for (let key of Object.keys(allRegistries)) {
item = allRegistries[key];
if (item[FIELD_IS_CURRENT] && equalsIgnoreCase(item.registry, cur)) {
currentRegistry = item;
break;
}
}
var registry = allRegistries[name];
let attrs = [].concat(REGISTRY_ATTRS).concat();
for (let attr in Object.assign({}, currentRegistry, registry)) {
if (!REGISTRY_ATTRS.includes(attr) && !IGNORED_ATTRS.includes(attr)) {
attrs.push(attr);
}
}
config(attrs, registry).then(() => {
console.log(' ');
const newR = npm.config.get(FIELD_REGISTRY);
var customRegistries = getCustomRegistry();
Object.keys(customRegistries).forEach(key => {
delete customRegistries[key][FIELD_IS_CURRENT];
});
if (customRegistries.hasOwnProperty(name) && (name in registries || customRegistries[name].registry === registry.registry)) {
registry[FIELD_IS_CURRENT] = true;
customRegistries[name] = registry;
}
setCustomRegistry(customRegistries);
printMsg(['', ' Registry has been set to: ' + newR, '']);
}).catch(err => {
exit(err);
});
});
} else {
printMsg(['', ' Not find registry: ' + name, '']);
}
}
function onDel (name) {
var customRegistries = getCustomRegistry();
if (!customRegistries.hasOwnProperty(name)) return;
getCurrentRegistry(function (cur) {
if (equalsIgnoreCase(customRegistries[name].registry, cur)) {
onUse('npm');
}
delete customRegistries[name];
setCustomRegistry(customRegistries, function (err) {
if (err) return exit(err);
printMsg(['', ' delete registry ' + name + ' success', '']);
});
});
}
function onAdd (name, url, home) {
var customRegistries = getCustomRegistry();
if (customRegistries.hasOwnProperty(name)) return;
var config = customRegistries[name] = {};
if (url[url.length - 1] !== '/') url += '/'; // ensure url end with /
config.registry = url;
if (home) {
config.home = home;
}
setCustomRegistry(customRegistries, function (err) {
if (err) return exit(err);
printMsg(['', ' add registry ' + name + ' success', '']);
});
}
function onLogin (registryName, value, cmd) {
const customRegistries = getCustomRegistry();
if (!customRegistries.hasOwnProperty(registryName)) return;
const registry = customRegistries[registryName];
let attrs = [FIELD_AUTH];
if (value) {
registry[FIELD_AUTH] = value;
} else if (cmd.username && cmd.password) {
registry[FIELD_AUTH] = Buffer.from(`${cmd.username}:${cmd.password}`).toString('base64');
} else {
return exit(new Error('your username & password or auth value is required'));
}
if (cmd[humps.camelize(FIELD_ALWAYS_AUTH, { separator: '-' })]) {
registry[FIELD_ALWAYS_AUTH] = true;
attrs.push(FIELD_ALWAYS_AUTH);
}
if (cmd.email) {
registry.email = cmd.email;
attrs.push(FIELD_EMAIL);
}
new Promise(resolve => {
registry[FIELD_IS_CURRENT] ? resolve(config(attrs, registry)) : resolve();
}).then(() => {
customRegistries[registryName] = registry;
setCustomRegistry(customRegistries, function (err) {
if (err) return exit(err);
printMsg(['', ' set authorize info to registry ' + registryName + ' success', '']);
});
}).catch(exit);
}
function onSetRepository (registry, value) {
var customRegistries = getCustomRegistry();
if (!customRegistries.hasOwnProperty(registry)) return;
var config = customRegistries[registry];
config[FIELD_REPOSITORY] = value;
new Promise(resolve => {
config[FIELD_IS_CURRENT] ? resolve(config([FIELD_REPOSITORY], config)) : resolve();
}).then(() => {
setCustomRegistry(customRegistries, function (err) {
if (err) return exit(err);
printMsg(['', ` set ${FIELD_REPOSITORY} to registry [${registry}] success`, '']);
});
}).catch(exit);
}
function onSetScope (scopeName, value) {
const npmrc = getNPMInfo();
const scopeRegistryKey = `${scopeName}:registry`
config([scopeRegistryKey], { [scopeRegistryKey]: value }).then(function () {
printMsg(['', ` set [ ${scopeRegistryKey}=${value} ] success`, '']);
}).catch(exit)
}
function onDelScope (scopeName) {
const npmrc = getNPMInfo();
const scopeRegistryKey = `${scopeName}:registry`
npmrc[scopeRegistryKey] && config([scopeRegistryKey], {}).then(function () {
printMsg(['', ` delete [ ${scopeRegistryKey} ] success`, '']);
}).catch(exit)
}
function onSet (registryName, cmd) {
if (!registryName || !cmd.attr || cmd.value === undefined) return;
if (IGNORED_ATTRS.includes(cmd.attr)) return;
var customRegistries = getCustomRegistry();
if (!customRegistries.hasOwnProperty(registryName)) return;
const registry = customRegistries[registryName];
registry[cmd.attr] = cmd.value;
new Promise(resolve => {
registry[FIELD_IS_CURRENT] ? resolve(config([cmd.attr], registry)) : resolve();
}).then(() => {
customRegistries[registryName] = registry;
setCustomRegistry(customRegistries, function (err) {
if (err) return exit(err);
printMsg(['', ` set registry ${registryName} [${cmd.attr}=${cmd.value}] success`, '']);
});
}).catch(exit);
}
function onRename (registryName, newName) {
if (!newName || registryName === newName) return;
let customRegistries = getCustomRegistry();
if (!customRegistries.hasOwnProperty(registryName)) {
console.log('Only custom registries can be modified');
return;
}
if (registries[newName] || customRegistries[newName]) {
console.log('The registry contains this new name');
return;
}
customRegistries[newName] = JSON.parse(JSON.stringify(customRegistries[registryName]));
delete customRegistries[registryName];
setCustomRegistry(customRegistries, function (err) {
if (err) return exit(err);
printMsg(['', ` rename ${registryName} to ${newName} success`, '']);
});
}
function onHome (name, browser) {
var allRegistries = getAllRegistry();
var home = allRegistries[name] && allRegistries[name].home;
if (home) {
var args = [home];
if (browser) args.push(browser);
open.apply(null, args);
}
}
function onPublish (tarballOrFolder, cmd) {
getCurrentRegistry(registry => {
const customRegistries = getCustomRegistry();
let currentRegistry;
// find current using custom registry
Object.keys(customRegistries).forEach(function (key) {
const item = customRegistries[key];
if (item[FIELD_IS_CURRENT] && equalsIgnoreCase(item.registry, registry)) {
currentRegistry = item;
currentRegistry.name = key;
}
});
const attrs = [FIELD_REGISTRY];
let command = '> npm publish';
const optionData = {};
cmd.options.forEach(option => {
const opt = option.long.substring(2);
const optionValue = cmd[opt];
if (optionValue) {
optionData[opt] = cmd[opt];
attrs.push(opt);
}
});
new Promise((resolve, reject) => {
if (currentRegistry) {
if (currentRegistry[FIELD_REPOSITORY]) {
printMsg(['',
' current registry is a custom registry, publish to custom repository.',
''
]);
optionData.registry = currentRegistry[FIELD_REPOSITORY];
Object.keys(optionData).forEach((key) => {
command += ` --${key} ${optionData[key]}`;
});
printMsg([command]);
resolve(config(attrs, optionData));
} else {
reject(new Error(` current using registry [${currentRegistry.name}] has no ${FIELD_REPOSITORY} field, can't execute publish.`));
}
} else {
printMsg(['',
' current using registry is not a custom registry, will publish to npm official repository.',
''
]);
optionData.registry = registries.npm.registry;
// find current using registry
Object.keys(registries).forEach(function (key) {
const item = registries[key];
if (item.registry === registry) {
currentRegistry = item;
currentRegistry.name = key;
}
});
printMsg([command]);
resolve(config(attrs, optionData));
}
}).then(() => {
const callback = (err) => {
config(attrs, currentRegistry).then(() => {
err && exit(err);
printMsg(['', ` published to registry ${currentRegistry[FIELD_REPOSITORY]} successfully.`, '']);
}).catch(exit);
};
try {
tarballOrFolder ? npm.publish(tarballOrFolder, callback) : npm.publish(callback);
} catch (e) {
callback(err);
}
}).catch(err => {
printErr(err);
});
});
}
function onTest (registry) {
var allRegistries = getAllRegistry();
var toTest;
if (registry) {
if (!allRegistries.hasOwnProperty(registry)) {
return;
}
toTest = only(allRegistries, registry);
} else {
toTest = allRegistries;
}
async.map(Object.keys(toTest), function (name, cbk) {
var registry = toTest[name];
var start = +new Date();
request(registry.registry + 'pedding', function (error) {
cbk(null, {
name: name,
registry: registry.registry,
time: (+new Date() - start),
error: error ? true : false
});
});
}, function (err, results) {
getCurrentRegistry(function (cur) {
var msg = [''];
results.forEach(function (result) {
var prefix = result.registry === cur ? '* ' : ' ';
var suffix = result.error ? 'Fetch Error' : result.time + 'ms';
msg.push(prefix + result.name + line(result.name, 8) + suffix);
});
msg.push('');
printMsg(msg);
});
});
}
/*//////////////// helper methods /////////////////*/
/*
* get current registry
*/
function getCurrentRegistry (cbk) {
npm.load(function (err, conf) {
if (err) return exit(err);
cbk(npm.config.get(FIELD_REGISTRY));
});
}
function getCustomRegistry () {
return getINIInfo(NRMRC)
}
function setCustomRegistry (config, cbk) {
for (let name in config) {
if (name in registries) {
delete config[name].registry;
delete config[name].home;
}
}
fs.writeFile(NRMRC, ini.stringify(config), cbk)
}
function getAllRegistry () {
const custom = getCustomRegistry();
const all = extend({}, registries, custom);
for (let name in registries) {
if (name in custom) {
all[name] = extend({}, custom[name], registries[name]);
}
}
return all;
}
function printErr (err) {
console.error('an error occured: ' + err);
}
function printMsg (infos) {
infos.forEach(function (info) {
console.log(info);
});
}
function getNPMInfo () {
return getINIInfo(NPMRC)
}
function getINIInfo (path) {
return fs.existsSync(path) ? ini.parse(fs.readFileSync(path, 'utf-8')) : {};
}
/*
* print message & exit
*/
function exit (err) {
printErr(err);
process.exit(1);
}
function line (str, len) {
var line = new Array(Math.max(1, len - str.length)).join('-');
return ' ' + line + ' ';
}
/**
* compare ignore case
*
* @param {string} str1
* @param {string} str2
*/
function equalsIgnoreCase (str1, str2) {
if (str1 && str2) {
return str1.toLowerCase() === str2.toLowerCase();
} else {
return !str1 && !str2;
}
}
function cleanRegistry () {
setCustomRegistry('', function (err) {
if (err) exit(err);
onUse('npm')
})
}
module.exports = {
cleanRegistry,
errExit: exit
}