-
Notifications
You must be signed in to change notification settings - Fork 30
/
util.js
85 lines (80 loc) · 2.33 KB
/
util.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/**
* Convert a string like `/something/g` to a RegExp instance.
*/
function regExpBuilder (find) {
const regExpRe = /\/(.*)\/(\w*)/
if (find) {
if (regExpRe.test(find)) {
const matches = find.match(regExpRe)
const pattern = matches[1]
const flags = matches[2]
return new RegExp(pattern, flags)
} else {
return find
}
} else {
return null
}
}
function expandGlobPatterns (files) {
const glob = require('glob')
const flatten = require('reduce-flatten')
const unique = require('reduce-unique')
return files
.map(file => glob.hasMagic(file) ? glob.sync(file, { nonull: true }) : file)
.reduce(flatten, [])
.reduce(unique, [])
}
function depthFirstSort (files) {
return files.sort(this.depthFirstCompare)
}
function depthFirstCompare (a, b) {
const path = require('path')
a = path.normalize(a)
b = path.normalize(b)
const depth = {
a: a.split(path.sep).length,
b: b.split(path.sep).length
}
if (depth.a > depth.b) {
return -1
} if (depth.a === depth.b) {
return 0
} else {
return 1
}
}
function loadPlugins (pluginNames) {
const path = require('path')
const arrayify = require('array-back')
const t = require('typical')
return arrayify(pluginNames).map(pluginName => {
let createPlugin
if (typeof pluginName === 'string') {
const loadModule = require('load-module')
const globalModules = require('global-modules')
createPlugin = loadModule(pluginName, {
paths: [path.resolve(__dirname, 'plugin'), '.', globalModules],
prefix: 'renamer-'
})
} else {
createPlugin = pluginName
}
if (!(typeof createPlugin === 'function' && !t.isClass(createPlugin))) {
throw new Error('Invalid plugin: plugin module must export a function')
}
const Plugin = createPlugin(require('./plugin-base'))
if (!t.isClass(Plugin)) {
throw new Error('Invalid plugin: plugin module must export a function which returns a class')
}
if (!Plugin.prototype.replace) {
throw new Error('Invalid plugin: plugin class must implement a replace method')
}
return new Plugin()
})
}
exports.regExpBuilder = regExpBuilder
exports.expandGlobPatterns = expandGlobPatterns
exports.depthFirstSort = depthFirstSort
exports.depthFirstCompare = depthFirstCompare
exports.loadPlugins = loadPlugins