-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathcode.js
60 lines (58 loc) · 1.65 KB
/
code.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import fs from 'node:fs'
import { getQuestionCodeList } from '#common/utils/question-getter/getQuestionCodeList.js'
import {
getLangByExtension,
setLineComment
} from '#common/utils/question-handler/questionLanguage.js'
import { DefaultLang } from '#common/constants/question.const.js'
/**
* 获取代码
* @param slug
* @param lang
* @returns {Promise<*>}
*/
export async function getCodeBySlug(slug, lang) {
const list = await getQuestionCodeList(slug)
return list.find((o) => o.langSlug === lang)?.code
}
/**
* 获取支持的代码语言
* @param slug
* @returns {Promise<string[]>}
*/
export async function getSupportCode(slug) {
const list = await getQuestionCodeList(slug)
return list.map((code) => code?.langSlug)
}
/**
* 生成有范围块的代码
* @param lang
* @param code
* @returns {*|string}
*/
export function getCodeRange(lang, code) {
if (!code) {
return setLineComment(
lang,
`!important: 此题目没有当前语言[${lang}]的代码模板!`
)
}
return `${setLineComment(lang, '@QUESTION_START') + code}\n${setLineComment(
lang,
'@QUESTION_END'
)}`
}
/**
* 获取文件中的代码部分
*/
export function getCodeInFile(filePath) {
const lang = getLangByExtension(filePath)?.lang ?? DefaultLang
const data = fs.readFileSync(filePath, 'utf-8')
const startTag = setLineComment(lang, '@QUESTION_START')
const endTag = setLineComment(lang, '@QUESTION_END')
const rangeReg = new RegExp(`${startTag}.*${endTag}`, 'ms')
const rangeTagReg = new RegExp(`(${startTag}|${endTag})+`, 'mg')
const match = data.match(rangeReg)
if (!match) return null
return match[0]?.replace(rangeTagReg, '')
}