/
resolveImportCode.ts
50 lines (45 loc) · 1.33 KB
/
resolveImportCode.ts
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
import { colors, fs, logger, path } from '@vuepress/utils'
import type { MarkdownEnv } from '../../types.js'
import type { ImportCodeTokenMeta } from './types.js'
export const resolveImportCode = (
{ importPath, lineStart, lineEnd }: ImportCodeTokenMeta,
{ filePath }: MarkdownEnv
): {
importFilePath: string | null
importCode: string
} => {
let importFilePath = importPath
if (!path.isAbsolute(importPath)) {
// if the importPath is relative path, we need to resolve it
// according to the markdown filePath
if (!filePath) {
logger.error(
`Import file ${colors.magenta(importPath)} can not be resolved`
)
return {
importFilePath: null,
importCode: 'Error when resolving path',
}
}
importFilePath = path.resolve(filePath, '..', importPath)
}
// check file existence
if (!fs.existsSync(importFilePath)) {
logger.error(`Import file ${colors.magenta(importPath)} not found`)
return {
importFilePath,
importCode: 'File not found',
}
}
// read file content
const fileContent = fs.readFileSync(importFilePath).toString()
// resolve partial import
return {
importFilePath,
importCode: fileContent
.split('\n')
.slice(lineStart ? lineStart - 1 : lineStart, lineEnd)
.join('\n')
.replace(/\n?$/, '\n'),
}
}