|
1 | 1 | import { execa } from "execa";
|
| 2 | +import fs from "fs"; |
| 3 | +import path from "path"; |
2 | 4 | import type { Options } from "execa";
|
3 | 5 | import { consola } from "consola";
|
4 | 6 | import process from "node:process";
|
@@ -58,3 +60,71 @@ export const loggerSuccess = (content: string) => {
|
58 | 60 | export const loggerError = (content: string | unknown) => {
|
59 | 61 | console.log(lightRed(`[ERROR]: ${content}`));
|
60 | 62 | };
|
| 63 | + |
| 64 | +export function filterFiles( |
| 65 | + fileList: string[], |
| 66 | + allowedExtensions: string[] |
| 67 | +): string[] { |
| 68 | + const filteredFiles: string[] = []; |
| 69 | + |
| 70 | + for (let i = 0; i < fileList.length; i++) { |
| 71 | + const file = fileList[i]; |
| 72 | + |
| 73 | + for (let j = 0; j < allowedExtensions.length; j++) { |
| 74 | + const extension = allowedExtensions[j]; |
| 75 | + |
| 76 | + if (file.endsWith(extension)) { |
| 77 | + filteredFiles.push(file); |
| 78 | + break; |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + return filteredFiles; |
| 83 | +} |
| 84 | + |
| 85 | +export function getAllFiles(dirPaths: string[]): string[] { |
| 86 | + const fileList: string[] = []; |
| 87 | + function traverseDirectory(dirPath: string) { |
| 88 | + const files = fs.readdirSync(dirPath); |
| 89 | + |
| 90 | + files.forEach((file) => { |
| 91 | + const filePath = path.join(dirPath, file); |
| 92 | + const stat = fs.statSync(filePath); |
| 93 | + |
| 94 | + if (stat.isDirectory()) { |
| 95 | + // 如果是文件夹,则递归遍历 |
| 96 | + traverseDirectory(filePath); |
| 97 | + } else { |
| 98 | + // 如果是文件,则将文件路径添加到列表中 |
| 99 | + fileList.push(filePath); |
| 100 | + } |
| 101 | + }); |
| 102 | + } |
| 103 | + |
| 104 | + dirPaths.forEach((dirPath) => { |
| 105 | + traverseDirectory(dirPath); |
| 106 | + }); |
| 107 | + |
| 108 | + const uniqueFiles = Array.from(new Set(fileList)); |
| 109 | + return uniqueFiles; |
| 110 | +} |
| 111 | + |
| 112 | +export const getLintFiles = async ( |
| 113 | + cwd: string, |
| 114 | + staged: boolean, |
| 115 | + paths: string[], |
| 116 | + suffix: string[] |
| 117 | +) => { |
| 118 | + let files: string[] = []; |
| 119 | + if (staged) { |
| 120 | + const result = await execCommand("git", [ |
| 121 | + "diff", |
| 122 | + "--name-only", |
| 123 | + "--cached", |
| 124 | + ]); |
| 125 | + files = result?.split("\n").map((path) => `${cwd}/${path}`) || []; |
| 126 | + } else { |
| 127 | + files = getAllFiles(paths.map((path) => `${cwd}/${path}`)); |
| 128 | + } |
| 129 | + return filterFiles(files, suffix); |
| 130 | +}; |
0 commit comments