index.ts 3.99 KB
import type { CAC } from 'cac';

import { relative, resolve } from 'node:path';

import { execaCommand } from '@venus/node-utils';

interface LintCommandOptions {
  /**
   * Format lint problem.
   */
  format?: boolean;
}

/**
 * 构建路径模式
 * @param paths 指定的路径数组
 * @returns 返回路径模式字符串,如果为空则返回 '.' 表示当前目录
 */
function buildPathPattern(paths: string[]): string {
  if (!paths || paths.length === 0) {
    return '.';
  }

  // 规范化路径:统一使用正斜杠,并处理相对路径
  const normalizedPaths = paths.map((path) => {
    // 如果是绝对路径,转换为相对路径
    const isAbsolute = path.startsWith('/') || /^[A-Z]:[\\/]/.test(path);
    if (isAbsolute) {
      const relativePath = relative(process.cwd(), resolve(path));
      return relativePath.replaceAll('\\', '/');
    }
    // 相对路径直接规范化
    return path.replaceAll('\\', '/');
  });

  // 如果只有一个路径,直接返回
  if (normalizedPaths.length === 1) {
    return normalizedPaths[0]!;
  }

  // 多个路径时,使用花括号模式
  return `{${normalizedPaths.join(',')}}`;
}

/**
 * 构建样式文件路径模式
 * @param basePattern 基础路径模式
 * @returns 返回样式文件的路径模式
 */
function buildStylePattern(basePattern: string): string {
  if (basePattern === '.') {
    return '**/*.{vue,css,less,scss}';
  }
  // 如果指定了具体路径,则在该路径下查找样式文件
  // 支持花括号模式(多个路径)
  if (basePattern.startsWith('{') && basePattern.endsWith('}')) {
    // 多个路径时,为每个路径添加样式文件匹配
    const paths = basePattern.slice(1, -1).split(',');
    return `{${paths.map((p) => `${p}/**/*.{vue,css,less,scss}`).join(',')}}`;
  }
  return `${basePattern}/**/*.{vue,css,less,scss}`;
}

async function runLint(
  files: string[] | undefined,
  options: LintCommandOptions,
) {
  // process.env.FORCE_COLOR = '3';

  // 处理 CAC 参数:如果 options 中包含 files,需要正确提取
  const { format } = options;
  let filePaths = files;

  // 如果 files 为空,尝试从 process.argv 中提取文件路径
  // 这可以处理 PowerShell 等 shell 的参数解析问题
  if (!filePaths || filePaths.length === 0) {
    const allArgs = process.argv.slice(2);
    // 查找 'lint' 命令的位置
    const lintIndex = allArgs.indexOf('lint');
    if (lintIndex !== -1) {
      // 提取 'lint' 之后的所有参数,过滤掉选项
      const argsAfterLint = allArgs.slice(lintIndex + 1);
      filePaths = argsAfterLint.filter(
        (arg) => !arg.startsWith('--') && arg !== '--format',
      );
    }
  }

  const pathPattern = buildPathPattern(filePaths || []);
  const stylePattern = buildStylePattern(pathPattern);

  if (format) {
    // 格式化样式文件
    await execaCommand(`stylelint "${stylePattern}" --cache --fix`, {
      stdio: 'inherit',
    });
    // 格式化代码文件
    await execaCommand(`eslint ${pathPattern} --cache --fix`, {
      stdio: 'inherit',
    });
    // 格式化所有文件
    await execaCommand(
      `prettier ${pathPattern} --write --cache --log-level warn`,
      {
        stdio: 'inherit',
      },
    );
    return;
  }

  // 检查模式:并行执行所有检查
  await Promise.all([
    execaCommand(`eslint ${pathPattern} --cache`, {
      stdio: 'inherit',
    }),
    execaCommand(`prettier ${pathPattern} --ignore-unknown --check --cache`, {
      stdio: 'inherit',
    }),
    execaCommand(`stylelint "${stylePattern}" --cache`, {
      stdio: 'inherit',
    }),
  ]);
}

function defineLintCommand(cac: CAC) {
  cac
    .command('lint [...files]')
    .usage('批量执行项目代码检查。可以指定文件或目录路径进行格式化。')
    .option('--format', '自动修复和格式化代码问题。')
    .example('vsh lint --format')
    .example('vsh lint --format apps/frontend')
    .example('vsh lint --format packages/utils src/components')
    .action(runLint);
}

export { defineLintCommand };