-
Notifications
You must be signed in to change notification settings - Fork 16
/
upath.coffee
executable file
·120 lines (98 loc) · 2.72 KB
/
upath.coffee
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
path = require 'path'
isFunction = (val) -> val instanceof Function
isString = (val) ->
typeof val == 'string' or
(!!val and typeof val == 'object' and Object::toString.call(val) == '[object String]')
upath = exports
upath.VERSION = if VERSION? then VERSION else 'NO-VERSION' # injected by urequire-inject-version
toUnix = (p) ->
p = p.replace /\\/g, '/'
double = /\/\//
while p.match double
p = p.replace double, '/' # node on windows doesn't replace doubles
p
for propName, propValue of path
if isFunction propValue
upath[propName] = do (propName) ->
(args...) ->
args = args.map (p) ->
if isString(p)
toUnix p
else
p
result = path[propName] args...
if isString result
toUnix result
else
result
else
upath[propName] = propValue
upath.sep = '/'
extraFunctions =
toUnix: toUnix
normalizeSafe: (p) ->
p = toUnix(p)
if p.startsWith './'
if p.startsWith('./..') or (p is './')
upath.normalize(p)
else
'./' + upath.normalize(p)
else
upath.normalize(p)
normalizeTrim: (p) ->
p = upath.normalizeSafe p
if p.endsWith('/')
p[0..p.length-2]
else
p
joinSafe: (p...) ->
result = upath.join.apply null, p
if p[0].startsWith('./') && !result.startsWith('./')
result = './' + result
result
addExt: (file, ext) ->
if not ext
file
else
ext = '.' + ext if ext[0] isnt '.'
file + if file.endsWith(ext) then '' else ext
trimExt: (filename, ignoreExts, maxSize=7) ->
oldExt = upath.extname filename
if isValidExt oldExt, ignoreExts, maxSize
filename[0..(filename.length - oldExt.length)-1]
else
filename
removeExt: (filename, ext) ->
if not ext
return filename
else
ext = if ext[0] is '.' then ext else '.' + ext
if upath.extname(filename) is ext
upath.trimExt filename, [], ext.length
else
filename
changeExt: (filename, ext, ignoreExts, maxSize=7) ->
upath.trimExt(filename, ignoreExts, maxSize) +
if not ext
''
else
if ext[0] is '.'
ext
else
'.' + ext
defaultExt: (filename, ext, ignoreExts, maxSize=7) ->
oldExt = upath.extname filename
if isValidExt(oldExt, ignoreExts, maxSize)
filename
else
upath.addExt filename, ext
isValidExt = (ext, ignoreExts = [], maxSize) ->
((ext) and (ext.length <= maxSize)) and
(ext not in ignoreExts.map (e) ->
(if e and (e[0] isnt '.') then '.' else '') + e
)
for own name, extraFn of extraFunctions
if upath[name] isnt undefined
throw new Error "path.#{name} already exists."
else
upath[name] = extraFn