Commit 1641f3d0 by Jaxon

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

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