Files: 49c6e5459b68f2a30bcecf7727b8c9a99cfe4e79 / lib / readModules.js
1402 bytesRaw
1 | // TODO extract into `bulk-require-async` |
2 | // and `bulkify-async` |
3 | // and `./lib/transformModule` |
4 | |
5 | const { assign, keys } = Object |
6 | const assert = require('assert') |
7 | const { join, sep } = require('path') |
8 | const readDirectory = require('read-directory') |
9 | const Matcher = require('minimatch').Minimatch |
10 | const requireFromString = require('require-from-string') |
11 | const mapValues = require('modify-values') |
12 | |
13 | module.exports = readModules |
14 | |
15 | function readModules (options, cb) { |
16 | const { dirname, types } = options |
17 | |
18 | // pre-compile type matchers |
19 | const matchers = mapValues(types, ({ glob }) => { |
20 | const matcher = Matcher(glob) |
21 | return filePath => matcher.match(filePath) |
22 | }) |
23 | |
24 | readDirectory(dirname, { |
25 | filter: '**/*.js', |
26 | dirnames: [dirname], |
27 | transform |
28 | }, cb) |
29 | |
30 | function transform (fileContent, parsedFilePath) { |
31 | const filePath = join(parsedFilePath.dir, parsedFilePath.base) |
32 | const path = join(parsedFilePath.dir, parsedFilePath.name).split(sep) |
33 | const exports = requireFromString(fileContent, filePath, { |
34 | appendPaths: [dirname] |
35 | }) |
36 | const module = assign({ path }, exports) |
37 | const modules = keys(types).reduce((sofar, typeName) => { |
38 | if (sofar !== null) return sofar |
39 | const { transform } = types[typeName] |
40 | const match = matchers[typeName] |
41 | return match(filePath) |
42 | ? transform(module) |
43 | : null |
44 | }, null) |
45 | return modules |
46 | } |
47 | } |
48 |
Built with git-ssb-web