forked from workshopper/workshopper
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutil.js
65 lines (50 loc) · 1.61 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
const path = require('path')
, fs = require('fs')
, mkdirp = require('mkdirp')
, vw = require('visualwidth')
function repeat (ch, sz) {
return new Array(sz + 1).join(ch)
}
function idFromName (id) {
return id.toLowerCase()
.replace(/\s/g, '_')
.replace(/[^\w]/gi, '')
}
function dirFromName (exerciseDir, name) {
return path.join(exerciseDir, idFromName(name))
}
function assertFs (type, options, field, base, fallback) {
var target = options[field]
, stat
if (typeof target != 'string')
if (fallback)
options[field] = target = path.join(base, fallback)
else
throw new TypeError('need to provide an "' + field + '" String option')
try {
stat = fs.statSync(target)
} catch (e) {}
if (!stat || !(type === 'file' ? stat.isFile() : stat.isDirectory()))
throw new Error('"' + field + '" [' + path.relative('.', target) + '] does not exist or is not a ' + type)
return target
}
function userDir () {
var folders = [process.env.HOME || process.env.USERPROFILE].concat(Array.prototype.slice.apply(arguments))
var dir = path.join.apply(path, folders)
mkdirp.sync(dir)
return dir
}
function applyTextMarker (text, marker, size) {
var availableSpace = size - vw.width(marker, true)
text = vw.truncate(text, availableSpace, '...', true)
return text + repeat(' ', availableSpace - vw.width(text, true)) + marker
}
module.exports = {
idFromName: idFromName
, dirFromName: dirFromName
, repeat: repeat
, applyTextMarker: applyTextMarker
, assertDir: assertFs.bind(null, 'dir')
, assertFile: assertFs.bind(null, 'file')
, userDir: userDir
}