-
-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathhelper.js
52 lines (46 loc) · 1.62 KB
/
helper.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 fs = require('fs')
const path = require('path')
function generateFilenames (directory, filenames) {
return filenames.reduce((acc, filename) => {
if (filename.indexOf('*') < 0) {
acc.push(filename)
return acc
} else if (!fs.existsSync(directory)) {
return acc
}
// We use a UNIX synthax in our classifier, so we need to transform this in to a JS RegExp
const regex = new RegExp(filename.replace('*', '.*'))
return acc.concat(fs.readdirSync(directory).filter(f => regex.test(f)))
}, [])
}
function singleResourceLoader (filepath, add, remove) {
if (!fs.existsSync(filepath)) { return }
let dict = fs.readFileSync(filepath, 'utf8')
dict.split('\n').forEach(row => {
if (row.trim().startsWith('#')) {
// Do nothing, this is a comment
} else if (row.startsWith('!')) {
row.substring(1).split('|').forEach(remove)
} else {
row.split('|').forEach(add)
}
})
}
function multiResourceLoader ({ directory, filenames }, add, remove) {
generateFilenames(directory, filenames).forEach(filename => {
let filepath = path.join(directory, filename)
singleResourceLoader(filepath, add, remove)
})
}
function resourceLoader (dictPath) {
return (opts, add, remove) => {
if (typeof opts === 'string') {
let filename = path.join(dictPath, opts)
return singleResourceLoader(filename, add, remove)
}
let directory = path.join(dictPath, opts.directory)
multiResourceLoader({ directory: directory, filenames: opts.filenames }, add, remove)
}
}
module.exports.generateFilenames = generateFilenames
module.exports.resourceLoader = resourceLoader