1 | const Asset = require('../Asset');
|
2 | const micromatch = require('micromatch');
|
3 | const path = require('path');
|
4 | const {glob} = require('../utils/glob');
|
5 |
|
6 | class GlobAsset extends Asset {
|
7 | constructor(name, options) {
|
8 | super(name, options);
|
9 | this.type = null;
|
10 | }
|
11 |
|
12 | async load() {
|
13 | let regularExpressionSafeName = this.name;
|
14 | if (process.platform === 'win32')
|
15 | regularExpressionSafeName = regularExpressionSafeName.replace(/\\/g, '/');
|
16 |
|
17 | let files = await glob(regularExpressionSafeName, {
|
18 | onlyFiles: true
|
19 | });
|
20 | let re = micromatch.makeRe(regularExpressionSafeName, {capture: true});
|
21 | let matches = {};
|
22 |
|
23 | for (let file of files) {
|
24 | let match = file.match(re);
|
25 | let parts = match
|
26 | .slice(1)
|
27 | .filter(Boolean)
|
28 | .reduce((a, p) => a.concat(p.split('/')), []);
|
29 | let relative =
|
30 | './' + path.relative(path.dirname(this.name), file.normalize('NFC'));
|
31 | set(matches, parts, relative);
|
32 | this.addDependency(relative);
|
33 | }
|
34 |
|
35 | return matches;
|
36 | }
|
37 |
|
38 | generate() {
|
39 | return [
|
40 | {
|
41 | type: 'js',
|
42 | value: 'module.exports = ' + generate(this.contents) + ';'
|
43 | }
|
44 | ];
|
45 | }
|
46 | }
|
47 |
|
48 | function generate(matches, indent = '') {
|
49 | if (typeof matches === 'string') {
|
50 | return `require(${JSON.stringify(matches)})`;
|
51 | }
|
52 |
|
53 | let res = indent + '{';
|
54 |
|
55 | let first = true;
|
56 | for (let key in matches) {
|
57 | if (!first) {
|
58 | res += ',';
|
59 | }
|
60 |
|
61 | res += `\n${indent} ${JSON.stringify(key)}: ${generate(
|
62 | matches[key],
|
63 | indent + ' '
|
64 | )}`;
|
65 | first = false;
|
66 | }
|
67 |
|
68 | res += '\n' + indent + '}';
|
69 | return res;
|
70 | }
|
71 |
|
72 | function set(obj, path, value) {
|
73 | for (let i = 0; i < path.length - 1; i++) {
|
74 | let part = path[i];
|
75 |
|
76 | if (obj[part] == null) {
|
77 | obj[part] = {};
|
78 | }
|
79 |
|
80 | obj = obj[part];
|
81 | }
|
82 |
|
83 | obj[path[path.length - 1]] = value;
|
84 | }
|
85 |
|
86 | module.exports = GlobAsset;
|