forked from github/docs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata-directory.js
71 lines (61 loc) · 2.55 KB
/
data-directory.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
61
62
63
64
65
66
67
68
69
70
71
import assert from 'assert'
import fs from 'fs'
import path from 'path'
import walk from 'walk-sync'
import yaml from 'js-yaml'
import { isRegExp, setWith } from 'lodash-es'
import filenameToKey from './filename-to-key.js'
import matter from 'gray-matter'
export default function dataDirectory(dir, opts = {}) {
const defaultOpts = {
preprocess: (content) => {
return content
},
ignorePatterns: [/README\.md$/i],
extensions: ['.json', '.md', '.markdown', '.yaml', '.yml'],
}
opts = Object.assign({}, defaultOpts, opts)
// validate input
assert(Array.isArray(opts.ignorePatterns))
assert(opts.ignorePatterns.every(isRegExp))
assert(Array.isArray(opts.extensions))
assert(opts.extensions.length)
// start with an empty data object
const data = {}
// find YAML and Markdown files in the given directory, recursively
const filenames = walk(dir, { includeBasePath: true }).filter((filename) => {
// ignore files that match any of ignorePatterns regexes
if (opts.ignorePatterns.some((pattern) => pattern.test(filename))) return false
// ignore files that don't have a whitelisted file extension
return opts.extensions.includes(path.extname(filename).toLowerCase())
})
const files = filenames.map((filename) => [filename, fs.readFileSync(filename, 'utf8')])
files.forEach(([filename, fileContent]) => {
// derive `foo.bar.baz` object key from `foo/bar/baz.yml` filename
const key = filenameToKey(path.relative(dir, filename))
const extension = path.extname(filename).toLowerCase()
if (opts.preprocess) fileContent = opts.preprocess(fileContent)
// Add this file's data to the global data object.
// Note we want to use `setWith` instead of `set` so we can customize the type during path creation.
// If we just use `set`, then e.g. `release-notes.enterprise-server.2-20.0` will be an Array but
// `release-notes.enterprise-server.3-0.0` will be an Object.
// See https://lodash.com/docs#set for an explanation.
switch (extension) {
case '.json':
setWith(data, key, JSON.parse(fileContent), Object)
break
case '.yaml':
case '.yml':
setWith(data, key, yaml.load(fileContent, { filename }), Object)
break
case '.md':
case '.markdown':
// Use `matter` to drop frontmatter, since localized reusable Markdown files
// can potentially have frontmatter, but we want to prevent the frontmatter
// from being rendered.
setWith(data, key, matter(fileContent).content, Object)
break
}
})
return data
}