Skip to content

Commit

Permalink
Add more options
Browse files Browse the repository at this point in the history
  • Loading branch information
gucong3000 committed Sep 7, 2018
1 parent 026deea commit 476c617
Show file tree
Hide file tree
Showing 13 changed files with 574 additions and 275 deletions.
4 changes: 2 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
language: node_js
dist: trusty
node_js:
- stable
- 6
- "stable"
- "--lts"

install:
- npm install --ignore-scripts
Expand Down
24 changes: 23 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,32 @@ mirror-config-china

```bash
npm i -g mirror-config-china --registry=https://registry.npm.taobao.org
# 检查是否安装成功
# 查看npm配置
npm config list
# 查看环境变量
source ~/.bashrc && env
```

## 参数

### `--registry=https://registry.npm.taobao.org`
registry.npmjs.com 镜像地址

### `--bin-mirrors-prefix=https://npm.taobao.org/mirrors`
npm.taobao.org/mirrors 镜像地址,会覆盖下文中的`{mirrors}`

### `--nodejs-org-mirror={mirrors}/node` (别名: `--disturl`)
nodejs.org/dist 镜像地址

### `--iojs-org-mirror={mirrors}/iojs`
iojs.org/dist 镜像地址

### `--nvmw-npm-mirror={mirrors}/npm`
github.com/npm/npm/releases 镜像地址

### 其他
其他参数将被写入`.npmrc`文件中

## 安装成功后,针对以下组件的镜像地址,将被写入npm用户配置文件(~/.npmrc)中

- [ChromeDriver](https://www.npmjs.com/package/chromedriver)
Expand Down
14 changes: 10 additions & 4 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
'use strict';
const config = require('./lib/config')(process.argv);
Object.keys(config).forEach(key => {
process.env['npm_config_' + key] = config[key];
const config = require('./lib/config')(process.argv.slice(2));

Object.keys(config.npmrc).forEach(key => {
config.env['npm_config_' + key.replace(/-/g, '_')] = config.npmrc[key];
});
console.log(process.env);

Object.assign(process.env, config.env, process.env);

if (process.mainModule === module) {
console.log(process.env);
}
6 changes: 2 additions & 4 deletions lib/cli.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
#!/usr/bin/env node
'use strict';
const npmrc = require('./npmrc');
const env = require('./env');
const update = require('./update');
const path = require('path');

npmrc(process.argv, path.join(process.cwd(), '.npmrc')).catch(console.error);
env(process.argv).catch(console.error);
update(process.argv.slice(2), path.resolve('.npmrc'));
157 changes: 117 additions & 40 deletions lib/config.js
Original file line number Diff line number Diff line change
@@ -1,37 +1,4 @@
'use strict';
const npmrc = {
registry: 'https://registry.npm.taobao.org',
disturl: 'https://npm.taobao.org/dist',
'chromedriver-cdnurl': '{mirrors}/chromedriver',
'couchbase-binary-host-mirror': '{mirrors}/couchbase/v{version}',
'debug-binary-host-mirror': '{mirrors}/node-inspector',
'electron-mirror': '{mirrors}/electron/',
'flow-bin-binary-host-mirror': '{mirrors}/flow/v',
'fse-binary-host-mirror': '{mirrors}/fsevents',
'fuse-bindings-binary-host-mirror': '{mirrors}/fuse-bindings/v{version}',
'git4win-mirror': '{mirrors}/git-for-windows',
'gl-binary-host-mirror': '{mirrors}/gl/v{version}',
'grpc-node-binary-host-mirror': '{mirrors}',
'hackrf-binary-host-mirror': '{mirrors}/hackrf/v{version}',
'leveldown-binary-host-mirror': '{mirrors}/leveldown/v{version}',
'leveldown-hyper-binary-host-mirror': '{mirrors}/leveldown-hyper/v{version}',
'mknod-binary-host-mirror': '{mirrors}/mknod/v{version}',
'node-sqlite3-binary-host-mirror': '{mirrors}',
'node-tk5-binary-host-mirror': '{mirrors}/node-tk5/v{version}',
'nodegit-binary-host-mirror': '{mirrors}/nodegit/v{version}/',
'operadriver-cdnurl': '{mirrors}/operadriver',
'phantomjs-cdnurl': '{mirrors}/phantomjs',
'profiler-binary-host-mirror': '{mirrors}/node-inspector/',
'puppeteer-download-host': '{mirrors}',
'python-mirror': '{mirrors}/python',
'rabin-binary-host-mirror': '{mirrors}/rabin/v{version}',
'sass-binary-site': '{mirrors}/node-sass',
'sodium-prebuilt-binary-host-mirror': '{mirrors}/sodium-prebuilt/v{version}',
'sqlite3-binary-site': '{mirrors}/sqlite3',
'utf-8-validate-binary-host-mirror': '{mirrors}/utf-8-validate/v{version}',
'utp-native-binary-host-mirror': '{mirrors}/utp-native/v{version}',
'zmq-prebuilt-binary-host-mirror': '{mirrors}/zmq-prebuilt/v{version}'
};
/*
const prebuild = require('binary-mirror-config').china;
const got = require('got');
Expand Down Expand Up @@ -67,17 +34,127 @@ Promise.all(
});
*/
function getConf (argv) {
let binMirrorPrefix = 'https://npm.taobao.org/mirrors';
const isWin = process.platform === 'win32';
const npmrc = {
registry: 'https://registry.npm.taobao.org',
disturl: '{mirrors}/node',
'chromedriver-cdnurl': '{mirrors}/chromedriver',
'couchbase-binary-host-mirror': '{mirrors}/couchbase/v{version}',
'debug-binary-host-mirror': '{mirrors}/node-inspector',
'electron-mirror': '{mirrors}/electron/',
'flow-bin-binary-host-mirror': '{mirrors}/flow/v',
'fse-binary-host-mirror': '{mirrors}/fsevents',
'fuse-bindings-binary-host-mirror': '{mirrors}/fuse-bindings/v{version}',
'git4win-mirror': '{mirrors}/git-for-windows',
'gl-binary-host-mirror': '{mirrors}/gl/v{version}',
'grpc-node-binary-host-mirror': '{mirrors}',
'hackrf-binary-host-mirror': '{mirrors}/hackrf/v{version}',
'leveldown-binary-host-mirror': '{mirrors}/leveldown/v{version}',
'leveldown-hyper-binary-host-mirror': '{mirrors}/leveldown-hyper/v{version}',
'mknod-binary-host-mirror': '{mirrors}/mknod/v{version}',
'node-sqlite3-binary-host-mirror': '{mirrors}',
'node-tk5-binary-host-mirror': '{mirrors}/node-tk5/v{version}',
'nodegit-binary-host-mirror': '{mirrors}/nodegit/v{version}/',
'operadriver-cdnurl': '{mirrors}/operadriver',
'phantomjs-cdnurl': '{mirrors}/phantomjs',
'profiler-binary-host-mirror': '{mirrors}/node-inspector/',
'puppeteer-download-host': '{mirrors}',
'python-mirror': '{mirrors}/python',
'rabin-binary-host-mirror': '{mirrors}/rabin/v{version}',
'sass-binary-site': '{mirrors}/node-sass',
'sodium-prebuilt-binary-host-mirror': '{mirrors}/sodium-prebuilt/v{version}',
'sqlite3-binary-site': '{mirrors}/sqlite3',
'utf-8-validate-binary-host-mirror': '{mirrors}/utf-8-validate/v{version}',
'utp-native-binary-host-mirror': '{mirrors}/utp-native/v{version}',
'zmq-prebuilt-binary-host-mirror': '{mirrors}/zmq-prebuilt/v{version}'
};

const env = {
// https://github.com/nodejs/node-gyp/
NODEJS_ORG_MIRROR: npmrc.disturl,
IOJS_ORG_MIRROR: '{mirrors}/iojs'
};

if (isWin) {
// https://github.com/hakobera/nvmw/
env.NVMW_NPM_MIRROR = '{mirrors}/npm';
}

// ProxyServer REG_SZ http=192.168.16.41:1080;https=safe.com:1109
// ProxyServer REG_SZ 192.168.16.41:1080
// AutoConfigURL REG_SZ http://192.168.16.41:1080/pac

// REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings"

argv.forEach(arg => {
if (/^--(\w+.+?)=(.*?)$/.test(arg)) {
npmrc[RegExp.$1] = RegExp.$2;
if (!/^--(\w+.+?)=(.*?)$/.test(arg)) {
return;
}
let key = RegExp.$1;
const value = RegExp.$2;
if (/^bin-mirrors-prefix$/i.test(key)) {
binMirrorPrefix = value;
return;
} else if (/^(https?)[-_]proxy$/i.test(key)) {
key = RegExp.$1.toLowerCase();
env[key + '_proxy'] = value;
key = key + '-proxy';
} else if (/^(?:\w+-)*(NODE|IO|NPM)(?:JS)?(?:-?ORG)?-MIRROR$/i.test(key)) {
key = RegExp.$1.toUpperCase();
env[key === 'NPM' ? 'NVMW_NPM_MIRROR' : (key + 'JS_ORG_MIRROR')] = value;
if (key === 'NODE') {
key = 'disturl';
} else {
return;
}
} else if (/^disturl$/i.test(key)) {
env.NODEJS_ORG_MIRROR = value;
}
npmrc[key.toLowerCase()] = value;
});

Object.keys(npmrc).forEach(key => {
if (npmrc[key]) {
npmrc[key] = npmrc[key].replace(/\{mirrors\}/g, 'https://npm.taobao.org/mirrors');
}
function fixUrl (obj) {
Object.keys(obj).forEach(key => {
if (obj[key]) {
obj[key] = obj[key].replace(/\{mirrors\}/g, binMirrorPrefix);
}
});
return obj;
}

fixUrl(env);
[
'NODEJS',
'IOJS'
].forEach(project => {
const propName = project + '_ORG_MIRROR';
(
isWin ? [
// https://github.com/hakobera/nvmw/
'NVMW_' + propName,
// https://github.com/marcelklehr/nodist
'NODIST_' + project.slice(0, 4) + '_MIRROR'
] : [
// https://github.com/creationix/nvm
'NVM_' + propName,
// https://github.com/tj/n
project.slice(0, -2) + '_MIRROR'
]
).filter(Boolean).forEach(prefixPropName => {
Object.defineProperty(env, prefixPropName, {
set: (value) => {
env[propName] = value;
},
get: () => env[propName],
enumerable: true
});
});
});
return npmrc;

return {
npmrc: fixUrl(npmrc),
env: env
};
}
module.exports = getConf;
59 changes: 22 additions & 37 deletions lib/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,50 +4,35 @@ const os = require('os');
const exec = (require('util').promisify || require('util.promisify'))(require('child_process').execFile);
const fs = require('fs-extra');

const MIRRORS = {
iojs: [
'IOJS_ORG_MIRROR',
'NODIST_IOJS_MIRROR',
'NVM_IOJS_ORG_MIRROR',
'NVMW_IOJS_ORG_MIRROR'
],
node: [
'NODEJS_ORG_MIRROR',
'NODIST_NODE_MIRROR',
'NVM_NODEJS_ORG_MIRROR',
'NVMW_NODEJS_ORG_MIRROR'
],
npm: [
'NVMW_NPM_MIRROR'
]
};

function getMirrors (tmp) {
return Array.prototype.concat.apply(
[],
Object.keys(MIRRORS).map(project => {
const url = 'https://npm.taobao.org/mirrors/' + project;
return MIRRORS[project].map(key => {
process.env[key] = url;
return tmp(key, url);
});
})
);
function getMirrors (env, tpl) {
return Object.keys(env).map(key => {
process.env[key] = env[key];
return tpl(key, env[key]);
});
}

function envForWin () {
const cmdTmpSetx = (key, url) => ['SETX', key, url];
const cmdTmpReg = (key, url) => ['REG', 'ADD', 'HKCU\\Environment', '/v', key, '/d', url, '/f'];
function envForWin (env) {
const cmdTplSetx = (key, url) => ['SETX', key, url];
const cmdTplReg = (key, url) => ['REG', 'ADD', 'HKCU\\Environment', '/v', key, '/d', url, '/f'];

return exec('where', ['SETX']).then(
() => cmdTmpSetx,
() => cmdTmpReg
).then(getMirrors).then(cmds => Promise.all(cmds.map(cmdArgs => exec(cmdArgs[0], cmdArgs.slice(1)))));
() => cmdTplSetx,
() => cmdTplReg
).then(cmdTpl => (
getMirrors(env, cmdTpl)
)).then(cmds => (
Promise.all(
cmds.map(cmdArgs => (
// console.log(cmdArgs[0], cmdArgs.slice(1).join(' '))
exec(cmdArgs[0], cmdArgs.slice(1))
))
)
));
}

function envInProfile () {
function envInProfile (env) {
// 环境变量信息转换为shell脚本
let sh = getMirrors((key, url) => `export ${key}=${url}`);
let sh = getMirrors(env, (key, url) => `export ${key}=${url}`).sort();

sh.unshift('\n\n# Created by mirror-config-china');
sh.push('# End of mirror-config-china\n');
Expand Down
24 changes: 10 additions & 14 deletions lib/install.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
'use strict';
const npmrc = require('./npmrc');
const env = require('./env');
const update = require('./update');
const path = require('path');
const os = require('os');

var argv;
let argv;
try {
argv = JSON.parse(process.env.npm_config_argv).original;
} catch (ex) {
argv = process.argv;
argv = process.argv.slice(2);
}

npmrc(argv, process.env.npm_config_userconfig || path.join(os.homedir(), '.npmrc')).catch(e => {
if (e.code === 'EACCES' || /\bpermissions?\b/i.test(e.message)) {
console.error(e.message);
console.error('Please try running this command again as root/Administrator.');
} else {
console.error(e);
}
process.exitCode = 1;
});
let configFile = process.env.npm_config_userconfig;
if (configFile) {
configFile = path.resolve(configFile);
} else {
configFile = path.join(os.homedir(), '.npmrc');
}

env();
module.exports = update(argv, configFile);
13 changes: 6 additions & 7 deletions lib/npmrc.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
'use strict';
const fs = require('fs-extra');
const config = require('./config');

function setConf (argv, configFile) {
const npmrc = config(argv);

function setConf (npmrc, configFile) {
// 读取npmrc文件
return fs.readFile(configFile, 'utf-8').catch(err => {
if (err.code === 'ENOENT') {
Expand All @@ -16,7 +13,7 @@ function setConf (argv, configFile) {
}).then(content => {
// 按行遍历原有配置,改其内容
var config = content.match(/^.*$/gm).filter(line => (
!(/^(.+?)=/.test(line) && RegExp.$1.toLowerCase() in npmrc)
!(/^(.+?)\s*=/.test(line) && RegExp.$1.toLowerCase() in npmrc)
));

while (config.length && !config[config.length - 1]) {
Expand All @@ -34,14 +31,16 @@ function setConf (argv, configFile) {
}
});

config.push('');
if (config[config.length - 1]) {
config.push('');
}

// 将配置转换为字符串
config = config.join('\n');

// 如果文件内容有变化,保存结果
if (content !== config) {
return fs.writeFile(configFile, config);
return fs.outputFile(configFile, config);
}
});
}
Expand Down
Loading

0 comments on commit 476c617

Please sign in to comment.