Commit 1641f3d0 by Jaxon

refactor(scripts): 统一代码格式并优化脚本逻辑

1 parent 83624060
{
"tailwindCSS.experimental.configFile": "internal/tailwind-config/src/index.ts",
"eslint.nodePath": "./node_modules",
// workbench
"workbench.list.smoothScrolling": true,
"workbench.startupEditor": "newUntitledFile",
......
module.exports = {
root: true,
env: {
node: true
},
extends: [
'plugin:vue/vue3-essential',
// '@vue/standard',
'@vue/typescript/recommended'
],
parserOptions: {
ecmaVersion: 2020
},
rules: {
'template-curly-spacing': 'off',
indent: 'off',
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'function-paren-newline': [2, {minItems: 6}],
}
};
......@@ -47,8 +47,6 @@
},
"devDependencies": {
"@types/node": "^20.14.2",
"@typescript-eslint/eslint-plugin": "^5.4.0",
"@typescript-eslint/parser": "^5.4.0",
"@vitejs/plugin-vue": "^5.0.4",
"less": "^3.9.0",
"less-loader": "^6.0.0",
......
module.exports = {
root: true,
env: {
node: true
},
extends: [
// 'plugin:vue/vue3-essential',
// '@vue/standard',
// '@vue/typescript/recommended'
],
parserOptions: {
ecmaVersion: 2020
},
rules: {
'template-curly-spacing': 'off',
indent: 'off',
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
// 'function-paren-newline': [2, {minItems: 3}],
"@typescript-eslint/ban-ts-comment": 1,
'no-undef-init': 0,//禁止将变量初始化为 undefined
"@typescript-eslint/no-explicit-any": ["off"],
"@typescript-eslint/explicit-module-boundary-types": "off"
},
overrides: [
{
files: [
'**/__tests__/*.{j,t}s?(x)',
'**/tests/unit/**/*.spec.{j,t}s?(x)'
],
env: {
jest: true
}
}
]
}
......@@ -4,7 +4,7 @@
"codelyzer"
],
"rules": {
"no-import-side-effect": [true, {"ignore-module": "(\\@lib)$"}], //禁止导入带有副作用的语句
"no-import-side-effect": [true, {"ignore-module": "(\\@lib)$"}], // 禁止导入带有副作用的语句
"no-trailing-whitespace": false,
"array-type": false,
"arrow-parens": false,
......
......@@ -84,6 +84,7 @@ export async function typescript(): Promise<Linter.Config[]> {
},
},
ignoresMiniprogram(pluginTs, parserTs),
ignoresScript(pluginTs, parserTs)
];
}
......@@ -119,3 +120,31 @@ function ignoresMiniprogram(pluginTs: any, parserTs:any): Linter.Config {
},
};
}
function ignoresScript(pluginTs: any, parserTs:any): Linter.Config {
return {
files: [ "scripts/**/*.?([cm])[jt]s?(x)" ],
languageOptions: {
parser: parserTs,
parserOptions: {
createDefaultProgram: false,
ecmaFeatures: {
jsx: true,
},
ecmaVersion: "latest",
extraFileExtensions: [ ".vue" ],
jsxPragma: "React",
project: "./tsconfig.*.json",
sourceType: "module",
},
},
plugins: {
"@typescript-eslint": pluginTs as any,
},
rules: {
"@typescript-eslint/no-require-imports": "off",
"@typescript-eslint/no-var-requires": "off",
},
};
}
{
"root": true,
"env": { "browser": true, "es2020": true },
"parserOptions": { "ecmaVersion": 2020, "sourceType": "module" },
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"plugin:react-hooks/recommended"
],
"settings": { "react": { "version": "detect" } }
}
{
"root": true,
"env": { "browser": true, "es2020": true },
"parserOptions": { "ecmaVersion": 2020, "sourceType": "module" },
"extends": ["eslint:recommended", "plugin:vue/vue3-recommended"],
"rules": {}
}
import terser from '@rollup/plugin-terser';
import terser from "@rollup/plugin-terser";
// 进行统一打包管理 rollup
import { rollup } from 'rollup';
import { rollup } from "rollup";
import { clearDist, getRollupConfigs } from './buildBase.js';
import { clearDist, getRollupConfigs } from "./buildBase.js";
async function build() {
const configs = await getRollupConfigs();
for (const name of Object.keys(configs)) {
clearDist(name);
const config = configs[name];
console.log(`正在打包:${name}`);
const bundle = await rollup({
input: config.input,
plugins: [...config.plugins, terser()],
external: config.external,
});
const tasks = [];
for (const output of config.output) {
tasks.push(bundle.write(output));
}
await Promise.all(tasks);
console.log(`打包完成:${name}`);
}
const configs = await getRollupConfigs();
for (const name of Object.keys(configs)) {
clearDist(name);
const config = configs[name];
console.log(`正在打包:${name}`);
const bundle = await rollup({
input: config.input,
plugins: [...config.plugins, terser()],
external: config.external,
});
const tasks = [];
for (const output of config.output) {
tasks.push(bundle.write(output));
}
await Promise.all(tasks);
console.log(`打包完成:${name}`);
}
}
build();
import fs from 'node:fs';
import path from 'node:path';
import URL from 'node:url';
import fs from "node:fs";
import path from "node:path";
import URL from "node:url";
import commonjs from '@rollup/plugin-commonjs';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import postcss from 'rollup-plugin-postcss';
import typescript from 'rollup-plugin-typescript2';
import vue from 'rollup-plugin-vue';
import commonjs from "@rollup/plugin-commonjs";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import postcss from "rollup-plugin-postcss";
import typescript from "rollup-plugin-typescript2";
import vue from "rollup-plugin-vue";
const __filename = URL.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
function discoverPackages() {
const base = path.resolve(__dirname, '../packages');
const result = [];
// tools
const toolsPath = path.resolve(base, 'tools');
if (fs.existsSync(path.resolve(toolsPath, 'package.json'))) {
result.push('tools');
}
// charts
const chartsPath = path.resolve(base, 'charts');
if (fs.existsSync(path.resolve(chartsPath, 'package.json'))) {
result.push('charts');
}
// cli
const cliPath = path.resolve(base, 'cli');
if (fs.existsSync(path.resolve(cliPath, 'package.json'))) {
result.push('cli');
}
// components/*
const componentsPath = path.resolve(base, 'components');
if (fs.existsSync(componentsPath)) {
const subs = fs.readdirSync(componentsPath, { withFileTypes: true });
for (const dirent of subs) {
if (dirent.isDirectory()) {
const name = dirent.name;
const pkgPath = path.resolve(componentsPath, name, 'package.json');
if (fs.existsSync(pkgPath)) {
result.push(`components/${name}`);
}
}
}
}
return result;
const base = path.resolve(__dirname, "../packages");
const result = [];
// tools
const toolsPath = path.resolve(base, "tools");
if (fs.existsSync(path.resolve(toolsPath, "package.json"))) {
result.push("tools");
}
// charts
const chartsPath = path.resolve(base, "charts");
if (fs.existsSync(path.resolve(chartsPath, "package.json"))) {
result.push("charts");
}
// cli
const cliPath = path.resolve(base, "cli");
if (fs.existsSync(path.resolve(cliPath, "package.json"))) {
result.push("cli");
}
// components/*
const componentsPath = path.resolve(base, "components");
if (fs.existsSync(componentsPath)) {
const subs = fs.readdirSync(componentsPath, { withFileTypes: true });
for (const dirent of subs) {
if (dirent.isDirectory()) {
const name = dirent.name;
const pkgPath = path.resolve(componentsPath, name, "package.json");
if (fs.existsSync(pkgPath)) {
result.push(`components/${name}`);
}
}
}
}
return result;
}
function getPackageRoots() {
const pkgs = discoverPackages();
return pkgs.map((pkg) => path.resolve(__dirname, `../packages`, pkg));
const pkgs = discoverPackages();
return pkgs.map((pkg) => path.resolve(__dirname, `../packages`, pkg));
}
async function packageJson(root) {
const pkgPath = path.resolve(root, 'package.json');
const content = await fs.promises.readFile(pkgPath, 'utf8');
return JSON.parse(content);
const pkgPath = path.resolve(root, "package.json");
const content = await fs.promises.readFile(pkgPath, "utf8");
return JSON.parse(content);
}
export async function getRollupConfig(root) {
const config = await packageJson(root);
const tsconfig = path.resolve(root, 'tsconfig.json');
const { name, formats = ['esm', 'cjs'] } = config.buildOptions || {};
const dist = path.resolve(root, './dist');
const entry = path.resolve(root, './src/index.ts');
if (!fs.existsSync(entry)) {
return null;
}
const isVue =
/components[\\/]+vue$/.test(root) ||
!!(config.peerDependencies && config.peerDependencies.vue);
const basePlugins = [nodeResolve(), commonjs(), postcss()];
const plugins = isVue
? [
vue({ compileTemplate: true }),
typescript({
tsconfig,
tsconfigOverride: { compilerOptions: { outDir: dist } },
check: false,
}),
...basePlugins,
]
: [
typescript({
tsconfig,
tsconfigOverride: { compilerOptions: { outDir: dist } },
check: false,
}),
...basePlugins,
];
const config = await packageJson(root);
const tsconfig = path.resolve(root, "tsconfig.json");
const { name, formats = ["esm", "cjs"] } = config.buildOptions || {};
const dist = path.resolve(root, "./dist");
const entry = path.resolve(root, "./src/index.ts");
if (!fs.existsSync(entry)) {
return null;
}
const isVue = /components[\\/]+vue$/.test(root) || !!(config.peerDependencies && config.peerDependencies.vue);
const basePlugins = [nodeResolve(), commonjs(), postcss()];
const plugins = isVue
? [
vue({ compileTemplate: true }),
typescript({
tsconfig,
tsconfigOverride: { compilerOptions: { outDir: dist } },
check: false,
}),
...basePlugins,
]
: [
typescript({
tsconfig,
tsconfigOverride: { compilerOptions: { outDir: dist } },
check: false,
}),
...basePlugins,
];
const rollupOptions = {
input: entry,
external: isVue ? ['vue'] : [],
plugins,
};
const output = [];
for (const format of formats) {
const outputItem = {
format,
file: path.resolve(dist, `index.${format}.js`),
sourcemap: true,
exports: 'named',
globals: isVue ? { vue: 'Vue' } : {},
};
if (format === 'iife') {
outputItem.name = name || 'VenusLib';
}
// 为 CLI 的 cjs 产物添加 shebang 以支持作为可执行脚本运行
const isCli = /[\\/]packages[\\/]+cli$/.test(root);
if (isCli && format === 'cjs') {
outputItem.banner = '#!/usr/bin/env node';
}
output.push(outputItem);
}
rollupOptions.output = output;
const rollupOptions = {
input: entry,
external: isVue ? ["vue"] : [],
plugins,
};
const output = [];
for (const format of formats) {
const outputItem = {
format,
file: path.resolve(dist, `index.${format}.js`),
sourcemap: true,
exports: "named",
globals: isVue ? { vue: "Vue" } : {},
};
if (format === "iife") {
outputItem.name = name || "VenusLib";
}
// 为 CLI 的 cjs 产物添加 shebang 以支持作为可执行脚本运行
const isCli = /[\\/]packages[\\/]+cli$/.test(root);
if (isCli && format === "cjs") {
outputItem.banner = "#!/usr/bin/env node";
}
output.push(outputItem);
}
rollupOptions.output = output;
rollupOptions.watch = {
include: path.resolve(root, 'src/**'),
exclude: path.resolve(root, 'node_modules/**'),
clearScreen: false,
};
return rollupOptions;
rollupOptions.watch = {
include: path.resolve(root, "src/**"),
exclude: path.resolve(root, "node_modules/**"),
clearScreen: false,
};
return rollupOptions;
}
export async function getRollupConfigs() {
const pkgs = discoverPackages();
const roots = getPackageRoots();
const configs = await Promise.all(roots.map(getRollupConfig));
const result = {};
for (const [i, pkg] of pkgs.entries()) {
const cfg = configs[i];
if (!cfg) {
console.warn(`跳过包: ${pkg},缺少入口文件 src/index.ts`);
continue;
}
result[pkg] = cfg;
}
return result;
const pkgs = discoverPackages();
const roots = getPackageRoots();
const configs = await Promise.all(roots.map((root) => getRollupConfig(root)));
const result = {};
for (const [i, pkg] of pkgs.entries()) {
const cfg = configs[i];
if (!cfg) {
console.warn(`跳过包: ${pkg},缺少入口文件 src/index.ts`);
continue;
}
result[pkg] = cfg;
}
return result;
}
export function clearDist(name) {
const dist = path.resolve(__dirname, `../packages`, name, `dist`);
if (fs.existsSync(dist)) {
fs.rmSync(dist, { recursive: true, force: true });
}
const dist = path.resolve(__dirname, `../packages`, name, `dist`);
if (fs.existsSync(dist)) {
fs.rmSync(dist, { recursive: true, force: true });
}
}
import path from 'node:path';
import URL from 'node:url';
import path from "node:path";
import URL from "node:url";
import terser from '@rollup/plugin-terser';
import terser from "@rollup/plugin-terser";
// 单独打包指定的包
import { rollup } from 'rollup';
import { rollup } from "rollup";
const __filename = URL.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
async function buildSingle(packageName) {
if (!packageName) {
console.error('请指定要构建的包名');
process.exit(1);
}
const packagePath = path.resolve(__dirname, `../../packages/${packageName}`);
try {
// 检查包是否存在
const fs = await import('node:fs');
if (!fs.existsSync(packagePath)) {
console.error(`包 ${packageName} 不存在`);
process.exit(1);
}
console.log(`正在构建包: ${packageName}`);
// 清理 dist 目录
const distPath = path.resolve(packagePath, 'dist');
if (fs.existsSync(distPath)) {
fs.rmSync(distPath, { recursive: true, force: true });
}
// 获取构建配置
const { getRollupConfig } = await import('./buildBase.js');
const config = await getRollupConfig(packagePath);
console.log(`正在打包: ${packageName}`);
const bundle = await rollup({
input: config.input,
plugins: [...config.plugins, terser()],
external: config.external,
});
const tasks = [];
for (const output of config.output) {
tasks.push(bundle.write(output));
}
await Promise.all(tasks);
console.log(`打包完成: ${packageName}`);
} catch (error) {
console.error(`构建失败: ${error.message}`);
process.exit(1);
}
if (!packageName) {
console.error("请指定要构建的包名");
process.exit(1);
}
const packagePath = path.resolve(__dirname, `../../packages/${packageName}`);
try {
// 检查包是否存在
const fs = await import("node:fs");
if (!fs.existsSync(packagePath)) {
console.error(`包 ${packageName} 不存在`);
process.exit(1);
}
console.log(`正在构建包: ${packageName}`);
// 清理 dist 目录
const distPath = path.resolve(packagePath, "dist");
if (fs.existsSync(distPath)) {
fs.rmSync(distPath, { recursive: true, force: true });
}
// 获取构建配置
const { getRollupConfig } = await import("./buildBase.js");
const config = await getRollupConfig(packagePath);
console.log(`正在打包: ${packageName}`);
const bundle = await rollup({
input: config.input,
plugins: [...config.plugins, terser()],
external: config.external,
});
const tasks = [];
for (const output of config.output) {
tasks.push(bundle.write(output));
}
await Promise.all(tasks);
console.log(`打包完成: ${packageName}`);
} catch (error) {
console.error(`构建失败: ${error.message}`);
process.exit(1);
}
}
// 从命令行参数获取包名
......
......@@ -6,26 +6,26 @@
* 3. 将构建产物复制到根目录的 dist 文件夹
*/
import { execSync } from 'node:child_process';
import { existsSync, mkdirSync, rmSync } from 'node:fs';
import { copyFile, readdir } from 'node:fs/promises';
import { join } from 'node:path';
import { execSync } from "node:child_process";
import { existsSync, mkdirSync, rmSync } from "node:fs";
import { copyFile, readdir } from "node:fs/promises";
import { join } from "node:path";
// 获取项目根目录
const rootDir = process.cwd();
const rootDistDir = join(rootDir, 'dist');
const rootDistDir = join(rootDir, "dist");
/**
* 清理根目录的 dist 文件夹
*/
function cleanRootDist() {
console.log('🧹 清理根目录的 dist 文件夹...');
if (existsSync(rootDistDir)) {
rmSync(rootDistDir, { recursive: true, force: true });
console.log('✅ 根目录 dist 文件夹已清理');
} else {
console.log('ℹ️ 根目录 dist 文件夹不存在,跳过清理');
}
console.log("🧹 清理根目录的 dist 文件夹...");
if (existsSync(rootDistDir)) {
rmSync(rootDistDir, { recursive: true, force: true });
console.log("✅ 根目录 dist 文件夹已清理");
} else {
console.log("ℹ️ 根目录 dist 文件夹不存在,跳过清理");
}
}
/**
......@@ -33,21 +33,21 @@ function cleanRootDist() {
* @param {string} packageName - 包名或过滤器
*/
function buildPackage(packageName) {
console.log(`\n📦 开始构建项目: ${packageName}`);
try {
execSync(`pnpm --filter=${packageName} run build`, {
stdio: 'inherit',
cwd: rootDir,
env: {
...process.env,
NODE_OPTIONS: '--max-old-space-size=8192',
},
});
console.log(`✅ 项目构建完成: ${packageName}`);
} catch {
console.error(`❌ 项目构建失败: ${packageName}`);
process.exit(1);
}
console.log(`\n📦 开始构建项目: ${packageName}`);
try {
execSync(`pnpm --filter=${packageName} run build`, {
stdio: "inherit",
cwd: rootDir,
env: {
...process.env,
NODE_OPTIONS: "--max-old-space-size=8192",
},
});
console.log(`✅ 项目构建完成: ${packageName}`);
} catch {
console.error(`❌ 项目构建失败: ${packageName}`);
process.exit(1);
}
}
/**
......@@ -56,21 +56,19 @@ function buildPackage(packageName) {
* @param {string} dest - 目标目录
*/
async function copyDirectory(src, dest) {
// 确保目标目录存在
if (!existsSync(dest)) {
mkdirSync(dest, { recursive: true });
}
// 确保目标目录存在
if (!existsSync(dest)) {
mkdirSync(dest, { recursive: true });
}
const entries = await readdir(src, { withFileTypes: true });
const entries = await readdir(src, { withFileTypes: true });
for (const entry of entries) {
const srcPath = join(src, entry.name);
const destPath = join(dest, entry.name);
for (const entry of entries) {
const srcPath = join(src, entry.name);
const destPath = join(dest, entry.name);
await (entry.isDirectory()
? copyDirectory(srcPath, destPath)
: copyFile(srcPath, destPath));
}
await (entry.isDirectory() ? copyDirectory(srcPath, destPath) : copyFile(srcPath, destPath));
}
}
/**
......@@ -79,45 +77,43 @@ async function copyDirectory(src, dest) {
* @returns {string|null} 包的路径
*/
async function findPackagePath(packageName) {
// 移除 @venus/ 前缀(如果有)
const cleanName = packageName.replace('@venus/', '');
// 可能的路径
const possiblePaths = [
join(rootDir, 'apps', 'frontend-micro', cleanName),
join(rootDir, 'apps', 'frontend', 'vue', cleanName),
join(rootDir, 'apps', cleanName),
join(rootDir, 'packages', cleanName),
join(rootDir, 'docs'),
];
// 尝试查找包
for (const path of possiblePaths) {
if (existsSync(path)) {
const packageJsonPath = join(path, 'package.json');
if (existsSync(packageJsonPath)) {
try {
const packageJson = JSON.parse(
await import('node:fs').then((fs) =>
fs.promises.readFile(packageJsonPath, 'utf8'),
),
);
// 检查包名是否匹配
if (
packageJson.name === packageName ||
packageJson.name === `@venus/${cleanName}` ||
packageJson.name === cleanName
) {
return path;
}
} catch {
// 忽略 JSON 解析错误
}
}
}
}
return null;
// 移除 @venus/ 前缀(如果有)
const cleanName = packageName.replace("@venus/", "");
// 可能的路径
const possiblePaths = [
join(rootDir, "apps", "frontend-micro", cleanName),
join(rootDir, "apps", "frontend", "vue", cleanName),
join(rootDir, "apps", cleanName),
join(rootDir, "packages", cleanName),
join(rootDir, "docs"),
];
// 尝试查找包
for (const path of possiblePaths) {
if (existsSync(path)) {
const packageJsonPath = join(path, "package.json");
if (existsSync(packageJsonPath)) {
try {
const packageJson = JSON.parse(
await import("node:fs").then((fs) => fs.promises.readFile(packageJsonPath, "utf8")),
);
// 检查包名是否匹配
if (
packageJson.name === packageName ||
packageJson.name === `@venus/${cleanName}` ||
packageJson.name === cleanName
) {
return path;
}
} catch {
// 忽略 JSON 解析错误
}
}
}
}
return null;
}
/**
......@@ -125,75 +121,75 @@ async function findPackagePath(packageName) {
* @param {string} packageName - 包名
*/
async function copyBuildToRoot(packageName) {
console.log(`\n📂 查找构建产物...`);
console.log(`\n📂 查找构建产物...`);
const packagePath = await findPackagePath(packageName);
const packagePath = await findPackagePath(packageName);
if (!packagePath) {
console.error(`❌ 无法找到包: ${packageName}`);
process.exit(1);
}
if (!packagePath) {
console.error(`❌ 无法找到包: ${packageName}`);
process.exit(1);
}
console.log(`📍 包路径: ${packagePath}`);
console.log(`📍 包路径: ${packagePath}`);
const sourceDistDir = join(packagePath, 'dist');
const sourceDistDir = join(packagePath, "dist");
if (!existsSync(sourceDistDir)) {
console.error(`❌ 构建产物不存在: ${sourceDistDir}`);
process.exit(1);
}
if (!existsSync(sourceDistDir)) {
console.error(`❌ 构建产物不存在: ${sourceDistDir}`);
process.exit(1);
}
console.log(`\n📋 复制构建产物到根目录...`);
console.log(` 源目录: ${sourceDistDir}`);
console.log(` 目标目录: ${rootDistDir}`);
console.log(`\n📋 复制构建产物到根目录...`);
console.log(` 源目录: ${sourceDistDir}`);
console.log(` 目标目录: ${rootDistDir}`);
try {
await copyDirectory(sourceDistDir, rootDistDir);
console.log('✅ 构建产物已复制到根目录的 dist 文件夹');
try {
await copyDirectory(sourceDistDir, rootDistDir);
console.log("✅ 构建产物已复制到根目录的 dist 文件夹");
// 显示复制的文件统计
const files = await readdir(rootDistDir, { recursive: true });
console.log(`\n📊 共复制 ${files.length} 个文件`);
} catch (error) {
console.error(`❌ 复制构建产物失败: ${error.message}`);
process.exit(1);
}
// 显示复制的文件统计
const files = await readdir(rootDistDir, { recursive: true });
console.log(`\n📊 共复制 ${files.length} 个文件`);
} catch (error) {
console.error(`❌ 复制构建产物失败: ${error.message}`);
process.exit(1);
}
}
/**
* 主函数
*/
async function main() {
const packageName = process.argv[2];
const packageName = process.argv[2];
if (!packageName) {
console.error('❌ 请指定要构建的项目名');
console.log('\n使用方法:');
console.log(' pnpm build:filter <package-name>');
console.log('\n示例:');
console.log(' pnpm build:filter @venus/venus-base');
console.log(' pnpm build:filter venus-micro-app');
process.exit(1);
}
if (!packageName) {
console.error("❌ 请指定要构建的项目名");
console.log("\n使用方法:");
console.log(" pnpm build:filter <package-name>");
console.log("\n示例:");
console.log(" pnpm build:filter @venus/venus-base");
console.log(" pnpm build:filter venus-micro-app");
process.exit(1);
}
console.log('🚀 开始自定义构建流程');
console.log(`📦 目标项目: ${packageName}\n`);
console.log("🚀 开始自定义构建流程");
console.log(`📦 目标项目: ${packageName}\n`);
// 1. 清理根目录 dist
cleanRootDist();
// 1. 清理根目录 dist
cleanRootDist();
// 2. 构建指定项目
buildPackage(packageName);
// 2. 构建指定项目
buildPackage(packageName);
// 3. 复制构建产物到根目录
await copyBuildToRoot(packageName);
// 3. 复制构建产物到根目录
await copyBuildToRoot(packageName);
console.log('\n✨ 构建流程完成!');
console.log(`📁 构建产物位置: ${rootDistDir}`);
console.log("\n✨ 构建流程完成!");
console.log(`📁 构建产物位置: ${rootDistDir}`);
}
// 执行主函数
main().catch((error) => {
console.error(`❌ 构建过程中出现错误: ${error.message}`);
process.exit(1);
console.error(`❌ 构建过程中出现错误: ${error.message}`);
process.exit(1);
});
import fs from 'node:fs';
import path from 'node:path';
import fs from "node:fs";
import path from "node:path";
// Usage:
// node scripts/cleanApp.js vue <name> [--dir=apps/frontend/vue] [--subdir=playground]
......@@ -8,49 +8,46 @@ import path from 'node:path';
// node scripts/cleanApp.js <template> <name> [--dir=<relative base>] [--subdir=<sub path>]
const args = process.argv.slice(2);
const template = (args[0] || 'vue').toLowerCase();
const flags = args.filter((a) => typeof a === 'string' && a.startsWith('--'));
const positionals = args
.filter((a) => typeof a === 'string' && !a.startsWith('--'))
.slice(1); // drop template
const template = (args[0] || "vue").toLowerCase();
const flags = args.filter((a) => typeof a === "string" && a.startsWith("--"));
const positionals = args.filter((a) => typeof a === "string" && !a.startsWith("--")).slice(1); // drop template
const dirArg = flags.find((a) => a.startsWith('--dir='));
const subdirArg = flags.find((a) => a.startsWith('--subdir='));
const pathArg = flags.find((a) => a.startsWith('--path='));
const dirArg = flags.find((a) => a.startsWith("--dir="));
const subdirArg = flags.find((a) => a.startsWith("--subdir="));
const pathArg = flags.find((a) => a.startsWith("--path="));
const defaultBase =
template === 'react' ? 'apps/frontend/react' : 'apps/frontend/vue';
const defaultBase = template === "react" ? "apps/frontend/react" : "apps/frontend/vue";
let target;
if (pathArg) {
const rel = pathArg.slice('--path='.length);
target = path.resolve(process.cwd(), rel);
const rel = pathArg.slice("--path=".length);
target = path.resolve(process.cwd(), rel);
} else {
const name = positionals[0];
if (!name) {
console.error('请提供要清理的项目名。例如: pnpm run clean:vue my-app-vue');
process.exit(1);
}
let base = dirArg ? dirArg.slice('--dir='.length) : defaultBase;
if (subdirArg) {
base = path.join(base, subdirArg.slice('--subdir='.length));
}
target = path.resolve(process.cwd(), base, name);
const name = positionals[0];
if (!name) {
console.error("请提供要清理的项目名。例如: pnpm run clean:vue my-app-vue");
process.exit(1);
}
let base = dirArg ? dirArg.slice("--dir=".length) : defaultBase;
if (subdirArg) {
base = path.join(base, subdirArg.slice("--subdir=".length));
}
target = path.resolve(process.cwd(), base, name);
}
try {
if (!fs.existsSync(target)) {
console.log(`目标目录不存在,已跳过: ${target}`);
process.exit(0);
}
fs.rmSync(target, { recursive: true, force: true });
console.log(`已清理: ${target}`);
process.exit(0);
if (!fs.existsSync(target)) {
console.log(`目标目录不存在,已跳过: ${target}`);
process.exit(0);
}
fs.rmSync(target, { recursive: true, force: true });
console.log(`已清理: ${target}`);
process.exit(0);
} catch (error) {
console.error(`清理失败: ${error?.message || error}`);
process.exit(1);
console.error(`清理失败: ${error?.message || error}`);
process.exit(1);
}
import { exec, execSync } from 'node:child_process';
import { exec, execSync } from "node:child_process";
/**
* 方案 1: 使用 execSync + encoding(推荐)
* 同步执行,直接获取输出字符串
*/
function testCommandSync() {
console.log('📡 执行 ipconfig 命令...\n');
try {
// 设置 encoding: 'utf8' 来捕获输出
const output = execSync('ipconfig', {
encoding: 'utf8', // 将输出转为字符串
windowsHide: true, // Windows 下隐藏命令窗口
});
console.log('✅ 命令执行成功!\n');
console.log('📋 输出内容:');
console.log('─'.repeat(60));
console.log(output);
console.log('─'.repeat(60));
return output;
} catch (error) {
console.error(`❌ 命令执行失败: ${error.message}`);
console.error(`错误输出: ${error.stderr || '无'}`);
process.exit(1);
}
console.log("📡 执行 ipconfig 命令...\n");
try {
// 设置 encoding: 'utf8' 来捕获输出
const output = execSync("ipconfig", {
encoding: "utf8", // 将输出转为字符串
windowsHide: true, // Windows 下隐藏命令窗口
});
console.log("✅ 命令执行成功!\n");
console.log("📋 输出内容:");
console.log("─".repeat(60));
console.log(output);
console.log("─".repeat(60));
return output;
} catch (error) {
console.error(`❌ 命令执行失败: ${error.message}`);
console.error(`错误输出: ${error.stderr || "无"}`);
process.exit(1);
}
}
/**
......@@ -32,18 +32,18 @@ function testCommandSync() {
* 直接将输出显示到终端(实时输出)
*/
function testCommandInherit() {
console.log('📡 执行 ipconfig 命令(实时输出)...\n');
try {
execSync('ipconfig', {
stdio: 'inherit', // 继承父进程的输入输出
windowsHide: true,
});
console.log('\n✅ 命令执行完成!');
} catch (error) {
console.error(`❌ 命令执行失败: ${error.message}`);
process.exit(1);
}
console.log("📡 执行 ipconfig 命令(实时输出)...\n");
try {
execSync("ipconfig", {
stdio: "inherit", // 继承父进程的输入输出
windowsHide: true,
});
console.log("\n✅ 命令执行完成!");
} catch (error) {
console.error(`❌ 命令执行失败: ${error.message}`);
process.exit(1);
}
}
/**
......@@ -51,31 +51,31 @@ function testCommandInherit() {
* 可以同时获取 stdout 和 stderr
*/
function testCommandAsync() {
return new Promise((resolve, reject) => {
console.log('📡 执行 ipconfig 命令(异步方式)...\n');
exec('ipconfig', { encoding: 'utf8' }, (error, stdout, stderr) => {
if (error) {
console.error(`❌ 命令执行失败: ${error.message}`);
console.error(`错误输出: ${stderr}`);
reject(error);
return;
}
console.log('✅ 命令执行成功!\n');
console.log('📋 标准输出:');
console.log('─'.repeat(60));
console.log(stdout);
console.log('─'.repeat(60));
if (stderr) {
console.log('\n⚠️ 错误输出:');
console.log(stderr);
}
resolve(stdout);
});
});
return new Promise((resolve, reject) => {
console.log("📡 执行 ipconfig 命令(异步方式)...\n");
exec("ipconfig", { encoding: "utf8" }, (error, stdout, stderr) => {
if (error) {
console.error(`❌ 命令执行失败: ${error.message}`);
console.error(`错误输出: ${stderr}`);
reject(error);
return;
}
console.log("✅ 命令执行成功!\n");
console.log("📋 标准输出:");
console.log("─".repeat(60));
console.log(stdout);
console.log("─".repeat(60));
if (stderr) {
console.log("\n⚠️ 错误输出:");
console.log(stderr);
}
resolve(stdout);
});
});
}
/**
......@@ -83,65 +83,55 @@ function testCommandAsync() {
* 获取 IPv4 地址信息
*/
function testCommandWithFilter() {
console.log('📡 获取网络配置信息...\n');
try {
// Windows 下获取详细信息
const output = execSync('ipconfig', {
encoding: 'utf8',
windowsHide: true,
});
console.log('✅ 命令执行成功!\n');
// 解析并格式化输出
const lines = output.split('\n');
let currentAdapter = '';
console.log('🌐 网络适配器信息:');
console.log('═'.repeat(60));
lines.forEach((line) => {
const trimmedLine = line.trim();
// 检测适配器名称
if (
trimmedLine &&
!trimmedLine.startsWith(' ') &&
trimmedLine.includes(':')
) {
currentAdapter = trimmedLine;
console.log(`\n📶 ${currentAdapter}`);
}
// IPv4 地址
if (trimmedLine.includes('IPv4')) {
console.log(` ├─ ${trimmedLine}`);
}
// 子网掩码
if (
trimmedLine.includes('子网掩码') ||
trimmedLine.includes('Subnet Mask')
) {
console.log(` ├─ ${trimmedLine}`);
}
// 默认网关
if (
trimmedLine.includes('默认网关') ||
trimmedLine.includes('Default Gateway')
) {
console.log(` └─ ${trimmedLine}`);
}
});
console.log(`\n${'═'.repeat(60)}`);
return output;
} catch (error) {
console.error(`❌ 命令执行失败: ${error.message}`);
process.exit(1);
}
console.log("📡 获取网络配置信息...\n");
try {
// Windows 下获取详细信息
const output = execSync("ipconfig", {
encoding: "utf8",
windowsHide: true,
});
console.log("✅ 命令执行成功!\n");
// 解析并格式化输出
const lines = output.split("\n");
let currentAdapter = "";
console.log("🌐 网络适配器信息:");
console.log("═".repeat(60));
lines.forEach((line) => {
const trimmedLine = line.trim();
// 检测适配器名称
if (trimmedLine && !trimmedLine.startsWith(" ") && trimmedLine.includes(":")) {
currentAdapter = trimmedLine;
console.log(`\n📶 ${currentAdapter}`);
}
// IPv4 地址
if (trimmedLine.includes("IPv4")) {
console.log(` ├─ ${trimmedLine}`);
}
// 子网掩码
if (trimmedLine.includes("子网掩码") || trimmedLine.includes("Subnet Mask")) {
console.log(` ├─ ${trimmedLine}`);
}
// 默认网关
if (trimmedLine.includes("默认网关") || trimmedLine.includes("Default Gateway")) {
console.log(` └─ ${trimmedLine}`);
}
});
console.log(`\n${"═".repeat(60)}`);
return output;
} catch (error) {
console.error(`❌ 命令执行失败: ${error.message}`);
process.exit(1);
}
}
/**
......@@ -149,31 +139,31 @@ function testCommandWithFilter() {
* 可以选择不同的方案
*/
function testCommand() {
console.log('🚀 开始测试命令执行\n');
console.log("🚀 开始测试命令执行\n");
// 选择你想要的方案(取消注释对应的方案)
// 选择你想要的方案(取消注释对应的方案)
// 方案 1: 同步获取输出(推荐)✅
testCommandSync();
// 方案 1: 同步获取输出(推荐)✅
testCommandSync();
// 方案 2: 实时显示输出
// testCommandInherit();
// 方案 2: 实时显示输出
// testCommandInherit();
// 方案 3: 异步方式(需要在 main 中使用 await)
// return testCommandAsync();
// 方案 3: 异步方式(需要在 main 中使用 await)
// return testCommandAsync();
// 方案 4: 格式化输出
// testCommandWithFilter();
// 方案 4: 格式化输出
// testCommandWithFilter();
}
async function main() {
try {
await testCommand();
console.log('\n✨ 测试完成!');
} catch (error) {
console.error(`❌ 测试过程中出现错误: ${error.message}`);
process.exit(1);
}
try {
await testCommand();
console.log("\n✨ 测试完成!");
} catch (error) {
console.error(`❌ 测试过程中出现错误: ${error.message}`);
process.exit(1);
}
}
// 执行主函数
......
......@@ -10,104 +10,106 @@
* On POSIX: write venus (bash) with executable permission
*/
const cp = require('node:child_process');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const cp = require("node:child_process");
const fs = require("node:fs");
const os = require("node:os");
const path = require("node:path");
function log(msg) {
console.log(`[createShims] ${msg}`);
console.log(`[createShims] ${msg}`);
}
function safeExec(cmd) {
try {
const out = cp
.execSync(cmd, { stdio: ['ignore', 'pipe', 'pipe'] })
.toString()
.trim();
return out;
} catch {
return '';
}
try {
const out = cp
.execSync(cmd, { stdio: ["ignore", "pipe", "pipe"] })
.toString()
.trim();
return out;
} catch {
return "";
}
}
function ensureDir(dir) {
try {
fs.mkdirSync(dir, { recursive: true });
} catch {
// ignore
}
try {
fs.mkdirSync(dir, { recursive: true });
} catch {
// ignore
}
}
function writeFile(filePath, content, mode) {
ensureDir(path.dirname(filePath));
fs.writeFileSync(filePath, content, 'utf8');
if (mode) {
try {
fs.chmodSync(filePath, mode);
} catch {}
}
log(`wrote shim: ${filePath}`);
ensureDir(path.dirname(filePath));
fs.writeFileSync(filePath, content, "utf8");
if (mode) {
try {
fs.chmodSync(filePath, mode);
} catch {}
}
log(`wrote shim: ${filePath}`);
}
function main() {
const repoRoot = process.cwd();
const entry = path.resolve(repoRoot, 'packages/cli/dist/index.cjs.js');
const isWin = process.platform === 'win32';
if (!fs.existsSync(entry)) {
log(`entry not found: ${entry}`);
log('skip creating shims (CLI not built yet).');
return;
}
// Prefer pnpm reported global bin, then common fallback dirs
const pnpmGlobalBin = safeExec('pnpm bin -g');
const candidates = [];
if (pnpmGlobalBin) candidates.push(pnpmGlobalBin);
if (isWin) {
// Common Node.js global bin location added to PATH by many installers
candidates.push(path.join(os.homedir(), 'AppData', 'Roaming', 'npm'));
} else {
// Common pnpm homes on POSIX
candidates.push(path.join(os.homedir(), '.local', 'share', 'pnpm'));
candidates.push(path.join(os.homedir(), 'Library', 'pnpm')); // macOS
}
// De-duplicate and keep only existing dirs
const dirs = [...new Set(candidates)].filter((d) => {
try {
return fs.existsSync(d);
} catch {
return false;
}
});
if (dirs.length === 0) {
log('no global bin directories found.');
log('you may need to run `pnpm setup` to add PNPM_HOME to PATH.');
return;
}
for (const dir of dirs) {
try {
if (isWin) {
const cmdBody = `@echo off\r\nnode "${entry}" %*`;
writeFile(path.join(dir, 'venus.cmd'), cmdBody);
const ps1Body = `& node "${entry}" $args`;
writeFile(path.join(dir, 'venus.ps1'), ps1Body);
} else {
const bashBody = `#!/usr/bin/env bash\nnode "${entry}" "$@"`;
writeFile(path.join(dir, 'venus'), bashBody, 0o755);
}
} catch (error) {
log(`failed to write into ${dir}: ${error && error.message}`);
}
}
log('done.');
const repoRoot = process.cwd();
const entry = path.resolve(repoRoot, "packages/cli/dist/index.cjs.js");
const isWin = process.platform === "win32";
if (!fs.existsSync(entry)) {
log(`entry not found: ${entry}`);
log("skip creating shims (CLI not built yet).");
return;
}
// Prefer pnpm reported global bin, then common fallback dirs
const pnpmGlobalBin = safeExec("pnpm bin -g");
const candidates = [];
if (pnpmGlobalBin) candidates.push(pnpmGlobalBin);
if (isWin) {
// Common Node.js global bin location added to PATH by many installers
candidates.push(path.join(os.homedir(), "AppData", "Roaming", "npm"));
} else {
// Common pnpm homes on POSIX
candidates.push(
path.join(os.homedir(), ".local", "share", "pnpm"),
path.join(os.homedir(), "Library", "pnpm"), // macOS
);
}
// De-duplicate and keep only existing dirs
const dirs = [...new Set(candidates)].filter((d) => {
try {
return fs.existsSync(d);
} catch {
return false;
}
});
if (dirs.length === 0) {
log("no global bin directories found.");
log("you may need to run `pnpm setup` to add PNPM_HOME to PATH.");
return;
}
for (const dir of dirs) {
try {
if (isWin) {
const cmdBody = `@echo off\r\nnode "${entry}" %*`;
writeFile(path.join(dir, "venus.cmd"), cmdBody);
const ps1Body = `& node "${entry}" $args`;
writeFile(path.join(dir, "venus.ps1"), ps1Body);
} else {
const bashBody = `#!/usr/bin/env bash\nnode "${entry}" "$@"`;
writeFile(path.join(dir, "venus"), bashBody, 0o755);
}
} catch (error) {
log(`failed to write into ${dir}: ${error && error.message}`);
}
}
log("done.");
}
main();
import { watch } from 'rollup';
import { watch } from "rollup";
import { getRollupConfigs } from './buildBase.js';
import { getRollupConfigs } from "./buildBase.js";
async function dev() {
const configs = await getRollupConfigs();
for (const name of Object.keys(configs)) {
const config = configs[name];
const watcher = watch(
config.output.map((o) => ({
input: config.input,
plugins: [...config.plugins],
external: config.external,
output: o,
watch: config.watch,
})),
);
watcher.on('event', (event) => {
switch (event.code) {
case 'BUNDLE_END': {
console.log(`打包完成: ${name}`);
const configs = await getRollupConfigs();
for (const name of Object.keys(configs)) {
const config = configs[name];
const watcher = watch(
config.output.map((o) => ({
input: config.input,
plugins: [...config.plugins],
external: config.external,
output: o,
watch: config.watch,
})),
);
watcher.on("event", (event) => {
switch (event.code) {
case "BUNDLE_END": {
console.log(`打包完成: ${name}`);
break;
}
case 'BUNDLE_START': {
console.log(`开始打包: ${name}`);
break;
}
case "BUNDLE_START": {
console.log(`开始打包: ${name}`);
break;
}
case 'ERROR': {
console.error(`打包失败: ${name}`, event.error);
break;
}
case "ERROR": {
console.error(`打包失败: ${name}`, event.error);
break;
}
case 'START': {
console.log(`开始监听: ${name}`);
break;
}
case "START": {
console.log(`开始监听: ${name}`);
break;
}
// No default
}
});
}
break;
}
// No default
}
});
}
}
dev();
import { promises as fs } from 'node:fs';
import { join, normalize } from 'node:path';
import { promises as fs } from "node:fs";
import { join, normalize } from "node:path";
const rootDir = process.cwd();
......@@ -7,7 +7,7 @@ const rootDir = process.cwd();
const CONCURRENCY_LIMIT = 10;
// 需要跳过的目录,避免进入这些目录进行清理
const SKIP_DIRS = new Set(['.DS_Store', '.git', '.idea', '.vscode']);
const SKIP_DIRS = new Set([".DS_Store", ".git", ".idea", ".vscode"]);
/**
* 处理单个文件/目录项
......@@ -18,37 +18,35 @@ const SKIP_DIRS = new Set(['.DS_Store', '.git', '.idea', '.vscode']);
* @returns {Promise<boolean>} - 是否需要进一步递归处理
*/
async function processItem(currentDir, item, targets, _depth) {
// 跳过特殊目录
if (SKIP_DIRS.has(item)) {
return false;
}
try {
const itemPath = normalize(join(currentDir, item));
if (targets.includes(item)) {
// 匹配到目标目录或文件时直接删除
await fs.rm(itemPath, { force: true, recursive: true });
console.log(`✅ Deleted: ${itemPath}`);
return false; // 已删除,无需递归
}
// 使用 readdir 的 withFileTypes 选项,避免额外的 lstat 调用
return true; // 可能需要递归,由调用方决定
} catch (error) {
// 更详细的错误信息
if (error.code === 'ENOENT') {
// 文件不存在,可能已被删除,这是正常情况
return false;
} else if (error.code === 'EPERM' || error.code === 'EACCES') {
console.error(`❌ Permission denied: ${item} in ${currentDir}`);
} else {
console.error(
`❌ Error handling item ${item} in ${currentDir}: ${error.message}`,
);
}
return false;
}
// 跳过特殊目录
if (SKIP_DIRS.has(item)) {
return false;
}
try {
const itemPath = normalize(join(currentDir, item));
if (targets.includes(item)) {
// 匹配到目标目录或文件时直接删除
await fs.rm(itemPath, { force: true, recursive: true });
console.log(`✅ Deleted: ${itemPath}`);
return false; // 已删除,无需递归
}
// 使用 readdir 的 withFileTypes 选项,避免额外的 lstat 调用
return true; // 可能需要递归,由调用方决定
} catch (error) {
// 更详细的错误信息
if (error.code === "ENOENT") {
// 文件不存在,可能已被删除,这是正常情况
return false;
} else if (error.code === "EPERM" || error.code === "EACCES") {
console.error(`❌ Permission denied: ${item} in ${currentDir}`);
} else {
console.error(`❌ Error handling item ${item} in ${currentDir}: ${error.message}`);
}
return false;
}
}
/**
......@@ -58,84 +56,78 @@ async function processItem(currentDir, item, targets, _depth) {
* @param {number} depth - 当前递归深度,避免过深递归
*/
async function cleanTargetsRecursively(currentDir, targets, depth = 0) {
// 限制递归深度,避免无限递归
if (depth > 10) {
console.warn(`Max recursion depth reached at: ${currentDir}`);
return;
}
let dirents;
try {
// 使用 withFileTypes 选项,一次性获取文件类型信息,避免后续 lstat 调用
dirents = await fs.readdir(currentDir, { withFileTypes: true });
} catch (error) {
// 如果无法读取目录,可能已被删除或权限不足
console.warn(`Cannot read directory ${currentDir}: ${error.message}`);
return;
}
// 分批处理,控制并发数量
for (let i = 0; i < dirents.length; i += CONCURRENCY_LIMIT) {
const batch = dirents.slice(i, i + CONCURRENCY_LIMIT);
const tasks = batch.map(async (dirent) => {
const item = dirent.name;
const shouldRecurse = await processItem(currentDir, item, targets, depth);
// 如果是目录且没有被删除,则递归处理
if (shouldRecurse && dirent.isDirectory()) {
const itemPath = normalize(join(currentDir, item));
return cleanTargetsRecursively(itemPath, targets, depth + 1);
}
return null;
});
// 并发执行当前批次的任务
const results = await Promise.allSettled(tasks);
// 检查是否有失败的任务(可选:用于调试)
const failedTasks = results.filter(
(result) => result.status === 'rejected',
);
if (failedTasks.length > 0) {
console.warn(
`${failedTasks.length} tasks failed in batch starting at index ${i} in directory: ${currentDir}`,
);
}
}
// 限制递归深度,避免无限递归
if (depth > 10) {
console.warn(`Max recursion depth reached at: ${currentDir}`);
return;
}
let dirents;
try {
// 使用 withFileTypes 选项,一次性获取文件类型信息,避免后续 lstat 调用
dirents = await fs.readdir(currentDir, { withFileTypes: true });
} catch (error) {
// 如果无法读取目录,可能已被删除或权限不足
console.warn(`Cannot read directory ${currentDir}: ${error.message}`);
return;
}
// 分批处理,控制并发数量
for (let i = 0; i < dirents.length; i += CONCURRENCY_LIMIT) {
const batch = dirents.slice(i, i + CONCURRENCY_LIMIT);
const tasks = batch.map(async (dirent) => {
const item = dirent.name;
const shouldRecurse = await processItem(currentDir, item, targets, depth);
// 如果是目录且没有被删除,则递归处理
if (shouldRecurse && dirent.isDirectory()) {
const itemPath = normalize(join(currentDir, item));
return cleanTargetsRecursively(itemPath, targets, depth + 1);
}
return null;
});
// 并发执行当前批次的任务
const results = await Promise.allSettled(tasks);
// 检查是否有失败的任务(可选:用于调试)
const failedTasks = results.filter((result) => result.status === "rejected");
if (failedTasks.length > 0) {
console.warn(
`${failedTasks.length} tasks failed in batch starting at index ${i} in directory: ${currentDir}`,
);
}
}
}
(async function startCleanup() {
// 要删除的目录及文件名称
const targets = ['node_modules', 'dist', '.turbo', 'dist.zip'];
const deleteLockFile = process.argv.includes('--del-lock');
const cleanupTargets = [...targets];
// 要删除的目录及文件名称
const targets = ["node_modules", "dist", ".turbo", "dist.zip"];
const deleteLockFile = process.argv.includes("--del-lock");
const cleanupTargets = [...targets];
if (deleteLockFile) {
cleanupTargets.push('pnpm-lock.yaml');
}
if (deleteLockFile) {
cleanupTargets.push("pnpm-lock.yaml");
}
console.log(
`🚀 Starting cleanup of targets: ${cleanupTargets.join(', ')} from root: ${rootDir}`,
);
console.log(`🚀 Starting cleanup of targets: ${cleanupTargets.join(", ")} from root: ${rootDir}`);
const startTime = Date.now();
const startTime = Date.now();
try {
// 先统计要删除的目标数量
console.log('📊 Scanning for cleanup targets...');
try {
// 先统计要删除的目标数量
console.log("📊 Scanning for cleanup targets...");
await cleanTargetsRecursively(rootDir, cleanupTargets);
await cleanTargetsRecursively(rootDir, cleanupTargets);
const endTime = Date.now();
const duration = (endTime - startTime) / 1000;
const endTime = Date.now();
const duration = (endTime - startTime) / 1000;
console.log(
`✨ Cleanup process completed successfully in ${duration.toFixed(2)}s`,
);
} catch (error) {
console.error(`💥 Unexpected error during cleanup: ${error.message}`);
process.exit(1);
}
console.log(`✨ Cleanup process completed successfully in ${duration.toFixed(2)}s`);
} catch (error) {
console.error(`💥 Unexpected error during cleanup: ${error.message}`);
process.exit(1);
}
})();
......@@ -2,35 +2,34 @@
* 将当前项目的 dist 文件夹复制到 根目录的 dist 文件夹
* 用于 postbuild 钩子
*/
import { existsSync, rmSync, cpSync } from 'node:fs';
import { join, dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { cpSync, existsSync, rmSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
// 获取项目根目录(scripts 的父目录)
const venusProRoot = resolve(__dirname, '..');
const rootDistDir = join(venusProRoot, 'dist');
console.log('目根目录', venusProRoot);
console.log('输出路径', rootDistDir);
const venusProRoot = resolve(__dirname, "..");
const rootDistDir = join(venusProRoot, "dist");
console.log("目根目录", venusProRoot);
console.log("输出路径", rootDistDir);
// 获取当前包的工作目录
// pnpm 在执行 postbuild 时,工作目录就是包的目录
const packageDir = process.cwd();
const sourceDistDir = join(packageDir, 'dist');
const sourceDistDir = join(packageDir, "dist");
if (!existsSync(sourceDistDir)) {
console.error(`❌ 构建产物不存在: ${sourceDistDir}`);
process.exit(1);
console.error(`❌ 构建产物不存在: ${sourceDistDir}`);
process.exit(1);
}
// 清理 根目录的 dist(如果存在)
if (existsSync(rootDistDir)) {
rmSync(rootDistDir, { recursive: true, force: true });
rmSync(rootDistDir, { recursive: true, force: true });
}
// 复制 dist 到根目录的 dist 文件夹
cpSync(sourceDistDir, rootDistDir, { recursive: true });
console.log(`✅ 已将构建产物复制到根目录: ${rootDistDir}`);
import { getRollupConfigs } from "./buildBase.js";
import { watch } from "rollup";
import { getRollupConfigs } from "./buildBase.js";
async function dev() {
const configs = await getRollupConfigs();
for (const name of Object.keys(configs)) {
const config = configs[name];
const watcher = watch(
config.output.map(o => ({
input: config.input,
plugins: [...config.plugins],
external: config.external,
output: o,
watch: config.watch
}))
);
watcher.on("event", event => {
if (event.code === "START") {
console.log(`开始监听: ${name}`);
} else if (event.code === "ERROR") {
console.error(`打包失败: ${name}`, event.error);
} else if (event.code === "BUNDLE_START") {
console.log(`开始打包: ${name}`);
} else if (event.code === "BUNDLE_END") {
console.log(`打包完成: ${name}`);
}
});
}
const configs = await getRollupConfigs();
for (const name of Object.keys(configs)) {
const config = configs[name];
const watcher = watch(
config.output.map((o) => ({
input: config.input,
plugins: [...config.plugins],
external: config.external,
output: o,
watch: config.watch,
})),
);
watcher.on("event", (event) => {
switch (event.code) {
case "BUNDLE_END": {
console.log(`打包完成: ${name}`);
break;
}
case "BUNDLE_START": {
console.log(`开始打包: ${name}`);
break;
}
case "ERROR": {
console.error(`打包失败: ${name}`, event.error);
break;
}
case "START": {
console.log(`开始监听: ${name}`);
break;
}
// No default
}
});
}
}
dev();
#!/usr/bin/env node
import('../dist/index.mjs');
import("../dist/index.mjs");
import { defineBuildConfig } from 'unbuild';
import { defineBuildConfig } from "unbuild";
export default defineBuildConfig({
clean: true,
declaration: true,
entries: ['src/index'],
clean: true,
declaration: true,
entries: ["src/index"],
});
{
"name": "@venus/turbo-run",
"version": "5.5.9",
"private": true,
"license": "MIT",
"type": "module",
"scripts": {
"stub": "pnpm unbuild --stub"
},
"files": [
"dist"
],
"bin": {
"turbo-run": "./bin/turbo-run.mjs"
},
"main": "./dist/index.mjs",
"module": "./dist/index.mjs",
"exports": {
".": {
"default": "./dist/index.mjs"
},
"./package.json": "./package.json"
},
"dependencies": {
"@clack/prompts": "catalog:",
"@venus/node-utils": "workspace:*",
"cac": "catalog:"
}
"name": "@venus/turbo-run",
"version": "5.5.9",
"private": true,
"license": "MIT",
"type": "module",
"scripts": {
"stub": "pnpm unbuild --stub"
},
"files": [
"dist"
],
"bin": {
"turbo-run": "./bin/turbo-run.mjs"
},
"main": "./dist/index.mjs",
"module": "./dist/index.mjs",
"exports": {
".": {
"default": "./dist/index.mjs"
},
"./package.json": "./package.json"
},
"dependencies": {
"@clack/prompts": "catalog:",
"@venus/node-utils": "workspace:*",
"cac": "catalog:"
}
}
import { colors, consola } from '@venus/node-utils';
import { colors, consola } from "@venus/node-utils";
import { cac } from 'cac';
import { cac } from "cac";
import { run } from './run';
import { run } from "./run";
try {
const turboRun = cac('turbo-run');
console.log(process.argv);
turboRun
.command('[script]')
.usage(`Run turbo interactively.`)
.option('--filter <package>', 'Filter by package name')
.action(async (command: string, options: { filter?: string }) => {
run({ command, filter: options.filter });
});
// Invalid command
turboRun.on('command:*', () => {
consola.error(colors.red('Invalid command!'));
process.exit(1);
});
const turboRun = cac("turbo-run");
console.log(process.argv);
turboRun
.command("[script]")
.usage(`Run turbo interactively.`)
.option("--filter <package>", "Filter by package name")
.action(async (command: string, options: { filter?: string }) => {
run({ command, filter: options.filter });
});
// Invalid command
turboRun.on("command:*", () => {
consola.error(colors.red("Invalid command!"));
process.exit(1);
});
turboRun.usage('turbo-run');
turboRun.help();
turboRun.parse();
turboRun.usage("turbo-run");
turboRun.help();
turboRun.parse();
} catch (error) {
consola.error(error);
process.exit(1);
consola.error(error);
process.exit(1);
}
import { execaCommand, getPackages } from '@venus/node-utils';
import { execaCommand, getPackages } from "@venus/node-utils";
import { cancel, isCancel, select } from '@clack/prompts';
import { cancel, isCancel, select } from "@clack/prompts";
interface RunOptions {
command?: string;
filter?: string;
command?: string;
filter?: string;
}
export async function run(options: RunOptions) {
const { command, filter } = options;
if (!command) {
console.error('Please enter the command to run');
process.exit(1);
}
const { command, filter } = options;
if (!command) {
console.error("Please enter the command to run");
process.exit(1);
}
// 如果指定了 filter,直接使用,不进行交互式选择
if (filter) {
console.log(`Running [${command}] on package: ${filter}`);
execaCommand(`pnpm --filter=${filter} run ${command}`, {
stdio: 'inherit',
});
return;
}
// 如果指定了 filter,直接使用,不进行交互式选择
if (filter) {
console.log(`Running [${command}] on package: ${filter}`);
execaCommand(`pnpm --filter=${filter} run ${command}`, {
stdio: "inherit",
});
return;
}
const { packages } = await getPackages();
// const appPkgs = await findApps(process.cwd(), packages);
// const websitePkg = packages.find(
// (item) => item.packageJson.name === '@venus/website',
// );
const { packages } = await getPackages();
// const appPkgs = await findApps(process.cwd(), packages);
// const websitePkg = packages.find(
// (item) => item.packageJson.name === '@venus/website',
// );
// 只显示有对应命令的包
const selectPkgs = packages.filter((pkg) => {
return (pkg?.packageJson as Record<string, any>)?.scripts?.[command];
});
// 只显示有对应命令的包
const selectPkgs = packages.filter((pkg) => {
return (pkg?.packageJson as Record<string, any>)?.scripts?.[command];
});
let selectPkg: string | symbol;
if (selectPkgs.length > 1) {
console.log('selectPkgs', selectPkgs);
selectPkg = await select<string>({
message: `Select the app you need to run [${command}]:`,
options: selectPkgs.map((item) => ({
label: item?.packageJson.name,
value: item?.packageJson.name,
})),
});
let selectPkg: string | symbol;
if (selectPkgs.length > 1) {
console.log("selectPkgs", selectPkgs);
selectPkg = await select<string>({
message: `Select the app you need to run [${command}]:`,
options: selectPkgs.map((item) => ({
label: item?.packageJson.name,
value: item?.packageJson.name,
})),
});
if (isCancel(selectPkg) || !selectPkg) {
cancel('👋 Has cancelled');
process.exit(0);
}
} else {
selectPkg = selectPkgs[0]?.packageJson?.name ?? '';
}
if (isCancel(selectPkg) || !selectPkg) {
cancel("👋 Has cancelled");
process.exit(0);
}
} else {
selectPkg = selectPkgs[0]?.packageJson?.name ?? "";
}
if (!selectPkg) {
console.error('No app found');
process.exit(1);
}
if (!selectPkg) {
console.error("No app found");
process.exit(1);
}
execaCommand(`pnpm --filter=${selectPkg} run ${command}`, {
stdio: 'inherit',
});
execaCommand(`pnpm --filter=${selectPkg} run ${command}`, {
stdio: "inherit",
});
}
/**
......
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@venus/tsconfig/node.json",
"include": ["src"],
"exclude": ["node_modules"]
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@venus/tsconfig/node.json",
"include": ["src"],
"exclude": ["node_modules"]
}
......@@ -48,6 +48,7 @@ vsh [command]
# 运行命令
pnpm vsh [command]
```
涵盖场景:
代码质量:lint
包发布:publint
......
#!/usr/bin/env node
import('../dist/index.mjs');
import("../dist/index.mjs");
import { defineBuildConfig } from 'unbuild';
import { defineBuildConfig } from "unbuild";
export default defineBuildConfig({
clean: true,
declaration: true,
entries: ['src/index'],
clean: true,
declaration: true,
entries: ["src/index"],
});
{
"name": "@venus/vsh",
"version": "5.5.9",
"private": true,
"license": "MIT",
"type": "module",
"scripts": {
"stub": "pnpm unbuild --stub"
},
"files": [
"dist"
],
"bin": {
"vsh": "./bin/vsh.mjs"
},
"main": "./dist/index.mjs",
"module": "./dist/index.mjs",
"exports": {
".": {
"default": "./dist/index.mjs"
},
"./package.json": "./package.json"
},
"dependencies": {
"@venus/node-utils": "workspace:*",
"cac": "catalog:",
"circular-dependency-scanner": "catalog:",
"depcheck": "catalog:",
"publint": "catalog:"
}
"name": "@venus/vsh",
"version": "5.5.9",
"private": true,
"license": "MIT",
"type": "module",
"scripts": {
"stub": "pnpm unbuild --stub"
},
"files": [
"dist"
],
"bin": {
"vsh": "./bin/vsh.mjs"
},
"main": "./dist/index.mjs",
"module": "./dist/index.mjs",
"exports": {
".": {
"default": "./dist/index.mjs"
},
"./package.json": "./package.json"
},
"dependencies": {
"@venus/node-utils": "workspace:*",
"cac": "catalog:",
"circular-dependency-scanner": "catalog:",
"depcheck": "catalog:",
"publint": "catalog:"
}
}
import type { CAC } from 'cac';
import type { CAC } from "cac";
import { extname } from 'node:path';
import { extname } from "node:path";
import { getStagedFiles } from '@venus/node-utils';
import { getStagedFiles } from "@venus/node-utils";
import { circularDepsDetect } from 'circular-dependency-scanner';
import { circularDepsDetect } from "circular-dependency-scanner";
// 默认配置
const DEFAULT_CONFIG = {
allowedExtensions: ['.cjs', '.js', '.jsx', '.mjs', '.ts', '.tsx', '.vue'],
ignoreDirs: ['dist', '.turbo', 'output', '.cache', 'scripts', 'internal'],
threshold: 0, // 循环依赖的阈值
allowedExtensions: [".cjs", ".js", ".jsx", ".mjs", ".ts", ".tsx", ".vue"],
ignoreDirs: ["dist", ".turbo", "output", ".cache", "scripts", "internal"],
threshold: 0, // 循环依赖的阈值
} as const;
// 类型定义
type CircularDependencyResult = string[];
interface CheckCircularConfig {
allowedExtensions?: string[];
ignoreDirs?: string[];
threshold?: number;
allowedExtensions?: string[];
ignoreDirs?: string[];
threshold?: number;
}
interface CommandOptions {
config?: CheckCircularConfig;
staged: boolean;
verbose: boolean;
config?: CheckCircularConfig;
staged: boolean;
verbose: boolean;
}
// 缓存机制
......@@ -36,16 +36,16 @@ const cache = new Map<string, CircularDependencyResult[]>();
* @param circles - 循环依赖结果
*/
function formatCircles(circles: CircularDependencyResult[]): void {
if (circles.length === 0) {
console.log('✅ No circular dependencies found');
return;
}
console.log('⚠️ Circular dependencies found:');
circles.forEach((circle, index) => {
console.log(`\nCircular dependency #${index + 1}:`);
circle.forEach((file) => console.log(` → ${file}`));
});
if (circles.length === 0) {
console.log("✅ No circular dependencies found");
return;
}
console.log("⚠️ Circular dependencies found:");
circles.forEach((circle, index) => {
console.log(`\nCircular dependency #${index + 1}:`);
circle.forEach((file) => console.log(` → ${file}`));
});
}
/**
......@@ -56,77 +56,68 @@ function formatCircles(circles: CircularDependencyResult[]): void {
* @param options.config - 自定义配置
* @returns Promise<void>
*/
async function checkCircular({
config = {},
staged,
verbose,
}: CommandOptions): Promise<void> {
try {
// 合并配置
const finalConfig = {
...DEFAULT_CONFIG,
...config,
};
// 生成忽略模式
const ignorePattern = `**/{${finalConfig.ignoreDirs.join(',')}}/**`;
// 检查缓存
const cacheKey = `${staged}-${process.cwd()}-${ignorePattern}`;
if (cache.has(cacheKey)) {
const cachedResults = cache.get(cacheKey);
if (cachedResults) {
verbose && formatCircles(cachedResults);
}
return;
}
// 检测循环依赖
const results = await circularDepsDetect({
absolute: staged,
cwd: process.cwd(),
ignore: [ignorePattern],
});
if (staged) {
let files = await getStagedFiles();
const allowedExtensions = new Set(finalConfig.allowedExtensions);
// 过滤文件列表
files = files.filter((file) => allowedExtensions.has(extname(file)));
const circularFiles: CircularDependencyResult[] = [];
for (const file of files) {
for (const result of results) {
const resultFiles = result.flat();
if (resultFiles.includes(file)) {
circularFiles.push(result);
}
}
}
// 更新缓存
cache.set(cacheKey, circularFiles);
verbose && formatCircles(circularFiles);
} else {
// 更新缓存
cache.set(cacheKey, results);
verbose && formatCircles(results);
}
// 如果发现循环依赖,只输出警告信息
if (results.length > 0) {
console.log(
'\n⚠️ Warning: Circular dependencies found, please check and fix',
);
}
} catch (error) {
console.error(
'❌ Error checking circular dependencies:',
error instanceof Error ? error.message : error,
);
}
async function checkCircular({ config = {}, staged, verbose }: CommandOptions): Promise<void> {
try {
// 合并配置
const finalConfig = {
...DEFAULT_CONFIG,
...config,
};
// 生成忽略模式
const ignorePattern = `**/{${finalConfig.ignoreDirs.join(",")}}/**`;
// 检查缓存
const cacheKey = `${staged}-${process.cwd()}-${ignorePattern}`;
if (cache.has(cacheKey)) {
const cachedResults = cache.get(cacheKey);
if (cachedResults) {
verbose && formatCircles(cachedResults);
}
return;
}
// 检测循环依赖
const results = await circularDepsDetect({
absolute: staged,
cwd: process.cwd(),
ignore: [ignorePattern],
});
if (staged) {
let files = await getStagedFiles();
const allowedExtensions = new Set(finalConfig.allowedExtensions);
// 过滤文件列表
files = files.filter((file) => allowedExtensions.has(extname(file)));
const circularFiles: CircularDependencyResult[] = [];
for (const file of files) {
for (const result of results) {
const resultFiles = result.flat();
if (resultFiles.includes(file)) {
circularFiles.push(result);
}
}
}
// 更新缓存
cache.set(cacheKey, circularFiles);
verbose && formatCircles(circularFiles);
} else {
// 更新缓存
cache.set(cacheKey, results);
verbose && formatCircles(results);
}
// 如果发现循环依赖,只输出警告信息
if (results.length > 0) {
console.log("\n⚠️ Warning: Circular dependencies found, please check and fix");
}
} catch (error) {
console.error("❌ Error checking circular dependencies:", error instanceof Error ? error.message : error);
}
}
/**
......@@ -134,27 +125,26 @@ async function checkCircular({
* @param cac - CAC实例
*/
function defineCheckCircularCommand(cac: CAC): void {
cac
.command('check-circular')
.option('--staged', 'Only check staged files')
.option('--verbose', 'Show detailed information')
.option('--threshold <number>', 'Threshold for circular dependencies', {
default: 0,
})
.option('--ignore-dirs <dirs>', 'Directories to ignore, comma separated')
.usage('Analyze project circular dependencies')
.action(async ({ ignoreDirs, staged, threshold, verbose }) => {
const config: CheckCircularConfig = {
threshold: Number(threshold),
...(ignoreDirs && { ignoreDirs: ignoreDirs.split(',') }),
};
await checkCircular({
config,
staged,
verbose: verbose ?? true,
});
});
cac.command("check-circular")
.option("--staged", "Only check staged files")
.option("--verbose", "Show detailed information")
.option("--threshold <number>", "Threshold for circular dependencies", {
default: 0,
})
.option("--ignore-dirs <dirs>", "Directories to ignore, comma separated")
.usage("Analyze project circular dependencies")
.action(async ({ ignoreDirs, staged, threshold, verbose }) => {
const config: CheckCircularConfig = {
threshold: Number(threshold),
...(ignoreDirs && { ignoreDirs: ignoreDirs.split(",") }),
};
await checkCircular({
config,
staged,
verbose: verbose ?? true,
});
});
}
export { type CheckCircularConfig, defineCheckCircularCommand };
import type { CAC } from 'cac';
import type { CAC } from "cac";
import { getPackages } from '@venus/node-utils';
import { getPackages } from "@venus/node-utils";
import depcheck from 'depcheck';
import depcheck from "depcheck";
// 默认配置
const DEFAULT_CONFIG = {
// 需要忽略的依赖匹配
ignoreMatches: [
'vite',
'vitest',
'unbuild',
'@venus/tsconfig',
'@venus/tailwind-config',
'@types/*',
'@venus/design',
],
// 需要忽略的包
ignorePackages: [
'@venus/backend-mock',
'@venus/commitlint-config',
'@venus/eslint-config',
'@venus/node-utils',
'@venus/prettier-config',
'@venus/stylelint-config',
'@venus/tailwind-config',
'@venus/tsconfig',
'@venus/vsh',
],
// 需要忽略的文件模式
ignorePatterns: ['dist', 'node_modules', 'public'],
// 需要忽略的依赖匹配
ignoreMatches: [
"vite",
"vitest",
"unbuild",
"@venus/tsconfig",
"@venus/tailwind-config",
"@types/*",
"@venus/design",
],
// 需要忽略的包
ignorePackages: [
"@venus/backend-mock",
"@venus/commitlint-config",
"@venus/eslint-config",
"@venus/node-utils",
"@venus/prettier-config",
"@venus/stylelint-config",
"@venus/tailwind-config",
"@venus/tsconfig",
"@venus/vsh",
],
// 需要忽略的文件模式
ignorePatterns: ["dist", "node_modules", "public"],
};
interface DepcheckResult {
dependencies: string[];
devDependencies: string[];
missing: Record<string, string[]>;
dependencies: string[];
devDependencies: string[];
missing: Record<string, string[]>;
}
interface DepcheckConfig {
ignoreMatches?: string[];
ignorePackages?: string[];
ignorePatterns?: string[];
ignoreMatches?: string[];
ignorePackages?: string[];
ignorePatterns?: string[];
}
interface PackageInfo {
dir: string;
packageJson: {
name: string;
};
dir: string;
packageJson: {
name: string;
};
}
/**
......@@ -56,18 +56,16 @@ interface PackageInfo {
* @param unused - 依赖检查结果
*/
function cleanDepcheckResult(unused: DepcheckResult): void {
// 删除file:前缀的依赖提示,该依赖是本地依赖
Reflect.deleteProperty(unused.missing, 'file:');
// 清理路径依赖
Object.keys(unused.missing).forEach((key) => {
unused.missing[key] = (unused.missing[key] || []).filter(
(item: string) => !item.startsWith('/'),
);
if (unused.missing[key].length === 0) {
Reflect.deleteProperty(unused.missing, key);
}
});
// 删除file:前缀的依赖提示,该依赖是本地依赖
Reflect.deleteProperty(unused.missing, "file:");
// 清理路径依赖
Object.keys(unused.missing).forEach((key) => {
unused.missing[key] = (unused.missing[key] || []).filter((item: string) => !item.startsWith("/"));
if (unused.missing[key].length === 0) {
Reflect.deleteProperty(unused.missing, key);
}
});
}
/**
......@@ -76,34 +74,32 @@ function cleanDepcheckResult(unused: DepcheckResult): void {
* @param unused - 依赖检查结果
*/
function formatDepcheckResult(pkgName: string, unused: DepcheckResult): void {
const hasIssues =
Object.keys(unused.missing).length > 0 ||
unused.dependencies.length > 0 ||
unused.devDependencies.length > 0;
if (!hasIssues) {
return;
}
console.log('\n📦 Package:', pkgName);
if (Object.keys(unused.missing).length > 0) {
console.log('❌ Missing dependencies:');
Object.entries(unused.missing).forEach(([dep, files]) => {
console.log(` - ${dep}:`);
files.forEach((file) => console.log(` 📄 ${file}`));
});
}
if (unused.dependencies.length > 0) {
console.log('⚠️ Unused dependencies:');
unused.dependencies.forEach((dep) => console.log(` - ${dep}`));
}
if (unused.devDependencies.length > 0) {
console.log('⚠️ Unused devDependencies:');
unused.devDependencies.forEach((dep) => console.log(` - ${dep}`));
}
const hasIssues =
Object.keys(unused.missing).length > 0 || unused.dependencies.length > 0 || unused.devDependencies.length > 0;
if (!hasIssues) {
return;
}
console.log("\n📦 Package:", pkgName);
if (Object.keys(unused.missing).length > 0) {
console.log("❌ Missing dependencies:");
Object.entries(unused.missing).forEach(([dep, files]) => {
console.log(` - ${dep}:`);
files.forEach((file) => console.log(` 📄 ${file}`));
});
}
if (unused.dependencies.length > 0) {
console.log("⚠️ Unused dependencies:");
unused.dependencies.forEach((dep) => console.log(` - ${dep}`));
}
if (unused.devDependencies.length > 0) {
console.log("⚠️ Unused devDependencies:");
unused.devDependencies.forEach((dep) => console.log(` - ${dep}`));
}
}
/**
......@@ -111,51 +107,48 @@ function formatDepcheckResult(pkgName: string, unused: DepcheckResult): void {
* @param config - 配置选项
*/
async function runDepcheck(config: DepcheckConfig = {}): Promise<void> {
try {
const finalConfig = {
...DEFAULT_CONFIG,
...config,
};
const { packages } = await getPackages();
let hasIssues = false;
await Promise.all(
packages.map(async (pkg: PackageInfo) => {
// 跳过需要忽略的包
if (finalConfig.ignorePackages.includes(pkg.packageJson.name)) {
return;
}
const unused = await depcheck(pkg.dir, {
ignoreMatches: finalConfig.ignoreMatches,
ignorePatterns: finalConfig.ignorePatterns,
});
cleanDepcheckResult(unused);
const pkgHasIssues =
Object.keys(unused.missing).length > 0 ||
unused.dependencies.length > 0 ||
unused.devDependencies.length > 0;
if (pkgHasIssues) {
hasIssues = true;
formatDepcheckResult(pkg.packageJson.name, unused);
}
}),
);
if (!hasIssues) {
console.log('\n✅ Dependency check completed, no issues found');
}
} catch (error) {
console.error(
'❌ Dependency check failed:',
error instanceof Error ? error.message : error,
);
}
try {
const finalConfig = {
...DEFAULT_CONFIG,
...config,
};
const { packages } = await getPackages();
let hasIssues = false;
await Promise.all(
packages.map(async (pkg: PackageInfo) => {
// 跳过需要忽略的包
if (finalConfig.ignorePackages.includes(pkg.packageJson.name)) {
return;
}
const unused = await depcheck(pkg.dir, {
ignoreMatches: finalConfig.ignoreMatches,
ignorePatterns: finalConfig.ignorePatterns,
});
cleanDepcheckResult(unused);
const pkgHasIssues =
Object.keys(unused.missing).length > 0 ||
unused.dependencies.length > 0 ||
unused.devDependencies.length > 0;
if (pkgHasIssues) {
hasIssues = true;
formatDepcheckResult(pkg.packageJson.name, unused);
}
}),
);
if (!hasIssues) {
console.log("\n✅ Dependency check completed, no issues found");
}
} catch (error) {
console.error("❌ Dependency check failed:", error instanceof Error ? error.message : error);
}
}
/**
......@@ -163,30 +156,20 @@ async function runDepcheck(config: DepcheckConfig = {}): Promise<void> {
* @param cac - CAC实例
*/
function defineDepcheckCommand(cac: CAC): void {
cac
.command('check-dep')
.option(
'--ignore-packages <packages>',
'Packages to ignore, comma separated',
)
.option(
'--ignore-matches <matches>',
'Dependency patterns to ignore, comma separated',
)
.option(
'--ignore-patterns <patterns>',
'File patterns to ignore, comma separated',
)
.usage('Analyze project dependencies')
.action(async ({ ignoreMatches, ignorePackages, ignorePatterns }) => {
const config: DepcheckConfig = {
...(ignorePackages && { ignorePackages: ignorePackages.split(',') }),
...(ignoreMatches && { ignoreMatches: ignoreMatches.split(',') }),
...(ignorePatterns && { ignorePatterns: ignorePatterns.split(',') }),
};
await runDepcheck(config);
});
cac.command("check-dep")
.option("--ignore-packages <packages>", "Packages to ignore, comma separated")
.option("--ignore-matches <matches>", "Dependency patterns to ignore, comma separated")
.option("--ignore-patterns <patterns>", "File patterns to ignore, comma separated")
.usage("Analyze project dependencies")
.action(async ({ ignoreMatches, ignorePackages, ignorePatterns }) => {
const config: DepcheckConfig = {
...(ignorePackages && { ignorePackages: ignorePackages.split(",") }),
...(ignoreMatches && { ignoreMatches: ignoreMatches.split(",") }),
...(ignorePatterns && { ignorePatterns: ignorePatterns.split(",") }),
};
await runDepcheck(config);
});
}
export { defineDepcheckCommand, type DepcheckConfig };
import type { CAC } from 'cac';
import type { CAC } from "cac";
import { join, relative } from 'node:path';
import { join, relative } from "node:path";
import {
colors,
consola,
findMonorepoRoot,
getPackages,
gitAdd,
outputJSON,
prettierFormat,
toPosixPath,
} from '@venus/node-utils';
colors,
consola,
findMonorepoRoot,
getPackages,
gitAdd,
outputJSON,
prettierFormat,
toPosixPath,
} from "@venus/node-utils";
const CODE_WORKSPACE_FILE = join('venus-admin.code-workspace');
const CODE_WORKSPACE_FILE = join("venus-admin.code-workspace");
interface CodeWorkspaceCommandOptions {
autoCommit?: boolean;
spaces?: number;
autoCommit?: boolean;
spaces?: number;
}
async function createCodeWorkspace({
autoCommit = false,
spaces = 2,
}: CodeWorkspaceCommandOptions) {
const { packages, rootDir } = await getPackages();
async function createCodeWorkspace({ autoCommit = false, spaces = 2 }: CodeWorkspaceCommandOptions) {
const { packages, rootDir } = await getPackages();
let folders = packages.map((pkg) => {
const { dir, packageJson } = pkg;
return {
name: packageJson.name,
path: toPosixPath(relative(rootDir, dir)),
};
});
let folders = packages.map((pkg) => {
const { dir, packageJson } = pkg;
return {
name: packageJson.name,
path: toPosixPath(relative(rootDir, dir)),
};
});
folders = folders.filter(Boolean);
folders = folders.filter(Boolean);
const monorepoRoot = findMonorepoRoot();
const outputPath = join(monorepoRoot, CODE_WORKSPACE_FILE);
await outputJSON(outputPath, { folders }, spaces);
const monorepoRoot = findMonorepoRoot();
const outputPath = join(monorepoRoot, CODE_WORKSPACE_FILE);
await outputJSON(outputPath, { folders }, spaces);
await prettierFormat(outputPath);
if (autoCommit) {
await gitAdd(CODE_WORKSPACE_FILE, monorepoRoot);
}
await prettierFormat(outputPath);
if (autoCommit) {
await gitAdd(CODE_WORKSPACE_FILE, monorepoRoot);
}
}
async function runCodeWorkspace({
autoCommit,
spaces,
}: CodeWorkspaceCommandOptions) {
await createCodeWorkspace({
autoCommit,
spaces,
});
if (autoCommit) {
return;
}
consola.log('');
consola.success(colors.green(`${CODE_WORKSPACE_FILE} is updated!`));
consola.log('');
async function runCodeWorkspace({ autoCommit, spaces }: CodeWorkspaceCommandOptions) {
await createCodeWorkspace({
autoCommit,
spaces,
});
if (autoCommit) {
return;
}
consola.log("");
consola.success(colors.green(`${CODE_WORKSPACE_FILE} is updated!`));
consola.log("");
}
function defineCodeWorkspaceCommand(cac: CAC) {
cac
.command('code-workspace')
.usage('Update the `.code-workspace` file')
.option('--spaces [number]', '.code-workspace JSON file spaces.', {
default: 2,
})
.option('--auto-commit', 'auto commit .code-workspace JSON file.', {
default: false,
})
.action(runCodeWorkspace);
cac.command("code-workspace")
.usage("Update the `.code-workspace` file")
.option("--spaces [number]", ".code-workspace JSON file spaces.", {
default: 2,
})
.option("--auto-commit", "auto commit .code-workspace JSON file.", {
default: false,
})
.action(runCodeWorkspace);
}
export { defineCodeWorkspaceCommand };
// 导入工具函数:颜色和日志输出
import { colors, consola } from '@venus/node-utils';
import { colors, consola } from "@venus/node-utils";
// 导入 CLI 框架
import { cac } from 'cac';
import { cac } from "cac";
// 导入版本号
import { version } from '../package.json';
import { version } from "../package.json";
// 导入各个命令的定义函数
import { defineCheckCircularCommand } from './check-circular';
import { defineDepcheckCommand } from './check-dep';
import { defineCodeWorkspaceCommand } from './code-workspace';
import { defineLintCommand } from './lint';
import { definePubLintCommand } from './publint';
import { defineCheckCircularCommand } from "./check-circular";
import { defineDepcheckCommand } from "./check-dep";
import { defineCodeWorkspaceCommand } from "./code-workspace";
import { defineLintCommand } from "./lint";
import { definePubLintCommand } from "./publint";
/**
* 命令描述映射表
* 用于在显示帮助信息时展示每个命令的说明
*/
const COMMAND_DESCRIPTIONS = {
'check-circular': 'Check for circular dependencies',
'check-dep': 'Check for unused dependencies',
'code-workspace': 'Manage VS Code workspace settings',
lint: 'Run linting on the project',
publint: 'Check package.json files for publishing standards',
"check-circular": "Check for circular dependencies",
"check-dep": "Check for unused dependencies",
"code-workspace": "Manage VS Code workspace settings",
lint: "Run linting on the project",
publint: "Check package.json files for publishing standards",
} as const;
/**
......@@ -30,58 +30,54 @@ const COMMAND_DESCRIPTIONS = {
* 这是 CLI 应用的主入口函数
*/
async function main(): Promise<void> {
try {
// 创建 CLI 实例,命令名称为 'vsh'
const vsh = cac('vsh');
try {
// 创建 CLI 实例,命令名称为 'vsh'
const vsh = cac("vsh");
// 注册所有命令
defineLintCommand(vsh);
definePubLintCommand(vsh);
defineCodeWorkspaceCommand(vsh);
defineCheckCircularCommand(vsh);
defineDepcheckCommand(vsh);
// 注册所有命令
defineLintCommand(vsh);
definePubLintCommand(vsh);
defineCodeWorkspaceCommand(vsh);
defineCheckCircularCommand(vsh);
defineDepcheckCommand(vsh);
// 处理无效命令
// 当用户输入了不存在的命令时,显示错误信息和可用命令列表
vsh.on('command:*', ([cmd]) => {
consola.error(
colors.red(`Invalid command: ${cmd}`),
'\n',
colors.yellow('Available commands:'),
'\n',
Object.entries(COMMAND_DESCRIPTIONS)
.map(([cmd, desc]) => ` ${colors.cyan(cmd)} - ${desc}`)
.join('\n'),
);
process.exit(1);
});
// 处理无效命令
// 当用户输入了不存在的命令时,显示错误信息和可用命令列表
vsh.on("command:*", ([cmd]) => {
consola.error(
colors.red(`Invalid command: ${cmd}`),
"\n",
colors.yellow("Available commands:"),
"\n",
Object.entries(COMMAND_DESCRIPTIONS)
.map(([cmd, desc]) => ` ${colors.cyan(cmd)} - ${desc}`)
.join("\n"),
);
process.exit(1);
});
// 设置 CLI 配置
// 设置使用说明、帮助信息和版本号
vsh.usage('vsh <command> [options]');
vsh.help();
vsh.version(version);
// 设置 CLI 配置
// 设置使用说明、帮助信息和版本号
vsh.usage("vsh <command> [options]");
vsh.help();
vsh.version(version);
// 解析命令行参数
vsh.parse();
} catch (error) {
// 捕获并处理运行时错误
consola.error(
colors.red('An unexpected error occurred:'),
'\n',
error instanceof Error ? error.message : error,
);
process.exit(1);
}
// 解析命令行参数
vsh.parse();
} catch (error) {
// 捕获并处理运行时错误
consola.error(
colors.red("An unexpected error occurred:"),
"\n",
error instanceof Error ? error.message : error,
);
process.exit(1);
}
}
// 运行 CLI 应用
// 如果启动失败,捕获错误并退出
main().catch((error) => {
consola.error(
colors.red('Failed to start CLI:'),
'\n',
error instanceof Error ? error.message : error,
);
process.exit(1);
consola.error(colors.red("Failed to start CLI:"), "\n", error instanceof Error ? error.message : error);
process.exit(1);
});
import type { CAC } from 'cac';
import type { CAC } from "cac";
import { relative, resolve } from 'node:path';
import { execaCommand } from '@venus/node-utils';
import { execaCommand } from "@venus/node-utils";
interface LintCommandOptions {
/**
* Format lint problem.
*/
format?: boolean;
/**
* Format lint problem.
*/
format?: boolean;
}
/**
* 构建路径模式
* @param paths 指定的路径数组
* @returns 返回路径模式字符串,如果为空则返回 '.' 表示当前目录
*/
function buildPathPattern(paths: string[]): string {
if (!paths || paths.length === 0) {
return '.';
}
// 规范化路径:统一使用正斜杠,并处理相对路径
const normalizedPaths = paths.map((path) => {
// 如果是绝对路径,转换为相对路径
const isAbsolute = path.startsWith('/') || /^[A-Z]:[\\/]/.test(path);
if (isAbsolute) {
const relativePath = relative(process.cwd(), resolve(path));
return relativePath.replaceAll('\\', '/');
}
// 相对路径直接规范化
return path.replaceAll('\\', '/');
});
// 如果只有一个路径,直接返回
if (normalizedPaths.length === 1) {
return normalizedPaths[0]!;
}
// 多个路径时,使用花括号模式
return `{${normalizedPaths.join(',')}}`;
}
/**
* 构建样式文件路径模式
* @param basePattern 基础路径模式
* @returns 返回样式文件的路径模式
*/
function buildStylePattern(basePattern: string): string {
if (basePattern === '.') {
return '**/*.{vue,css,less,scss}';
}
// 如果指定了具体路径,则在该路径下查找样式文件
// 支持花括号模式(多个路径)
if (basePattern.startsWith('{') && basePattern.endsWith('}')) {
// 多个路径时,为每个路径添加样式文件匹配
const paths = basePattern.slice(1, -1).split(',');
return `{${paths.map((p) => `${p}/**/*.{vue,css,less,scss}`).join(',')}}`;
}
return `${basePattern}/**/*.{vue,css,less,scss}`;
}
async function runLint(
files: string[] | undefined,
options: LintCommandOptions,
) {
// process.env.FORCE_COLOR = '3';
// 处理 CAC 参数:如果 options 中包含 files,需要正确提取
const { format } = options;
let filePaths = files;
// 如果 files 为空,尝试从 process.argv 中提取文件路径
// 这可以处理 PowerShell 等 shell 的参数解析问题
if (!filePaths || filePaths.length === 0) {
const allArgs = process.argv.slice(2);
// 查找 'lint' 命令的位置
const lintIndex = allArgs.indexOf('lint');
if (lintIndex !== -1) {
// 提取 'lint' 之后的所有参数,过滤掉选项
const argsAfterLint = allArgs.slice(lintIndex + 1);
filePaths = argsAfterLint.filter(
(arg) => !arg.startsWith('--') && arg !== '--format',
);
}
}
const pathPattern = buildPathPattern(filePaths || []);
const stylePattern = buildStylePattern(pathPattern);
if (format) {
// 格式化样式文件
await execaCommand(`stylelint "${stylePattern}" --cache --fix`, {
stdio: 'inherit',
});
// 格式化代码文件
await execaCommand(`eslint ${pathPattern} --cache --fix`, {
stdio: 'inherit',
});
// 格式化所有文件
await execaCommand(
`prettier ${pathPattern} --write --cache --log-level warn`,
{
stdio: 'inherit',
},
);
return;
}
// 检查模式:并行执行所有检查
await Promise.all([
execaCommand(`eslint ${pathPattern} --cache`, {
stdio: 'inherit',
}),
execaCommand(`prettier ${pathPattern} --ignore-unknown --check --cache`, {
stdio: 'inherit',
}),
execaCommand(`stylelint "${stylePattern}" --cache`, {
stdio: 'inherit',
}),
]);
async function runLint({ format }: LintCommandOptions) {
// process.env.FORCE_COLOR = '3';
if (format) {
await execaCommand(`stylelint "**/*.{vue,css,less,scss}" --cache --fix`, {
stdio: "inherit",
});
await execaCommand(`eslint . --cache --fix`, {
stdio: "inherit",
});
// await execaCommand(`prettier . --write --cache --log-level warn`, {
// stdio: "inherit",
// });
return;
}
await Promise.all([
execaCommand(`eslint . --cache`, {
stdio: "inherit",
}),
// execaCommand(`prettier . --ignore-unknown --check --cache`, {
// stdio: "inherit",
// }),
execaCommand(`stylelint "**/*.{vue,css,less,scss}" --cache`, {
stdio: "inherit",
}),
]);
}
function defineLintCommand(cac: CAC) {
cac
.command('lint [...files]')
.usage('批量执行项目代码检查。可以指定文件或目录路径进行格式化。')
.option('--format', '自动修复和格式化代码问题。')
.example('vsh lint --format')
.example('vsh lint --format apps/frontend')
.example('vsh lint --format packages/utils src/components')
.action(runLint);
cac.command("lint")
.usage("Batch execute project lint check.")
.option("--format", "Format lint problem.")
.action(runLint);
}
export { defineLintCommand };
......@@ -3,43 +3,38 @@
* 用于检查 monorepo 中的包是否符合 publint 标准
*/
import type { CAC } from 'cac';
import type { Result } from 'publint';
import type { CAC } from "cac";
import type { Result } from "publint";
import { basename, dirname, join } from 'node:path';
import { basename, dirname, join } from "node:path";
import {
colors,
consola,
ensureFile,
findMonorepoRoot,
generatorContentHash,
getPackages,
outputJSON,
readJSON,
UNICODE,
} from '@venus/node-utils';
import { publint } from 'publint';
import { formatMessage } from 'publint/utils';
colors,
consola,
ensureFile,
findMonorepoRoot,
generatorContentHash,
getPackages,
outputJSON,
readJSON,
UNICODE,
} from "@venus/node-utils";
import { publint } from "publint";
import { formatMessage } from "publint/utils";
/**
* 缓存文件路径
* 用于存储 publint 检查结果,避免重复检查未变更的包
*/
const CACHE_FILE = join(
'node_modules',
'.cache',
'publint',
'.pkglintcache.json',
);
const CACHE_FILE = join("node_modules", ".cache", "publint", ".pkglintcache.json");
/**
* Publint 命令选项接口
*/
interface PubLintCommandOptions {
/** 仅检查模式,不执行程序退出 */
check?: boolean;
/** 仅检查模式,不执行程序退出 */
check?: boolean;
}
/**
......@@ -48,20 +43,20 @@ interface PubLintCommandOptions {
* @returns 返回需要检查的 package.json 文件路径数组
*/
async function getLintFiles(files: string[] = []) {
const lintFiles: string[] = [];
const lintFiles: string[] = [];
// 如果指定了文件,则只检查这些文件中的 package.json
if (files?.length > 0) {
return files.filter((file) => basename(file) === 'package.json');
}
// 如果指定了文件,则只检查这些文件中的 package.json
if (files?.length > 0) {
return files.filter((file) => basename(file) === "package.json");
}
// 否则获取 monorepo 中所有包的 package.json
const { packages } = await getPackages();
// 否则获取 monorepo 中所有包的 package.json
const { packages } = await getPackages();
for (const { dir } of packages) {
lintFiles.push(join(dir, 'package.json'));
}
return lintFiles;
for (const { dir } of packages) {
lintFiles.push(join(dir, "package.json"));
}
return lintFiles;
}
/**
......@@ -69,8 +64,8 @@ async function getLintFiles(files: string[] = []) {
* @returns 返回缓存文件的完整路径
*/
function getCacheFile() {
const root = findMonorepoRoot();
return join(root, CACHE_FILE);
const root = findMonorepoRoot();
return join(root, CACHE_FILE);
}
/**
......@@ -79,12 +74,12 @@ function getCacheFile() {
* @returns 返回缓存数据对象,如果读取失败则返回空对象
*/
async function readCache(cacheFile: string) {
try {
await ensureFile(cacheFile);
return await readJSON(cacheFile);
} catch {
return {};
}
try {
await ensureFile(cacheFile);
return await readJSON(cacheFile);
} catch {
return {};
}
}
/**
......@@ -93,56 +88,56 @@ async function readCache(cacheFile: string) {
* @param options 命令选项
*/
async function runPublint(files: string[], { check }: PubLintCommandOptions) {
const lintFiles = await getLintFiles(files);
const cacheFile = getCacheFile();
const cacheData = await readCache(cacheFile);
const cache: Record<string, { hash: string; result: Result }> = cacheData;
// 并行检查所有包
const results = await Promise.all(
lintFiles.map(async (file) => {
try {
const pkgJson = await readJSON(file);
// 跳过私有包
if (pkgJson.private) {
return null;
}
// 移除依赖相关字段,避免依赖变更影响缓存命中
Reflect.deleteProperty(pkgJson, 'dependencies');
Reflect.deleteProperty(pkgJson, 'devDependencies');
Reflect.deleteProperty(pkgJson, 'peerDependencies');
const content = JSON.stringify(pkgJson);
const hash = generatorContentHash(content);
// 如果缓存中存在且 hash 匹配,则使用缓存结果,否则执行检查
const publintResult: Result =
cache?.[file]?.hash === hash
? (cache?.[file]?.result ?? [])
: await publint({
level: 'suggestion',
pkgDir: dirname(file),
strict: true,
});
// 更新缓存
cache[file] = {
hash,
result: publintResult,
};
return { pkgJson, pkgPath: file, publintResult };
} catch {
return null;
}
}),
);
// 保存缓存并打印结果
await outputJSON(cacheFile, cache);
printResult(results, check);
const lintFiles = await getLintFiles(files);
const cacheFile = getCacheFile();
const cacheData = await readCache(cacheFile);
const cache: Record<string, { hash: string; result: Result }> = cacheData;
// 并行检查所有包
const results = await Promise.all(
lintFiles.map(async (file) => {
try {
const pkgJson = await readJSON(file);
// 跳过私有包
if (pkgJson.private) {
return null;
}
// 移除依赖相关字段,避免依赖变更影响缓存命中
Reflect.deleteProperty(pkgJson, "dependencies");
Reflect.deleteProperty(pkgJson, "devDependencies");
Reflect.deleteProperty(pkgJson, "peerDependencies");
const content = JSON.stringify(pkgJson);
const hash = generatorContentHash(content);
// 如果缓存中存在且 hash 匹配,则使用缓存结果,否则执行检查
const publintResult: Result =
cache?.[file]?.hash === hash
? (cache?.[file]?.result ?? [])
: await publint({
level: "suggestion",
pkgDir: dirname(file),
strict: true,
});
// 更新缓存
cache[file] = {
hash,
result: publintResult,
};
return { pkgJson, pkgPath: file, publintResult };
} catch {
return null;
}
}),
);
// 保存缓存并打印结果
await outputJSON(cacheFile, cache);
printResult(results, check);
}
/**
......@@ -151,72 +146,70 @@ async function runPublint(files: string[], { check }: PubLintCommandOptions) {
* @param check 是否为仅检查模式,如果为 true 则不会退出程序
*/
function printResult(
results: Array<null | {
pkgJson: Record<string, number | string>;
pkgPath: string;
publintResult: Result;
}>,
check?: boolean,
results: Array<null | {
pkgJson: Record<string, number | string>;
pkgPath: string;
publintResult: Result;
}>,
check?: boolean,
) {
let errorCount = 0;
let warningCount = 0;
let suggestionsCount = 0;
// 遍历所有结果并统计问题数量
for (const result of results) {
if (!result) {
continue;
}
const { pkgJson, pkgPath, publintResult } = result;
const messages = publintResult?.messages ?? [];
// 如果没有消息则跳过
if (messages?.length < 1) {
continue;
}
// 打印包路径和所有消息
consola.log('');
consola.log(pkgPath);
for (const message of messages) {
// 根据消息类型统计数量
switch (message.type) {
case 'error': {
errorCount++;
break;
}
case 'suggestion': {
suggestionsCount++;
break;
}
case 'warning': {
warningCount++;
break;
}
// 无默认分支
}
// 生成规则链接并打印格式化后的消息
const ruleUrl = `https://publint.dev/rules#${message.code.toLocaleLowerCase()}`;
consola.log(
` ${formatMessage(message, pkgJson)}${colors.dim(` ${ruleUrl}`)}`,
);
}
}
// 打印统计信息
const totalCount = warningCount + errorCount + suggestionsCount;
if (totalCount > 0) {
consola.error(
colors.red(
`${UNICODE.FAILURE} ${totalCount} problem (${errorCount} errors, ${warningCount} warnings, ${suggestionsCount} suggestions)`,
),
);
// 如果不是仅检查模式,则退出程序
!check && process.exit(1);
} else {
consola.log(colors.green(`${UNICODE.SUCCESS} No problem`));
}
let errorCount = 0;
let warningCount = 0;
let suggestionsCount = 0;
// 遍历所有结果并统计问题数量
for (const result of results) {
if (!result) {
continue;
}
const { pkgJson, pkgPath, publintResult } = result;
const messages = publintResult?.messages ?? [];
// 如果没有消息则跳过
if (messages?.length < 1) {
continue;
}
// 打印包路径和所有消息
consola.log("");
consola.log(pkgPath);
for (const message of messages) {
// 根据消息类型统计数量
switch (message.type) {
case "error": {
errorCount++;
break;
}
case "suggestion": {
suggestionsCount++;
break;
}
case "warning": {
warningCount++;
break;
}
// 无默认分支
}
// 生成规则链接并打印格式化后的消息
const ruleUrl = `https://publint.dev/rules#${message.code.toLocaleLowerCase()}`;
consola.log(` ${formatMessage(message, pkgJson)}${colors.dim(` ${ruleUrl}`)}`);
}
}
// 打印统计信息
const totalCount = warningCount + errorCount + suggestionsCount;
if (totalCount > 0) {
consola.error(
colors.red(
`${UNICODE.FAILURE} ${totalCount} problem (${errorCount} errors, ${warningCount} warnings, ${suggestionsCount} suggestions)`,
),
);
// 如果不是仅检查模式,则退出程序
!check && process.exit(1);
} else {
consola.log(colors.green(`${UNICODE.SUCCESS} No problem`));
}
}
/**
......@@ -224,11 +217,10 @@ function printResult(
* @param cac CAC 实例,用于注册命令
*/
function definePubLintCommand(cac: CAC) {
cac
.command('publint [...files]')
.usage('检查 monorepo 中的包是否符合 publint 标准。')
.option('--check', '仅检查模式,只检查错误,不执行程序退出。')
.action(runPublint);
cac.command("publint [...files]")
.usage("检查 monorepo 中的包是否符合 publint 标准。")
.option("--check", "仅检查模式,只检查错误,不执行程序退出。")
.action(runPublint);
}
export { definePubLintCommand };
{
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@venus/tsconfig/node.json",
"include": ["src"],
"exclude": ["node_modules"]
"$schema": "https://json.schemastore.org/tsconfig",
"extends": "@venus/tsconfig/node.json",
"include": ["src"],
"exclude": ["node_modules"]
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!