|
1 | 1 | const fs = require('fs') |
| 2 | +const { extname, basename } = require('path') |
2 | 3 | const { promisify } = require('util') |
3 | | -const { join, dirname } = require('path') |
4 | 4 |
|
5 | 5 |
|
6 | 6 | const readFile = promisify(fs.readFile) |
7 | 7 | const writeFile = promisify(fs.writeFile) |
8 | | -const access = promisify(fs.access) |
9 | | -const mkdir = promisify(fs.mkdir) |
10 | 8 |
|
| 9 | +const commentator = [ |
| 10 | + { |
| 11 | + filenames: [], |
| 12 | + extnames: ['.js', '.ts'], |
| 13 | + create: (upgrade) => ([ |
| 14 | + `// mili upgrade type: ${upgrade}`, |
| 15 | + ].join('\n')), |
| 16 | + }, |
| 17 | + { |
| 18 | + filenames: [], |
| 19 | + extnames: ['.md'], |
| 20 | + create: (upgrade) => ([ |
| 21 | + `<!-- mili upgrade type: ${upgrade} -->`, |
| 22 | + ].join('\n')), |
| 23 | + }, |
| 24 | + { |
| 25 | + filenames: ['.gitignore', '.npmrc'], |
| 26 | + extnames: ['.yml', '.yaml'], |
| 27 | + create: (upgrade) => ([ |
| 28 | + `# mili upgrade type: ${upgrade}`, |
| 29 | + ].join('\n')), |
| 30 | + }, |
| 31 | +] |
11 | 32 |
|
12 | 33 |
|
13 | | -module.exports = async ({ path, view , handlers, encoding, targetPath }, root) => { |
| 34 | +const appendFileHeader = file => { |
| 35 | + const ext = extname(file.targetPath) |
| 36 | + const filename = basename(file.targetPath) |
| 37 | + const cm = commentator.find(handler => ( |
| 38 | + handler.extnames.includes(ext) || handler.filenames.includes(filename) |
| 39 | + )) |
14 | 40 |
|
15 | | - // 提前做 |
16 | | - // await ensureDirectoryExistence(targetPath) |
| 41 | + if (!cm) return file |
| 42 | + |
| 43 | + if (file.upgrade === 'cover') { |
| 44 | + const comment = cm.create(file.upgrade, 'This file will be cover when upgrade template') |
| 45 | + return { ...file, content: `${comment}\n${file.content}` } |
| 46 | + } else if (file.upgrade === 'merge') { |
| 47 | + const comment = cm.create(file.upgrade, 'This file will be merge when upgrade template') |
| 48 | + return { ...file, content: `${comment}\n${file.content}` } |
| 49 | + } |
| 50 | + |
| 51 | + return file |
| 52 | +} |
| 53 | + |
| 54 | + |
| 55 | +module.exports = async ({ upgrade, path, view , handlers, encoding, targetPath }, root) => { |
17 | 56 | const content = await readFile(path, encoding) |
18 | | - file = handlers.reduce( |
| 57 | + let file = handlers.reduce( |
19 | 58 | (file, handler) => handler.genFile(file), |
20 | | - { path, view, content, encoding, targetPath } |
| 59 | + { path, view, content, upgrade, encoding, targetPath } |
21 | 60 | ) |
22 | 61 |
|
| 62 | + file = appendFileHeader(file) |
| 63 | + |
23 | 64 | await writeFile(targetPath, file.content, encoding) |
24 | 65 | } |
0 commit comments