- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpath.lua
More file actions
Latest commit
437 lines (400 loc) · 12.4 KB
/
Copy pathpath.lua
File metadata and controls
437 lines (400 loc) · 12.4 KB
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
---cSpell:ignore vararg
---[LuaFileSystem](https://keplerproject.github.io/luafilesystem/)
---@diagnosticdisable-next-line:undefined-doc-name
---@typeLFS
locallfs
do
localsuccess
success, lfs=pcall(require, "lfs")
ifnotsuccessthen
lfs= (nil)--[[@as LFS]]
end
end
---@classPath
---@fieldentriesstring[]
---@fieldforce_directoryboolean? @ trailing slashes define `force_directory` paths
---@field__is_absoluteboolean? @ internal only. use `is_absolute()` instead
---@fielddrive_letterstring? @ windows only
localPath= {}
Path.__index=Path
localmain_separator=package.config:sub(1, 1)
localis_windows=main_separator=="\\"
localseparator_pattern=is_windows
and"()[\\/]()"
or"()/()"
---The main separator defines what to use when converting Paths to strings.\
---By default this only sets the main separator if the current platform is windows.
---@paramforward_or_backslash"/"|"\\" @ New main separator
---@paramset_regardless_of_platform?boolean @ Set even if the current platform is not windows?
functionPath.set_main_separator(forward_or_backslash, set_regardless_of_platform)
ifforward_or_backslash~="\\" andforward_or_backslash~="/" then
error("Attempt to set main path separator to '"..forward_or_backslash.."' \z
when the only valid separators are '/' and '\\'."
)
end
ifset_regardless_of_platformoris_windowsthen
main_separator=forward_or_backslash
end
end
---Get the main separator that is currently used when converting Paths to strings
functionPath.get_main_separator()
returnmain_separator
end
---@parampathstring
localfunctionget_drive_letter(path)
ifnotis_windowsthen
error("Cannot get_drive_letter when not on windows")
end
ifpath:sub(2, 2) ~=":" then
returnnil, "Unable to get drive letter from path '"..path.."'"
end
returnpath:sub(1, 1)
end
functionPath.is_windows()
returnis_windows
end
---Try parsing a string as a path
---@parampathstring?
---@returnPath|nil result @ nil if unable to parse
---@returnnil|string err
functionPath.try_parse(path)
localentries= {}
localresult= {entries=entries}
ifpaththen
localentries_start_position=1
ifis_windowsthen
localdrive_letter=get_drive_letter(path)
ifdrive_letterthen
result.drive_letter=drive_letter
result.__is_absolute=true
entries_start_position=3
end
end
ifpath:find("^"..separator_pattern, entries_start_position) then
result.__is_absolute=true
entries_start_position=entries_start_position+1
elseifis_windowsandresult.drive_letterand#path>=entries_start_positionthen
returnnil, "Expected path separator after drive letter in path '"..path.."'"
end
localentry_start_position=1
localentires_part=path:sub(entries_start_position)
forsep_position, next_entry_positioninentires_part:gmatch(separator_pattern) do
ifsep_position==entry_start_positionthen
returnnil, "Path separators must not be followed by another \z
path separator in path '"..path.."' at "..sep_position
end
entries[#entries+1] =entires_part:sub(entry_start_position, sep_position-1)
entry_start_position=next_entry_position
end
ifentries_start_position+entry_start_position-1>#paththen-- trailing path separator?
result.force_directory=true
else
entries[#entries+1] =entires_part:sub(entry_start_position)
end
end
return (setmetatable(result, Path))
end
---Path constructor
---@parampath (string|Path)?
---@returnPath
functionPath.new(path)
iftype(path) =="table" then
returnpath:copy()
end
---@castpathstring
localresult, err=Path.try_parse(path)
ifnotresultthen
error(err)
end
returnresult
end
---copy this path
---@returnPath
functionPath:copy()
localentries= {}
localresult= {
entries=entries,
__is_absolute=self.__is_absolute,
force_directory=self.force_directory,
}
ifis_windowsthen
result.drive_letter=self.drive_letter
end
for_, entry_nameinipairs(self.entries) do
entries[#entries+1] =entry_name
end
returnsetmetatable(result, Path)
end
functionPath:is_absolute()
return ((is_windowsandself.drive_letter) orself.__is_absolute)
end
---By default this only overrides the main separator if the current platform is windows.
---@paramoverridden_separator ("/"|"\\")? @ Separator to use instead of the current main separator.
---@paramoverride_regardless_of_platformboolean? @ Use even if the current platform is not windows?
---@returnstring
functionPath:str(overridden_separator, override_regardless_of_platform)
localseparator=main_separator
ifoverridden_separatorthen
ifoverridden_separator~="\\" andoverridden_separator~="/" then
error("Attempt to set path separator to '"..overridden_separator.."' \z
when the only valid separators are '/' and '\\'."
)
end
ifoverride_regardless_of_platformoris_windowsthen
separator=overridden_separator
end
end
return (is_windowsandself.drive_letterand (self.drive_letter..":") or"")
..(self:is_absolute() andseparatoror"")
..(self.entries[1] andtable.concat(self.entries, separator) or (notself:is_absolute() and"." or""))
..(self.force_directoryand (self.entries[1] ornotself:is_absolute()) andseparatoror"")
end
Path.__tostring=Path.str
functionPath:length()
return#self.entries
end
Path.__len=Path.length
---@paramotherPath
---@returnboolean
functionPath:equals(other)
localcount=#self.entries
ifcount~=#other.entries
or (is_windowsandself.drive_letter~=other.drive_letter)
orself:is_absolute() ~=other:is_absolute()
orself.force_directory~=other.force_directory
then
returnfalse
end
fori=1, countdo
ifself.entries[i] ~=other.entries[i] then
returnfalse
end
end
returntrue
end
Path.__eq=Path.equals
---create a new path which is all given paths combined
---@varargPath|string
---@returnPath
functionPath.combine(...)
localresult=Path.new()
localentries=result.entries
localpaths= {...}
result.force_directory=paths[1] andpaths[#paths].force_directory
fori, pathinipairs(paths) do
iftype(path) =="string" then
localerr
path, err=Path.new(path)
ifnotpaththen
error(err.." when parsing path number "..i.." when combining paths")
end
end
ifi==1then
ifis_windowsthen
result.drive_letter=path.drive_letter
end
result.__is_absolute=path.__is_absolute
else
ifpath:is_absolute() then
error("Cannot combine paths that are absolute unless they are \z
the first path in the list. Absolute path at number "..i.." '"..path:str().."."
)
end
end
for_, entry_nameinipairs(path.entries) do
entries[#entries+1] =entry_name
end
end
returnresult
end
Path.__div=Path.combine
---get the extension of the path
---@returnstring
functionPath:extension()
ifself.force_directorythen
error("Unable to get the extension of a path that is a directory")
end
returnstring.match(self.entries[#self.entries], "(%.[^.]*)$") or""
end
---get the filename of the path
---@returnstring
functionPath:filename()
ifself.force_directorythen
error("Unable to get the filename of a path that is a directory")
end
returnstring.match(self.entries[#self.entries], "(.-)%.?[^.]*$")
end
---Extract a part of the path as a new path.
---Works just like string.sub where each entry_name is like a character
---@paramiinteger
---@paramjinteger?
---@returnPath
functionPath:sub(i, j)
localcount=#self.entries
do
ifi<0then
i=count+1+i
end
i=math.max(i, 1)
ifjthen
ifj<0then
j=count+1+j
end
j=math.min(j, count)
else
j=count
end
end
localresult=Path.new()
ifi==1then
result.__is_absolute=self.__is_absolute
ifis_windowsthen
result.drive_letter=self.drive_letter
end
end
ifj==countthen
result.force_directory=self.force_directory
end
fork=i, jdo
result.entries[#result.entries+1] =self.entries[k]
end
returnresult
end
---@paramworking_directoryPath|string?
---@returnPath
functionPath:to_fully_qualified(working_directory)
localresult=self:copy()
ifself:is_absolute() then
ifis_windowsandnotself.drive_letterthen
ifnotworking_directoryandnotlfsthen
error("Cannot convert an absolute path without a drive letter \z
to a fully qualified path without a provided `working_directory` \z
nor without LuaFileSystem."
)
end
result.drive_letter=assert(get_drive_letter(
type(working_directory) =="table"
andworking_directory:str()
orworking_directory--[[@as string?]]
orassert(lfs.currentdir()))
)
end
else
ifnotworking_directoryandnotlfsthen
error("Cannot convert a relative path to a fully qualified path \z
without a provided `working_directory` \z
nor without LuaFileSystem."
)
end
result=Path.combine(working_directoryorlfs.currentdir(), self)
end
returnresult
end
---@returnPath
functionPath:normalize()
localresult=self:copy()
localentries= {}
result.entries=entries
for_, entryinipairs(self.entries) do
ifentry=="." then
gotocontinue
elseifentry==".." then
ifnotentries[1] orentries[#entries] ==".." then
ifself:is_absolute() then
error("Trying to move up an entry ('..') when there are no more \z
entries left when normalizing the path '"..self:str().."'"
)
end
entries[#entries+1] =".."
else
entries[#entries] =nil
end
else
entries[#entries+1] =entry
end
::continue::
end
returnresult
end
---**on windows** clears the `drive_letter`. You may want `set_drive_letter()` instead
---@returnPath
functionPath:to_absolute()
localresult=self:copy()
result.__is_absolute=true
ifis_windowsthen
result.drive_letter=nil
end
returnresult
end
---@returnPath
functionPath:to_relative()
localresult=self:copy()
result.__is_absolute=false
ifis_windowsthen
result.drive_letter=nil
end
returnresult
end
---**windows only**
---@paramdrive_letterstring?
---@returnPath
functionPath:set_drive_letter(drive_letter)
ifnotis_windowsthen
-- TODO: decide on if it should just silently return instead of erroring
error("set_drive_letter is only for windows")
end
localresult=self:copy()
result.__is_absolute=true
result.drive_letter=drive_letter
returnresult
end
---@paramforce_directoryboolean?
functionPath:set_force_directory(force_directory)
localresult=self:copy()
result.force_directory=force_directory
returnresult
end
---requires [LuaFileSystem](https://keplerproject.github.io/luafilesystem/)
---@returnboolean
functionPath:exists()
returnlfs.attributes(self:str(), "dev") ~=nil
end
---requires [LuaFileSystem](https://keplerproject.github.io/luafilesystem/)
---@diagnosticdisable-next-line:undefined-doc-name
---@returnfun(dir_obj: LFSDirObject):string iter
---@diagnosticdisable-next-line:undefined-doc-name
---@returnLFSDirObject dir_obj
functionPath:enumerate()
returnlfs.dir(self:str())
end
---requires [LuaFileSystem](https://keplerproject.github.io/luafilesystem/)\
---calls lfs.attributes(request_name) and returns the result
---@paramrequest_namestring
---@diagnosticdisable-next-line:undefined-doc-name
---@returnstring|number|LFSAttributes|nil
functionPath:attr(request_name)
returnlfs.attributes(self:str(), request_name)
end
---requires [LuaFileSystem](https://keplerproject.github.io/luafilesystem/)\
---calls lfs.symlinkattributes(request_name) and returns the result
---@paramrequest_namestring
---@diagnosticdisable-next-line:undefined-doc-name
---@returnstring|number|LFSAttributes|nil
functionPath:sym_attr(request_name)
returnlfs.symlinkattributes(self:str(), request_name)
end
Path.arg_parser_path_type_def= {
id="path",
arg_count=1,
convert=function(arg, context)
localresult, err=Path.try_parse(arg)
ifnotresultthen
returnnil, err..""..context.."."
end
returnresult
end,
compare=function(left, right)
returnleft:str() ==right:str()
end,
}
returnPath