Files
cli/src/command/npm.ts
2024-12-05 17:31:32 +08:00

198 lines
5.8 KiB
TypeScript

import { program, Command } from '@/program.ts';
import { chalk } from '../module/chalk.ts';
import path from 'path';
import { spawn } from 'child_process';
import { fileIsExist } from '@/uitls/file.ts';
import { getConfig } from '@/module/get-config.ts';
import fs from 'fs';
import inquirer from 'inquirer';
import { checkPnpm } from '@/uitls/npm.ts';
const command = new Command('npm').description('npm command show publish and set .npmrc').action(async (options) => {});
const publish = new Command('publish')
.argument('[registry]')
.option('-p --proxy', 'proxy')
.description('publish npm')
.action(async (registry, options) => {
const answer = await inquirer.prompt([
{
type: 'list',
name: 'publish',
message: 'Select the registry to publish',
choices: [
{
name: 'me',
value: 'me',
},
{
name: 'npm',
value: 'npm',
},
],
when: !registry,
},
]);
registry = registry || answer.publish;
const config = getConfig();
let cmd = '';
const execPath = process.cwd();
let setEnv = {};
const proxyEnv = {
https_proxy: 'http://127.0.0.1:7890',
http_proxy: 'http://127.0.0.1:7890',
all_proxy: 'socks5://127.0.0.1:7890',
...config?.proxy,
};
if (options?.proxy) {
setEnv = {
...proxyEnv,
};
}
if (registry) {
const packageJson = path.resolve(execPath, 'package.json');
switch (registry) {
case 'me':
cmd = 'npm publish --registry https://npm.xiongxiao.me';
console.log(chalk.green(cmd));
break;
case 'npm':
cmd = 'npm publish --registry https://registry.npmjs.org';
console.log(chalk.green(cmd));
break;
default:
cmd = 'npm publish --registry https://npm.xiongxiao.me';
console.log(chalk.green(cmd));
break;
}
if (fileIsExist(packageJson)) {
const keys = Object.keys(config).filter((key) => key.includes('NPM_TOKEN'));
const tokenEnv = keys.reduce((prev, key) => {
return {
...prev,
[key]: config[key],
};
}, {});
const child = spawn(cmd, {
shell: true,
cwd: execPath,
env: {
...process.env, // 保留当前环境变量
...tokenEnv,
...setEnv,
},
});
child.stdout.on('data', (data) => {
console.log(chalk.green(`${data}`));
});
child.stderr.on('data', (data) => {
// 过滤掉 'npm notice' 或者其他信息
if (data.toString().includes('npm notice')) {
console.log(chalk.yellow(`notice: ${data}`));
} else {
console.error(`stderr: ${data}`);
}
});
child.on('close', (code) => {
// console.log(`child process exited with code ${code}`);
});
} else {
console.error(chalk.red('package.json not found'));
}
}
});
command.addCommand(publish);
const getnpmrc = new Command('get').action(async () => {
const execPath = process.cwd();
const npmrcPath = path.resolve(execPath, '.npmrc');
if (fileIsExist(npmrcPath)) {
const npmrcContent = fs.readFileSync(npmrcPath, 'utf-8');
// console.log(chalk.green('get .npmrc success'));
console.log(npmrcContent);
}
});
command.addCommand(getnpmrc);
const npmrc = new Command('set')
.description('set .npmrc')
.option('-f <force>')
.action(async (options) => {
const config = getConfig();
const npmrcContent =
config?.npmrc ||
`//npm.xiongxiao.me/:_authToken=\${ME_NPM_TOKEN}
@abearxiong:registry=https://npm.pkg.github.com
//registry.npmjs.org/:_authToken=\${NPM_TOKEN}
@kevisual:registry=https://npm.xiongxiao.me`;
const execPath = process.cwd();
const npmrcPath = path.resolve(execPath, '.npmrc');
let writeFlag = false;
if (fileIsExist(npmrcPath)) {
if (options.force) {
writeFlag = true;
} else {
const answer = await inquirer.prompt([
{
type: 'confirm',
name: 'confirm',
message: `Are you sure you want to overwrite the .npmrc file?`,
default: false,
},
]);
if (answer.confirm) {
writeFlag = true;
}
}
} else {
writeFlag = true;
}
if (writeFlag) {
fs.writeFileSync(npmrcPath, npmrcContent);
console.log(chalk.green('write .npmrc success'));
}
});
command.addCommand(npmrc);
const remove = new Command('remove').description('remove .npmrc').action(async () => {
const execPath = process.cwd();
const npmrcPath = path.resolve(execPath, '.npmrc');
if (fileIsExist(npmrcPath)) {
fs.unlinkSync(npmrcPath);
console.log(chalk.green('remove .npmrc success'));
} else {
console.log(chalk.green('.npmrc success'));
}
});
command.addCommand(remove);
const install = new Command('install')
.option('-n, --noproxy', 'no proxy')
.description('npm install 使用 proxy代理去下载')
.action(async (options) => {
const cwd = process.cwd();
const config = getConfig();
let setEnv = {};
const proxyEnv = {
https_proxy: 'http://127.0.0.1:7890',
http_proxy: 'http://127.0.0.1:7890',
all_proxy: 'socks5://127.0.0.1:7890',
...config?.proxy,
};
setEnv = {
...proxyEnv,
};
if (options?.noproxy) {
setEnv = {};
}
if (checkPnpm()) {
spawn('pnpm', ['i'], { stdio: 'inherit', cwd: cwd, env: { ...process.env, ...setEnv } });
} else {
spawn('npm', ['i'], { stdio: 'inherit', cwd: cwd, env: { ...process.env, ...setEnv } });
}
});
command.addCommand(install);
// program 添加npm 的命令
program.addCommand(command);