forked from cnpm/cnpm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
origin_npm.js
123 lines (107 loc) · 2.57 KB
/
origin_npm.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
'use strict';
const debug = require('debug')('cnpm:origin');
const match = require('auto-correct');
const spawn = require('cross-spawn');
const fs = require('fs');
const path = require('path');
const config = require('./config');
const parseArgv = require('./parse_argv');
const program = parseArgv();
const rawArgs = program.rawArgs.slice(2);
const args = [];
let hasCNPM = false;
let isInstall = false;
let installer = 'npminstall';
for (let i = 0; i < rawArgs.length; i++) {
let arg = rawArgs[i];
if (arg[0] !== '-') {
arg = correct(arg);
if (arg === 'cnpm') {
hasCNPM = true;
}
}
if (i === 0 && (arg === 'i' || arg === 'install')) {
isInstall = true;
continue;
}
// support `$ cnpm i --by=npm`
if (arg.indexOf('--by=') === 0) {
installer = arg.split('=', 2)[1];
continue;
}
args.push(arg);
}
var CWD = process.cwd();
if (program.userconfig && !fs.existsSync(program.userconfig)) {
// make sure userconfig exists
// or it will throw: npm ERR! Error: default value must be string or number
fs.writeFileSync(program.userconfig, 'email =\n');
}
args.unshift('--registry=' + program.registry);
if (program.disturl) {
args.unshift('--disturl=' + program.disturl);
}
if (program.userconfig) {
args.unshift('--userconfig=' + program.userconfig);
}
if (program.proxy) {
args.unshift('--proxy=' + program.proxy);
}
var npmBin;
if (isInstall) {
// if local npm not exists, use npm. happen on `$ cnpm install cnpm`
if (hasCNPM) {
npmBin = path.join(path.dirname(process.execPath), 'npm');
args.unshift('install');
} else {
npmBin = path.join(__dirname, 'node_modules', '.bin', installer);
if (installer === 'npminstall') {
args.unshift('--china');
} else {
// other installer, like npm
args.unshift('install');
}
// maybe outside installer, just use installer as binary name
if (!fs.existsSync(npmBin)) {
npmBin = installer;
}
}
} else {
npmBin = path.join(__dirname, 'node_modules', '.bin', 'npm');
}
debug('%s %s', npmBin, args.join(' '));
const env = {};
for (const k in process.env) {
env[k] = process.env[k];
}
const npm = spawn(npmBin, args, {
env: env,
cwd: CWD,
stdio: [
process.stdin,
process.stdout,
process.stderr,
]
});
npm.on('exit', (code, signal) => {
process.exit(code);
});
/**
* correct command
*/
function correct(command) {
const cmds = [
'install',
'publish',
'adduser',
'author',
'config',
'unpublish',
];
for (const cmd of cmds) {
if (match(command, cmd)) {
return cmd;
}
}
return command;
}