1+ import * as fs from 'fs' ;
2+ import * as path from 'path' ;
3+ import * as YAML from 'yaml' ;
4+ import { Challenge } from '../../../types/challenge' ;
5+ import { processChallengeData } from './processor' ;
6+
7+ /**
8+ * 收集目录下所有YAML文件中的挑战数据
9+ * @param dirPath 目录路径
10+ * @param rootDir 根目录
11+ * @param isBuild 是否为构建模式
12+ * @returns 挑战数据数组
13+ */
14+ export function collectYAMLChallenges ( dirPath : string , rootDir : string , isBuild = false ) : Challenge [ ] {
15+ const entries = fs . readdirSync ( dirPath , { withFileTypes : true } ) ;
16+ let challenges : Challenge [ ] = [ ] ;
17+
18+ for ( const entry of entries ) {
19+ const fullPath = path . join ( dirPath , entry . name ) ;
20+ if ( entry . isDirectory ( ) ) {
21+ challenges = challenges . concat ( collectYAMLChallenges ( fullPath , rootDir , isBuild ) ) ;
22+ } else if ( entry . isFile ( ) && path . extname ( entry . name ) === '.yml' ) {
23+ const yamlChallenges = processYamlFile ( fullPath , rootDir , isBuild ) ;
24+ if ( yamlChallenges && yamlChallenges . length > 0 ) {
25+ challenges = challenges . concat ( yamlChallenges ) ;
26+ }
27+ }
28+ }
29+ return challenges ;
30+ }
31+
32+ /**
33+ * 处理单个YAML文件
34+ * @param filePath 文件路径
35+ * @param rootDir 根目录
36+ * @param isBuild 是否为构建模式
37+ * @returns 挑战数据数组
38+ */
39+ function processYamlFile ( filePath : string , rootDir : string , isBuild = false ) : Challenge [ ] {
40+ try {
41+ const content = fs . readFileSync ( filePath , 'utf8' ) ;
42+ const parsed = YAML . parse ( content ) ;
43+ const challenges : Challenge [ ] = [ ] ;
44+
45+ // 计算YAML文件相对于根目录的路径
46+ const yamlRelativePath = path . relative ( rootDir , filePath ) ;
47+
48+ // 处理挑战数据
49+ if ( parsed . challenges && Array . isArray ( parsed . challenges ) ) {
50+ // 处理多个挑战的数组格式
51+ console . log ( `解析包含挑战数组的YAML文件: ${ filePath } ` ) ;
52+ parsed . challenges . forEach ( ( challenge : any ) => {
53+ // 跳过标记为ignored的挑战
54+ if ( challenge . ignored === true ) {
55+ console . log ( `跳过忽略的挑战: ID=${ challenge . id || 'unknown' } , 文件: ${ yamlRelativePath } ` ) ;
56+ return ;
57+ }
58+ // 传递YAML文件路径
59+ challenges . push ( processChallengeData ( challenge , rootDir , isBuild , yamlRelativePath ) ) ;
60+ } ) ;
61+ } else if ( parsed . id ) {
62+ // 处理单个挑战格式
63+ console . log ( `解析单个挑战YAML文件: ${ filePath } ` ) ;
64+ // 跳过标记为ignored的挑战
65+ if ( parsed . ignored !== true ) {
66+ challenges . push ( processChallengeData ( parsed , rootDir , isBuild , yamlRelativePath ) ) ;
67+ } else {
68+ console . log ( `跳过忽略的挑战文件: ${ yamlRelativePath } ` ) ;
69+ }
70+ } else {
71+ console . warn ( `无法识别的YAML格式,没有找到challenges数组或id字段: ${ filePath } ` ) ;
72+ }
73+
74+ return challenges ;
75+ } catch ( e : any ) {
76+ console . error ( `Error processing ${ filePath } : ${ e . message } ` ) ;
77+ return [ ] ;
78+ }
79+ }
0 commit comments