-
Notifications
You must be signed in to change notification settings - Fork 41
/
util.js
47 lines (38 loc) · 991 Bytes
/
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
const path = require('path')
const fs = require('fs')
function idFromName (id, spaceChar = '_') {
if (id === null || id === undefined) {
id = ''
}
const regex = new RegExp(`[^\\w${spaceChar}]`, 'gi')
return id.toString().toLowerCase()
.replace(/^\s+|\s+$/g, '')
.replace(/\s/g, spaceChar)
.replace(regex, '')
}
function dirFromName (exerciseDir, name) {
if (typeof exerciseDir !== 'string') {
return null
}
return path.join(exerciseDir, idFromName(name))
}
function getFsObject (type, file, base) {
var stat
if (typeof base !== 'string' || typeof file !== 'string') {
return null
}
file = path.resolve(base, file)
try {
stat = fs.statSync(file)
} catch (e) {}
if (!stat || !(type === 'file' ? stat.isFile() : stat.isDirectory())) {
return null
}
return file
}
module.exports = {
idFromName: idFromName,
dirFromName: dirFromName,
getDir: getFsObject.bind(null, 'dir'),
getFile: getFsObject.bind(null, 'file')
}