Skip to content

Commit

Permalink
精简 npmrc 更新时的日志输出信息
Browse files Browse the repository at this point in the history
增强 install 的可测试性
  • Loading branch information
gucong3000 committed May 24, 2023
1 parent 9d18c6f commit e6f50e9
Show file tree
Hide file tree
Showing 7 changed files with 86 additions and 66 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ source ~/.bashrc && env

- `--registry=https://registry.npmmirror.com`
`https://registry.npmjs.org/`的镜像地址
- `--disturl=https://cdn.npmmirror.com/binaries/node`
`https://nodejs.org/dist/`的镜像地址
- `--bin-mirror-prefix=https://cdn.npmmirror.com/binaries`
二进制文件下载镜像站地址
二进制文件下载镜像站地址的前缀
- `--disturl={bin-mirror}/node`
`https://nodejs.org/dist/`的镜像地址

以上信息存入`.npmrc`文件

Expand Down Expand Up @@ -95,7 +95,7 @@ PATH 环境变量中加入`node_modules/.bin`这个路径,方便调用`mocha`
- [windows-build-tools](https://www.npmjs.com/package/windows-build-tools)
- [@swc/core](https://www.npmjs.com/package/@swc/core)

注:未能全部列出
注:未能全部列出,详见[data/npmrc.js](./data/npmrc.js)

## 未尽功能

Expand Down
2 changes: 1 addition & 1 deletion data/npmrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,12 @@ const npmrc = {

'disturl': '{bin-mirror}/node',

/* eslint no-template-curly-in-string: "off" */
'better-sqlite3-binary-host': '{bin-mirror}/better-sqlite3',
'canvas-binary-host-mirror': '{bin-mirror}/node-canvas-prebuilt/v{version}',
'canvas-prebuilt-binary-host-mirror': '{bin-mirror}/node-canvas-prebuilt/v{version}',
'chromedriver-cdnurl': '{bin-mirror}/chromedriver',
'couchbase-binary-host-mirror': '{bin-mirror}/couchbase/v{version}',
/* eslint no-template-curly-in-string: "off" */
'cypress-download-path-template': '{bin-mirror}/cypress/${version}/${platform}-${arch}/cypress.zip',
'debug-binary-host-mirror': '{bin-mirror}/node-inspector',
'electron-builder-binaries-mirror': '{bin-mirror}/electron-builder-binaries/',
Expand Down
2 changes: 2 additions & 0 deletions lib/cli.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#!/usr/bin/env node

import update from './update.js';
import install from './install.js';
import { resolve } from 'node:path';

await install;
await update(process.argv.slice(2), resolve('.npmrc'));
34 changes: 22 additions & 12 deletions lib/install.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,18 @@ import update from './update.js';
import path from 'node:path';
import { homedir } from 'node:os';

let argv;
try {
argv = JSON.parse(process.env.npm_config_argv).original;
} catch (ex) {
argv = process.argv.slice(2);
function getArgv (env) {
let argv;
try {
argv = JSON.parse(env.npm_config_argv).original;
} catch (ex) {
argv = process.argv.slice(2);
}
return argv;
}
function getNpmUserCfg () {
let configFile = process.env.npm_config_userconfig;

function getNpmUserCfg (env) {
let configFile = env.npm_config_userconfig;
if (configFile) {
configFile = path.resolve(configFile);
} else {
Expand All @@ -19,11 +23,17 @@ function getNpmUserCfg () {
return configFile;
}

function install (configFile = getNpmUserCfg()) {
return update(argv, configFile);
function install (env = process.env) {
return update(
getArgv(env),
getNpmUserCfg(env),
);
}

await install();
export {
getArgv,
install,
getNpmUserCfg,
};

export { install };
export default install;
export default await install();
78 changes: 49 additions & 29 deletions lib/npmrc.js
Original file line number Diff line number Diff line change
@@ -1,48 +1,68 @@
import fs from 'node:fs/promises';

function setConf (npmrc, configFile) {
async function setConf (npmrc, configFile) {
// 读取npmrc文件
return fs.readFile(configFile, 'utf-8').catch(err => {
let content;
try {
content = await fs.readFile(configFile, 'utf-8');
} catch (err) {
if (err.code === 'ENOENT') {
// 文件不存在
return '';
content = '';
} else {
throw err;
}
}).then(content => {
// 按行遍历原有配置,改其内容
let config = content.match(/^.*$/gm).filter(line => (
!(/^(.+?)\s*=/.test(line) && RegExp.$1.toLowerCase() in npmrc)
));

while (config.length && !config[config.length - 1]) {
config.pop();
}
}

const oldRc = {
};

if (config.length) {
config.push('');
// 按行遍历原有配置,改其内容
let config = content.split(/\r\n|\r|\n/g).filter(line => {
line = /^(.+?)\s*=\s*(.*?)\s*$/.exec(line.toLowerCase());
if (line) {
const [, key, value] = line;
oldRc[key] = value;
// 删除原配置中,与新配置相同的项目
return !(key in npmrc);
}
return true;
});

// 删除文件结尾的空行
while (config.length && !config[config.length - 1]) {
config.pop();
}

// 将文件中没有的配置项,追加到其末尾
for (const key in npmrc) {
if (npmrc[key]) {
console.log('> npm config set', key, npmrc[key]);
config.push(key + '=' + npmrc[key]);
// 如果原文件内容非空,添一行空行以示分割
if (config.length) {
config.push('');
}

// 将新的配置项,追加到其末尾
for (const key in npmrc) {
if (npmrc[key]) {
const value = npmrc[key].toLowerCase();
if (oldRc[key] !== value) {
console.log('> npm config set', key, value);
}
config.push(key + '=' + value);
} else if (oldRc[key]) {
console.log('> npm config delete', key);
}
}

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

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

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

export {
Expand Down
5 changes: 3 additions & 2 deletions lib/sudo.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,22 +4,23 @@ import { fileURLToPath } from 'node:url';
import isElevated from 'is-elevated';
import spawnAsync from './spawn.js';
const cache = {};
const isRoot = await isElevated();

function writeFileSync (file, data) {
console.log('>', 'tee', file);
return fs.writeFile(file, data);
}

async function writeFile (file, data) {
if (await isElevated()) {
if (isRoot) {
return writeFileSync(file, data);
} else {
cache.fs[file] = data.toString();
}
}

async function spawn (...args) {
if (await isElevated()) {
if (isRoot) {
return spawnAsync(...args);
} else {
cache.cmd.push(args);
Expand Down
23 changes: 5 additions & 18 deletions test/install.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,10 @@
import spawn from '../lib/spawn.js';
import { fileURLToPath } from 'node:url';
import path from 'node:path';

describe('install', () => {
it('install script', async () => {
const filename = fileURLToPath(
import.meta.url,
);
await spawn([
process.execPath,
path.resolve(
path.dirname(filename),
'../lib/install',
),
], {
encoding: 'utf8',
env: {
PATH: process.env.PATH,
},
});
(await import('../lib/install.js')).install();
});

it('install without npm', async () => {
(await import('../lib/install.js')).install({});
});
});

0 comments on commit e6f50e9

Please sign in to comment.