-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (41 loc) · 1.54 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const path = require('path')
const util = require('util')
const fs = require('fs')
const globby = require('globby')
const renameAsync = util.promisify(fs.rename)
module.exports = function (plop, config) {
plop.setDefaultInclude({ actionTypes: true })
plop.setActionType('renameMany', renameMany)
}
async function renameMany (data, config, plop) {
// shallow-merge default config and input config
const cfg = Object.assign({
verbose: true
}, config)
if (typeof cfg.renamer !== 'function') {
throw new Error('Invalid "renamer" argument - must be a function')
}
if (typeof cfg.templateFiles === 'function') {
cfg.templateFiles = cfg.templateFiles()
}
cfg.templateFiles = []
.concat(cfg.templateFiles) // Ensure `cfg.templateFiles` is an array, even if a string is passed.
.map(file => plop.renderString(file, data)) // render the paths as hbs templates
const templateFiles = globby.sync(cfg.templateFiles, {
nobrace: true
})
const filesRenamed = []
for (let filepath of templateFiles) {
const oldFileName = path.basename(filepath)
const newFileName = cfg.renamer(oldFileName)
const directory = path.dirname(filepath)
const newFilepath = path.resolve(directory, newFileName)
if (typeof newFileName === 'string') {
await renameAsync(filepath, newFilepath)
filesRenamed.push(path.relative(process.cwd(), newFilepath))
}
}
const summary = `${filesRenamed.length} files renamed`
if (!cfg.verbose) return summary
else return `${summary}\n -> ${filesRenamed.join('\n -> ')}`
}