2021-07-14 23:49:18 +03:00
|
|
|
import assert from 'assert'
|
|
|
|
import fs from 'fs'
|
|
|
|
import path from 'path'
|
|
|
|
import walk from 'walk-sync'
|
|
|
|
import yaml from 'js-yaml'
|
|
|
|
import { isRegExp, set } from 'lodash-es'
|
|
|
|
import filenameToKey from './filename-to-key.js'
|
2020-12-09 22:20:24 +03:00
|
|
|
|
2021-07-15 00:35:01 +03:00
|
|
|
export default function dataDirectory(dir, opts = {}) {
|
2020-12-09 22:20:24 +03:00
|
|
|
const defaultOpts = {
|
2021-07-15 00:35:01 +03:00
|
|
|
preprocess: (content) => {
|
|
|
|
return content
|
|
|
|
},
|
2020-12-09 22:20:24 +03:00
|
|
|
ignorePatterns: [/README\.md$/i],
|
2021-07-15 00:35:01 +03:00
|
|
|
extensions: ['.json', '.md', '.markdown', '.yaml', '.yml'],
|
2020-12-09 22:20:24 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
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
|
2021-07-15 00:35:01 +03:00
|
|
|
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
|
2020-12-09 22:20:24 +03:00
|
|
|
|
2021-07-15 00:35:01 +03:00
|
|
|
// ignore files that don't have a whitelisted file extension
|
|
|
|
return opts.extensions.includes(path.extname(filename).toLowerCase())
|
|
|
|
})
|
2020-12-16 01:04:41 +03:00
|
|
|
|
2021-07-15 00:35:01 +03:00
|
|
|
const files = filenames.map((filename) => [filename, fs.readFileSync(filename, 'utf8')])
|
2020-12-15 21:56:25 +03:00
|
|
|
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()
|
2020-12-09 22:20:24 +03:00
|
|
|
|
2020-12-15 21:56:25 +03:00
|
|
|
if (opts.preprocess) fileContent = opts.preprocess(fileContent)
|
2020-12-09 22:20:24 +03:00
|
|
|
|
2020-12-15 21:56:25 +03:00
|
|
|
// add this file's data to the global data object
|
|
|
|
switch (extension) {
|
|
|
|
case '.json':
|
|
|
|
set(data, key, JSON.parse(fileContent))
|
|
|
|
break
|
|
|
|
case '.yaml':
|
|
|
|
case '.yml':
|
2021-05-19 20:32:47 +03:00
|
|
|
set(data, key, yaml.load(fileContent, { filename }))
|
2020-12-15 21:56:25 +03:00
|
|
|
break
|
|
|
|
case '.md':
|
|
|
|
case '.markdown':
|
|
|
|
set(data, key, fileContent)
|
|
|
|
break
|
2020-12-14 18:56:05 +03:00
|
|
|
}
|
2021-07-15 00:35:01 +03:00
|
|
|
})
|
2020-12-09 22:20:24 +03:00
|
|
|
|
|
|
|
return data
|
|
|
|
}
|