|
1 | 1 | const path = require('path'); |
2 | 2 | const fsExtra = require('fs-extra'); |
3 | 3 |
|
| 4 | +const getDirectories = source => |
| 5 | + fsExtra.readdirSync(source, { withFileTypes: true }) |
| 6 | + .filter(dirent => dirent.isDirectory()) |
| 7 | + .map(dirent => dirent.name) |
| 8 | + |
| 9 | +const regex1 = RegExp('(.*)\\/\\*(.*)'); |
| 10 | + |
4 | 11 | exports.onCreateNode = ({ node }, pluginOptions) => { |
5 | | - const { source, destination } = pluginOptions; |
| 12 | + const { source, destination = '', purge = false } = pluginOptions; |
6 | 13 | const sourceNormalized = path.normalize(source); |
7 | 14 | if (node.internal.type === 'File') { |
8 | 15 | const dir = path.normalize(node.dir); |
9 | 16 | if (dir.includes(sourceNormalized)) { |
10 | 17 | const relativeToDest = dir.replace(sourceNormalized, ''); |
11 | | - const newPath = path.join( |
12 | | - process.cwd(), |
13 | | - 'public', |
14 | | - destination, |
15 | | - relativeToDest, |
16 | | - node.base |
17 | | - ); |
18 | | - |
19 | | - fsExtra.copy(node.absolutePath, newPath, err => { |
20 | | - if (err) { |
21 | | - console.error('Error copying file', err); |
22 | | - } |
23 | | - }); |
| 18 | + |
| 19 | + // if regex enabled |
| 20 | + if (regex1.test(destination)) { |
| 21 | + const hits = regex1.exec(destination) |
| 22 | + |
| 23 | + if (!hits) return |
| 24 | + const regPrefix = hits[1] |
| 25 | + const regPostfix = hits[2] |
| 26 | + |
| 27 | + const dirList = getDirectories(regPrefix) |
| 28 | + |
| 29 | + dirList.forEach(e => { |
| 30 | + const newDestination = regPrefix + '/' + e + regPostfix; |
| 31 | + const newPath = path.join( |
| 32 | + process.cwd(), |
| 33 | + 'public', |
| 34 | + newDestination, |
| 35 | + relativeToDest, |
| 36 | + node.base |
| 37 | + ); |
| 38 | + |
| 39 | + fsExtra.copy(node.absolutePath, newPath, { overwrite: purge }, err => { |
| 40 | + if (err) { |
| 41 | + console.error('Error copying file', err); |
| 42 | + } |
| 43 | + }); |
| 44 | + }) |
| 45 | + } |
| 46 | + // if regex not enabled |
| 47 | + else { |
| 48 | + const newPath = path.join( |
| 49 | + process.cwd(), |
| 50 | + 'public', |
| 51 | + destination, |
| 52 | + relativeToDest, |
| 53 | + node.base |
| 54 | + ); |
| 55 | + |
| 56 | + fsExtra.copy(node.absolutePath, newPath, { overwrite: purge }, err => { |
| 57 | + if (err) { |
| 58 | + console.error('Error copying file', err); |
| 59 | + } |
| 60 | + }); |
| 61 | + } |
24 | 62 | } |
25 | 63 | } |
26 | 64 | }; |
0 commit comments