refactor: optimize snippet markdown plugin code (#2580)

pull/2581/head
烽宁 1 year ago committed by GitHub
parent 32d65d40c5
commit d5ccc52048
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -145,36 +145,38 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => {
// @ts-ignore
const [src, regionName] = token.src ?? []
if (src) {
if (loader) {
loader.addDependency(src)
}
const isAFile = fs.lstatSync(src).isFile()
if (fs.existsSync(src) && isAFile) {
let content = fs.readFileSync(src, 'utf8')
if (regionName) {
const lines = content.split(/\r?\n/)
const region = findRegion(lines, regionName)
if (region) {
content = dedent(
lines
.slice(region.start, region.end)
.filter((line: string) => !region.regexp.test(line.trim()))
.join('\n')
)
}
}
if (!src) return fence(...args)
token.content = content
} else {
token.content = isAFile
? `Code snippet path not found: ${src}`
: `Invalid code snippet option`
token.info = ''
if (loader) {
loader.addDependency(src)
}
const isAFile = fs.lstatSync(src).isFile()
if (!fs.existsSync(src) || !isAFile) {
token.content = isAFile
? `Code snippet path not found: ${src}`
: `Invalid code snippet option`
token.info = ''
return fence(...args)
}
let content = fs.readFileSync(src, 'utf8')
if (regionName) {
const lines = content.split(/\r?\n/)
const region = findRegion(lines, regionName)
if (region) {
content = dedent(
lines
.slice(region.start, region.end)
.filter((line) => !region.regexp.test(line.trim()))
.join('\n')
)
}
}
token.content = content
return fence(...args)
}

Loading…
Cancel
Save