Skip to content

Commit d5ccc52

Browse files
authored
refactor: optimize snippet markdown plugin code (#2580)
1 parent 32d65d4 commit d5ccc52

File tree

1 file changed

+29
-27
lines changed

1 file changed

+29
-27
lines changed

Diff for: src/node/markdown/plugins/snippet.ts

+29-27
Original file line numberDiff line numberDiff line change
@@ -145,36 +145,38 @@ export const snippetPlugin = (md: MarkdownIt, srcDir: string) => {
145145
// @ts-ignore
146146
const [src, regionName] = token.src ?? []
147147

148-
if (src) {
149-
if (loader) {
150-
loader.addDependency(src)
151-
}
152-
const isAFile = fs.lstatSync(src).isFile()
153-
if (fs.existsSync(src) && isAFile) {
154-
let content = fs.readFileSync(src, 'utf8')
155-
156-
if (regionName) {
157-
const lines = content.split(/\r?\n/)
158-
const region = findRegion(lines, regionName)
159-
160-
if (region) {
161-
content = dedent(
162-
lines
163-
.slice(region.start, region.end)
164-
.filter((line: string) => !region.regexp.test(line.trim()))
165-
.join('\n')
166-
)
167-
}
168-
}
148+
if (!src) return fence(...args)
169149

170-
token.content = content
171-
} else {
172-
token.content = isAFile
173-
? `Code snippet path not found: ${src}`
174-
: `Invalid code snippet option`
175-
token.info = ''
150+
if (loader) {
151+
loader.addDependency(src)
152+
}
153+
154+
const isAFile = fs.lstatSync(src).isFile()
155+
if (!fs.existsSync(src) || !isAFile) {
156+
token.content = isAFile
157+
? `Code snippet path not found: ${src}`
158+
: `Invalid code snippet option`
159+
token.info = ''
160+
return fence(...args)
161+
}
162+
163+
let content = fs.readFileSync(src, 'utf8')
164+
165+
if (regionName) {
166+
const lines = content.split(/\r?\n/)
167+
const region = findRegion(lines, regionName)
168+
169+
if (region) {
170+
content = dedent(
171+
lines
172+
.slice(region.start, region.end)
173+
.filter((line) => !region.regexp.test(line.trim()))
174+
.join('\n')
175+
)
176176
}
177177
}
178+
179+
token.content = content
178180
return fence(...args)
179181
}
180182

0 commit comments

Comments
 (0)