vue-styleguidist / vue-styleguidist
1 1
import * as fs from 'fs'
2 1
import * as path from 'path'
3
import { FSWatcher } from 'chokidar'
4 1
import { promisify } from 'util'
5 1
import { writeDownMdFile } from './utils'
6
import { DocgenCLIConfigWithComponents } from './docgen'
7 1
import compileTemplates from './compileTemplates'
8

9 1
const unlink = promisify(fs.unlink)
10

11
/**
12
 * Build one md file per given compnent and save it respecting original scaffolding
13
 * if `config.watch` is true will jkeep on watch file changes
14
 * and update all needed files
15
 * @param files
16
 * @param config
17
 */
18 1
export default async function (
19
	files: string[],
20
	watcher: FSWatcher,
21
	config: DocgenCLIConfigWithComponents,
22
	docMap: { [filepath: string]: string },
23 1
	_compile = compile
24
) {
25 1
	const compileWithConfig = _compile.bind(null, config, docMap, watcher)
26

27 1
	await Promise.all(files.map(f => compileWithConfig(f)))
28

29 1
	if (config.watch) {
30 1
		watcher
31
			// on filechange, recompile the corresponding file
32
			.on('add', compileWithConfig)
33
			.on('change', compileWithConfig)
34
			// on file delete, delete corresponding md file
35 0
			.on('unlink', (relPath: string) => {
36 1
				if (files.includes(relPath)) {
37 0
					unlink(config.getDestFile(relPath, config))
38
				} else {
39
					// if it's not a main file recompile the file connected to it
40 0
					compileWithConfig(docMap[relPath])
41
				}
42
			})
43
	}
44
}
45

46
/**
47
 * Compile a markdown file from a components and save it
48
 * This will use the filePath to know where to save
49
 * @param config config passed to the current chunk
50
 * @param docMap a map of each documentation file to the component they refer to
51
 * @param watcher
52
 * @param filePath relative path where the MD file is going to be saved
53
 */
54 1
export async function compile(
55
	config: DocgenCLIConfigWithComponents,
56
	docMap: { [filepath: string]: string },
57
	watcher: FSWatcher,
58 1
	filePath: string
59
) {
60 1
	const componentFile = docMap[filePath] || filePath
61 1
	const file = config.getDestFile(componentFile, config)
62

63
	// if getDestFile is null, will not create files
64 1
	if (file) {
65
		try {
66 1
			const { content, dependencies } = await compileTemplates(
67
				path.join(config.componentsRoot, componentFile),
68
				config,
69
				componentFile
70
			)
71 1
			dependencies.forEach(d => {
72 0
				watcher.add(d)
73 0
				docMap[d] = componentFile
74
			})
75 1
			writeDownMdFile(content, file)
76
		} catch (e) {
77 0
			throw new Error(`Error compiling file ${file}: ${e.message}`)
78
		}
79
	}
80
}

Read our documentation on viewing source code .

Loading