-
Notifications
You must be signed in to change notification settings - Fork 1
/
base.lua
1490 lines (1375 loc) · 49.9 KB
/
base.lua
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local fs = vim.fs
local utils = require("pathlib.utils")
local const = require("pathlib.const")
local errs = require("pathlib.utils.errors")
local watcher = require("pathlib.utils.watcher")
---@class PathlibPath
---@field public nuv uv
---@field public git_state PathlibGitState
---@field public error_msg string|nil
---@field public _raw_paths PathlibStrList
---@field public _drive_name string # Drive name for Windows path. ("C:", "D:", "\\127.0.0.1")
---@field public _uri_protocol string|nil # URI protocol (without `:`) when object is created with `Path.from_uri` such as `file`, `sftp`.
---@field public __windows_panic boolean # Set to true when passed path might be a windows path. PathlibWindows ignores this.
---@field public __fs_event_callbacks table<string, PathlibWatcherCallback>|nil # List of functions called when a fs_event is triggered.
---@field public __string_cache string|nil # Cache result of `tostring(self)`.
---@field public __parent_cache PathlibPath|nil # Cache reference to parent object.
---@operator div(PathlibPath|string): PathlibPath
---@operator concat(PathlibPath|string): string
local Path = setmetatable({
mytype = const.path_module_enum.PathlibPath,
sep_str = "/",
const = const,
}, {
__call = function(cls, ...)
return cls.new(cls, ...)
end,
})
Path.__index = require("pathlib.utils.nuv").generate_index(Path)
---Create a new Path object
---@param ... string | PathlibPath # List of string and Path objects
---@return PathlibPath
function Path.new(...)
for _, s in ipairs({ ... }) do -- find first arg that is PathlibWindowsPath or PathlibPosixPath
if utils.tables.is_path_module(s) then
---@cast s PathlibPath
if utils.tables.is_type_of(s, const.path_module_enum.PathlibWindows) then
return require("pathlib.windows").new(...)
elseif utils.tables.is_type_of(s, const.path_module_enum.PathlibPosix) then
return require("pathlib.posix").new(...)
end
end
end
local self = Path.new_empty()
self:_init(...)
if self.__windows_panic then
vim.api.nvim_err_writeln(table.concat({
"Possible Windows path detected with PathlibPath module.",
"You may want to use PathlibWindows instead.",
"`local WindowsPath = require('pathlib.windows')`",
}, "\n"))
end
return self
end
-- ╭─────────────────────────────────────────────────────────╮ --
-- │ Class Methods │ --
-- ╰─────────────────────────────────────────────────────────╯ --
function Path.new_empty()
---@type PathlibPath
local self = setmetatable({}, Path)
self:to_empty()
return self
end
---Return `vim.fn.getcwd` in Path object
---@return PathlibPath
function Path.cwd()
return Path.new(vim.fn.getcwd())
end
---Return `vim.loop.os_homedir` in Path object
---@return PathlibPath
function Path.home()
return Path.new(vim.loop.os_homedir())
end
---Calculate permission integer from "rwxrwxrwx" notation.
---@param mode_string string
---@return integer
function Path.permission(mode_string)
errs.assert_function("Path.permission", function()
return const.check_permission_string(mode_string)
end, "mode_string must be in the form of `rwxrwxrwx` or `-` otherwise.")
return const.permission_from_string(mode_string)
end
---Shorthand to `vim.fn.stdpath` and specify child path in later args.
---Mason bin path: `Path.stdpath("data", "mason", "bin")` or `Path.stdpath("data", "mason/bin")`
---@param what string # See `:h stdpath` for information
---@param ... string|PathlibPath # child path after the result of stdpath
---@return PathlibPath
function Path.stdpath(what, ...)
return Path.new(vim.fn.stdpath(what), ...)
end
---Parse a uri and return its path. Protocol is saved at `self._uri_protocol`.
---@param uri string
function Path.from_uri(uri)
local protocol, file = require("pathlib.utils.uri").parse_uri(uri)
local result = Path.new(file)
result._uri_protocol = protocol
return result
end
-- ╭─────────────────────────────────────────────────────────╮ --
-- │ Object Methods │ --
-- ╰─────────────────────────────────────────────────────────╯ --
---Private init method to create a new Path object
---@param ... string | PathlibPath # List of string and Path objects
function Path:_init(...)
local run_resolve = false
local iswin = not utils.tables.is_type_of(self, const.path_module_enum.PathlibPosix)
for i, s in ipairs({ ... }) do
if utils.tables.is_path_module(s) then
---@cast s PathlibPath
if i == 1 then
self:copy_all_from(s)
else
assert(not s:is_absolute(), ("new: invalid root path object in %sth argument: %s"):format(i, s))
if s:peek(1) == ".." then
run_resolve = true
end
self._raw_paths:extend(s._raw_paths)
end
elseif type(s) == "string" then
local path = require("pathlib.utils.paths").normalize(s, iswin, { collapse_slash = false })
if i == 1 then
if path:sub(2, 2) == ":" then --[[Windows C: etc]]
self.__windows_panic = true
self._drive_name = path:sub(1, 2)
path = path:sub(3)
elseif vim.startswith(path, "//") then --[[Windows network devices: \\127.0.0.1, \\wsl$]]
self.__windows_panic = true
local path_start = path:find("/", 3) or 0
local network_device = path:sub(3, path_start - 1)
self._drive_name = self.sep_str:rep(2) .. network_device
path = path_start > 0 and path:sub(path_start) or "/"
end
end
local splits = vim.split(path:gsub("/+", "/"), "/", { plain = true, trimempty = false })
if #splits == 0 then
goto continue
elseif vim.tbl_contains(splits, "..") then -- deal with '../' later in `self:resolve()`
run_resolve = true
end
self._raw_paths:extend(splits)
else
error("PathlibPath(new): ValueError: Invalid type as argument: " .. ("%s (%s: %s)"):format(type(s), i, s))
end
::continue::
end
self:__clean_paths_list()
if run_resolve then
self:resolve()
end
end
function Path:to_empty()
self.git_state = {}
self._raw_paths = utils.lists.str_list.new()
self._drive_name = ""
self._uri_protocol = nil
self.__windows_panic = false
self.__string_cache = nil
return self
end
---Copy all attributes from `path` to self
---@param path PathlibPath
function Path:copy_all_from(path)
self._drive_name = path._drive_name
self._uri_protocol = path._uri_protocol
self._raw_paths:extend(path._raw_paths)
self.__string_cache = nil
return self
end
---Copy all attributes from `path` to self
function Path:deep_copy()
return self.new_empty():copy_all_from(self)
end
---Create a new Path object as self's child. `name` cannot be a grandchild.
---@param name string
---@return PathlibPath
function Path:child(name)
local new = self.deep_copy(self)
if self:tostring() ~= "." then
new.__string_cache = self:tostring() .. self.sep_str .. name
else
new.__string_cache = name
end
new._raw_paths:append(name)
new.__parent_cache = self
return new
end
---Create a new Path object as self's descentant. Use `self:child` if new path is a direct child of the dir.
---@deprecated Use `self:descentant` instead.
---@param ... string
---@return PathlibPath
function Path:new_descendant(...)
return self:descendant(...)
end
---Create a new Path object as self's descentant. Use `self:child` if new path is a direct child of the dir.
---@param ... string
---@return PathlibPath
function Path:descendant(...)
local new = self:deep_copy()
local args = { ... }
new._raw_paths:extend(args)
new.__string_cache = self:tostring() .. self.sep_str .. table.concat(args, self.sep_str)
return new
end
---Unpack name and return a new self's grandchild, where `name` contains more than one `/`.
---@deprecated Use `self:child_unpack` instead.
---@param name string
---@return PathlibPath
function Path:new_child_unpack(name)
return self:child_unpack(name)
end
---Unpack name and return a new self's grandchild, where `name` contains more than one `/`.
---@param name string
---@return PathlibPath
function Path:child_unpack(name)
return self:descendant(unpack(vim.split(name, "[/\\]", { plain = false, trimempty = true })))
end
function Path:__clean_paths_list()
self._raw_paths:filter_internal()
self.__string_cache = nil
end
---Fetch one part of the path.
---
---If index == 0: returns drive_name,
---elseif index > 0: gets the n-th element in the path starting from 1.
--- When path is absolute, `self:peek(1)` is always an empty string ("").
---elseif index < 0: gets the (-n)-th element counting from leaf.
--- `self:peek(-1) == self:basename()`.
---
--->>> Path("folder/foo.txt"):peek(1)
---"folder"
--->>> Path("folder/foo.txt"):peek(2)
---"foo.txt"
--->>> Path("folder/foo.txt"):peek(-1)
---"foo.txt"
---
--->>> Path("/etc/passwd"):peek(0)
---"" -- drive name is empty in posix paths
--->>> Path("/etc/passwd"):peek(1)
---"" -- first element of absolute path is always empty
--->>> Path("/etc/passwd"):peek(2)
---"etc"
---
---@param index integer
---@return string|nil
function Path:peek(index)
if index == 0 then
return self._drive_name
elseif index > 0 then
return self._raw_paths[index]
else
return self._raw_paths[self:depth() + index + 1]
end
end
---Return the basename of `self`.
---Eg: foo/bar/baz.txt -> baz.txt
---@return string
function Path:basename()
return self._raw_paths[#self._raw_paths]
end
---Return new object with new name. You can also use this to create siblings.
---
---This does not check if `name` contains invalid path separators like `"/"` so be careful.
---
--->>> Path("./folder/foo.txt"):with_basename("bar.png")
---Path("./folder/bar.png")
---
---@param name string
---@return PathlibPath
function Path:with_basename(name)
local parent = self:parent()
if parent then
return parent:child(name)
else
return self.new_empty():child(name)
end
end
---Return the group name of the file GID. Same as `str(self) minus self:modify(":r")`.
---
--->>> Path("folder/foo.txt"):suffix()
---"foo"
--->>> Path("folder/no-extension"):suffix()
---""
--->>> Path("folder/.bashrc"):suffix()
---".bashrc"
--->>> Path("folder/archive.tar.gz"):suffix()
---"archive.tar"
---
---@return string # extension of path including the dot (`.`): `.py`, `.lua` etc
function Path:suffix()
local s, counter = self:basename():gsub("^.*(%.[^.]+)$", "%1", 1)
return counter > 0 and s or ""
end
---Return new object with new suffix.
---
--->>> Path("./folder/foo.txt"):with_suffix(".png")
---Path("./folder/foo.png")
---
---@see PathlibPath.add_suffix as well
---@param suffix string # New suffix
function Path:with_suffix(suffix)
local name = self:stem() .. suffix
return self:with_basename(name)
end
---Append given `suffix` to path, if suffix is not as same as given.
---@see PathlibPath.with_suffix as well
---
--->>> Path("./folder/foo.tar"):add_suffix(".gz")
---Path("./folder/foo.tar.gz")
---
--->>> Path("./folder/foo.txt.bak"):add_suffix(".bak")
---Path("./folder/foo.txt.bak") -- is already ".bak", so no change applied
---
---@param suffix string # Append this suffix to path, if suffix is not already equal.
---@param force boolean|nil # If true, always append given suffix. Result will be `foo.txt.bak.bak` in above expample.
function Path:add_suffix(suffix, force)
local basename = self:basename()
if force or basename:sub(-suffix:len()) ~= suffix then
basename = basename .. suffix
end
return self:with_basename(basename)
end
---Remove `suffix` if and only if path ends with the given `suffix`.
---
--->>> Path("./folder/foo.tar.gz"):remove_suffix(".tar.gz")
---Path("./folder/foo")
---
--->>> Path("./folder/foo.txt"):remove_suffix(".bak")
---Path("./folder/foo.txt") -- is already not ".bak", so no change applied
---
---@param suffix string # Remove this suffix from path.
function Path:remove_suffix(suffix)
local basename = self:basename()
local suffix_length = suffix:len()
if suffix_length > 0 and basename:sub(-suffix_length) == suffix then
basename = basename:sub(1, -suffix_length - 1)
end
return self:with_basename(basename)
end
---Return the group name of the file GID. Same as `self:modify(":t:r")`.
---@return string # stem of path. (src/version.c -> "version")
function Path:stem()
return (self:basename():sub(1, -self:suffix():len() - 1))
end
---Return new object with new stem.
---
--->>> Path("./folder/foo.txt"):with_stem("bar")
---Path("./folder/bar.txt")
---
---@param stem string
function Path:with_stem(stem)
local name = stem .. self:suffix()
return self:with_basename(name)
end
---Return parent directory of itself. If parent does not exist, returns nil.
---
---If you never want a nil, use `self:parent_assert()`. This will raise an error if parent not found.
---This could be used to chain methods: (`self:parent_assert():tostring()`, `self:parent_assert():fs_iterdir()`).
---
---@return PathlibPath|nil
function Path:parent()
if not self.__parent_cache and #self._raw_paths >= 2 then
local parent = self.deep_copy(self)
local trim = parent._raw_paths:pop()
if trim then
self.__parent_cache = parent
end
end
return self.__parent_cache
end
---Return parent directory of itself. This will raise an error when parent is not found.
---@return PathlibPath
function Path:parent_assert()
local parent = self:parent()
assert(parent, string.format([[Parent for %s not found.]], self))
return parent
end
---Return iterator of parents.
function Path:parents()
local current = self
return function()
local result = current:parent()
if result == nil then
return nil
else
current = result
return result
end
end
end
---Returns a URI representation of `self`.
---
---This may not align with results from LSP, so convert LSP data with `Path.from_uri`
---and compare the path objects to get a consistent result.
---
---Objects are comparable with `==` and `~=`.
---
---@param rfc "rfc2396"|"rfc2732"|"rfc3986"|nil
---@return string encoded # URI representation of file path.
function Path:as_uri(rfc)
assert(self:is_absolute(), "Relative paths cannot be expressed as a file URI.")
local path = self:is_absolute() and self or self:absolute()
local encoded = vim.uri_encode(path:tostring("/"), rfc)
return (self._uri_protocol or "file") .. "://" .. encoded
end
---Returns whether registered path is absolute
---@return boolean
function Path:is_absolute()
error("PathlibPath: This function is an abstract method.")
end
---Return whether the file is treated as a _hidden_ file.
---Posix: basename starts with `.`, Windows: calls `GetFileAttributesA`.
---@return boolean
function Path:is_hidden()
error("PathlibPath: This function is an abstract method.")
end
---Returns whether registered path is relative
---@return boolean
function Path:is_relative()
return not self:is_absolute()
end
---Compute a version of this path relative to the path represented by `other`.
---If it’s impossible, nil is returned and `self.error_msg` is modified.
---
---When `walk_up == false` (the default), the path MUST start with `other`.
---When the argument is true, '`../`' entries may be added to form a relative path
---but this function DOES NOT check the actual filesystem for file existence whatsoever.
---
---If the paths referencing different drives or if only one of `self` or `other` is relative,
---nil is returned and `self.error_msg` is modified.
---
--->>> p = Path("/etc/passwd")
--->>> p:relative_to(Path("/"))
---Path.new("etc/passwd")
--->>> p:relative_to(Path("/usr"))
---nil; p.error_msg = "'%s' is not in the subpath of '%s'."
--->>> p:relative_to(Path("C:/foo"))
---nil; p.error_msg = "'%s' is not on the same disk as '%s'."
--->>> p:relative_to(Path("./foo"))
---nil; p.error_msg = "Only one path is relative: '%s', '%s'."
---
---@param other PathlibPath
---@param walk_up boolean|nil # If true, uses `../` to make relative path.
function Path:relative_to(other, walk_up)
if self:is_absolute() and other:is_absolute() then
if self._drive_name ~= other._drive_name then
self.error_msg = string.format("'%s' is not on the same disk as '%s'.", self, other)
return nil
end
elseif self:is_relative() and other:is_relative() then
else
self.error_msg = string.format("Only one path is relative: '%s', '%s'.", self, other)
return nil
end
if not walk_up and not self:is_relative_to(other) then
self.error_msg = string.format("'%s' is not in the subpath of '%s'.", self, other)
return nil
end
local result = self:deep_copy()
result._raw_paths:clear()
result._drive_name = ""
local index = other:depth()
while index > 0 and self._raw_paths[index] ~= other._raw_paths[index] do
result._raw_paths:append("..")
index = index - 1
end
for i = index + 1, self:depth() do
if self._raw_paths[i] and self._raw_paths[i]:len() > 0 then
result._raw_paths:append(self._raw_paths[i])
end
end
self:__clean_paths_list()
return result
end
---Return whether or not this path is relative to the `other` path.
---This is a wrapper of `vim.startswith(tostring(self), tostring(other))` and nothing else.
---It neither accesses the filesystem nor treats “..” segments specially.
---
---Use `self:absolute()` or `self:to_absolute()` beforehand if needed.
---
---`other` may be a string, but MUST use the same path separators.
---
--->>> p = Path("/etc/passwd")
--->>> p:is_relative_to("/etc") -- Must be [[\etc]] on Windows.
---true
--->>> p:is_relative_to(Path("/usr"))
---false
---
---@param other PathlibPath|PathlibString
function Path:is_relative_to(other)
return vim.startswith(tostring(self), tostring(other))
end
function Path:as_posix()
if not utils.tables.is_type_of(self, const.path_module_enum.PathlibWindows) then
return self:tostring()
end
local posix = self:deep_copy()
if posix._drive_name:find("^[A-Za-z]:$") then
posix._drive_name = ""
end
return (self:tostring():gsub(self.sep_str .. "+", require("pathlib.posix").sep_str))
end
---Returns a new path object with absolute path.
---
---Use `self:to_absolute()` instead to modify the object itself which does not need a deepcopy.
---
---If `self` is already an absolute path, returns itself.
---@param cwd PathlibPath|nil # If passed, this is used instead of `vim.fn.getcwd()`.
---@return PathlibPath
function Path:absolute(cwd)
if self:is_absolute() then
return self
else
return self.new(cwd or vim.fn.getcwd(), self)
end
end
---Modifies itself to point to an absolute path.
---
---Use `self:absolute()` instead to return a new path object without modifying self.
---
---If `self` is already an absolute path, does nothing.
---@param cwd PathlibPath|nil # If passed, this is used instead of `vim.fn.getcwd()`.
function Path:to_absolute(cwd)
if self:is_absolute() then
return self
end
local new = self.new(cwd or vim.fn.getcwd(), self)
self._raw_paths:clear()
self:copy_all_from(new)
return self
end
---Get the path being modified with `filename-modifiers`
---@param mods string # filename-modifiers passed to `vim.fn.fnamemodify`
---@return string # result of `vim.fn.fnamemodify(tostring(self), mods)`
function Path:modify(mods)
return vim.fn.fnamemodify(self:tostring(), mods)
end
---Resolves path. Eliminates `../` representation.
---Changes internal. (See `Path:resolve_copy` to create new object)
---@param allow_abs2rel boolean|nil # Allow absolute path to be converted to relative path when there are too many '../'
function Path:resolve(allow_abs2rel)
local accum, length = 1, self:depth()
local negatives, was_absolute = 0, self:is_absolute()
local raw_path = table.concat(self._raw_paths, self.sep_str)
for _, value in ipairs(vim.tbl_values(self._raw_paths)) do
if value == ".." then
if accum > 1 then
accum = accum - 1
else
negatives = negatives + 1
end
else
self._raw_paths[accum] = value
accum = accum + 1
end
end
for i = accum, length do
self._raw_paths[i] = nil
end
if not allow_abs2rel and was_absolute ~= self:is_absolute() then
errs.assert_function("Path:resolve", function()
return was_absolute == self:is_absolute()
end, string.format("'%s' was absolute but too many ../ included in path to resolve -> %s", raw_path, self))
end
for _ = 1, negatives do
table.insert(self._raw_paths, 1, "..")
end
self.__string_cache = nil
return self
end
---Resolves path. Eliminates `../` representation and returns a new object. `self` is not changed.
---@param allow_abs2rel boolean|nil # Allow absolute path to be converted to relative path when there are too many '../'
---@return PathlibPath
function Path:resolve_copy(allow_abs2rel)
local new = self:deep_copy()
return new:resolve(allow_abs2rel)
end
---Run `vim.fn.globpath` on this path.
---@param pattern string # glob pattern expression
---@return fun(): PathlibPath|nil # iterator of results.
function Path:glob(pattern)
local str = self:tostring()
errs.assert_function("Path:glob", function()
return not (str:find([[,]]))
end, "Path:glob cannot work on path that contains `,` (comma).")
local result, i = vim.fn.globpath(str, pattern, false, true), 0 ---@diagnostic disable-line
return function()
i = i + 1
if i <= #result then
return self.new(result[i])
end
end
end
-- ╭─────────────────────────────────────────────────────────╮
-- │ String Manipulation │
-- ╰─────────────────────────────────────────────────────────╯
---@see string.byte
function Path:byte(...)
return self:tostring():byte(...)
end
---@see string.find
function Path:find(...)
return self:tostring():find(...)
end
---@see string.gmatch
function Path:gmatch(...)
return self:tostring():gmatch(...)
end
---@see string.gsub
function Path:gsub(...)
return self:tostring():gsub(...)
end
---@see string.len
-- WARN: `self:len()` used to return the length of `self._raw_paths`.
-- Use `self:depth()` instead.
---
---Return the length of the string representation.
---
--->>> Path("foo/bar.txt"):len() == string.len("foo/bar.txt")
---true
---
function Path:len()
return self:tostring():len()
end
---@see string.lower
function Path:lower()
return self:tostring():lower()
end
---@see string.match
function Path:match(...)
return self:tostring():match(...)
end
---@see string.rep
function Path:rep(...)
return self:tostring():rep(...)
end
---@see string.reverse
function Path:reverse()
return self:tostring():reverse()
end
---@see string.sub
function Path:sub(...)
return self:tostring():sub(...)
end
---@see string.upper
function Path:upper()
return self:tostring():upper()
end
-- ╭─────────────────────────────────────────────────────────╮ --
-- │ UV Filesystem Methods │ --
-- ╰─────────────────────────────────────────────────────────╯ --
---Return result of `luv.fs_stat`.
---@param follow_symlinks boolean|nil # Whether to resolve symlinks
---@return uv.aliases.fs_stat_table|nil stat # nil if `fs_stat` failed
---@nodiscard
function Path:fs_stat(follow_symlinks)
if follow_symlinks then
local realpath = self:realpath()
if realpath then
return realpath:fs_stat(false)
end
else
return self.nuv.fs_stat(self:tostring())
end
end
---Return result of `luv.fs_stat`. Use `self:stat_async` to use with callback.
---@param follow_symlinks boolean|nil # Whether to resolve symlinks
---@return uv.aliases.fs_stat_table|nil stat # nil if `fs_stat` failed
---@nodiscard
function Path:stat(follow_symlinks)
return self:fs_stat(follow_symlinks)
end
function Path:lstat()
return self:stat(false)
end
function Path:exists(follow_symlinks)
local stat = self:stat(follow_symlinks)
return not not stat
end
function Path:size()
local stat = self:stat(true)
return stat and stat.size
end
function Path:is_dir(follow_symlinks)
local stat = self:stat(follow_symlinks)
return stat and stat.type == "directory"
end
function Path:is_file(follow_symlinks)
local stat = self:stat(follow_symlinks)
return stat and stat.type == "file"
end
function Path:is_symlink()
local stat = self:lstat()
return stat and stat.type == "link"
end
---Return result of `luv.fs_realpath` in `PathlibPath`.
---@return PathlibPath|nil # Resolves symlinks if exists. Returns nil if link does not exist.
function Path:realpath()
local realpath = self.nuv.fs_realpath(self:tostring())
if realpath then
return self.new(realpath)
end
end
---Get mode of path object. Use `self:get_type` to get type description in string instead.
---@param follow_symlinks boolean # Whether to resolve symlinks
---@return PathlibModeEnum|nil
function Path:get_mode(follow_symlinks)
local stat = self:stat(follow_symlinks)
return stat and stat.mode
end
---Get type description of path object. Use `self:get_mode` to get mode instead.
---@param follow_symlinks boolean # Whether to resolve symlinks
function Path:get_type(follow_symlinks)
local stat = self:stat(follow_symlinks)
return stat and stat.type
end
---Return whether `other` is the same file or not.
---@param other PathlibPath
---@return boolean
function Path:samefile(other)
local stat = self:stat()
local other_stat = other:stat()
return (stat and other_stat) and (stat.ino == other_stat.ino and stat.dev == stat.dev) or false
end
function Path:is_mount()
if not self:exists() or not self:is_dir() then
return false
end
local stat = self:stat()
if not stat then
return false
end
local parent_stat = self:parent():stat()
if not parent_stat then
return false
end
if stat.dev ~= parent_stat.dev then
return false
end
return stat.ino and stat.ino == parent_stat.ino
end
---Make directory. When `recursive` is true, will create parent dirs like shell command `mkdir -p`
---@param mode integer # permission. You may use `Path.permission()` to convert from "rwxrwxrwx"
---@param recursive boolean # if true, creates parent directories as well
---@return boolean|nil success
function Path:mkdir(mode, recursive)
if self:is_dir(true) then
return true
end
if recursive then
local parent = self:parent()
if parent and not parent:is_dir(true) then
local success = parent:mkdir(mode, recursive)
if not success then
return success
end
end
end
return self.nuv.fs_mkdir(self:tostring(), mode)
end
---Make file. When `recursive` is true, will create parent dirs like shell command `mkdir -p`
---@param mode integer # permission. You may use `Path.permission()` to convert from "rwxrwxrwx"
---@param recursive boolean # if true, creates parent directories as well
---@return boolean|nil success
function Path:touch(mode, recursive)
local fd = self:fs_open("a", mode, recursive)
if fd ~= nil then
self.nuv.fs_close(fd)
return true
end
return false
end
---Copy file to `target`
---@param target PathlibPath # `self` will be copied to `target`
---@return boolean|nil success # whether operation succeeded
function Path:copy(target)
errs.assert_function("Path:copy", function()
return utils.tables.is_path_module(target)
end, "target is not a Path object.")
return self.nuv.fs_copyfile(self:tostring(), target:tostring())
end
---Create a simlink named `self` pointing to `target`
---@param target PathlibPath
---@return boolean|nil success # whether operation succeeded
function Path:symlink_to(target)
errs.assert_function("Path:symlink_to", function()
return utils.tables.is_path_module(target)
end, "target is not a Path object.")
return self.nuv.fs_symlink(self:tostring(), target:tostring())
end
---Create a hardlink named `self` pointing to `target`
---@param target PathlibPath
---@return boolean|nil success # whether operation succeeded
function Path:hardlink_to(target)
errs.assert_function("Path:hardlink_to", function()
return utils.tables.is_path_module(target)
end, "target is not a Path object.")
return self.nuv.fs_link(self:tostring(), target:tostring())
end
---Rename `self` to `target`. If `target` exists, fails with false. Ref: `Path:move`
---@param target PathlibPath
---@return boolean|nil success # whether operation succeeded
function Path:rename(target)
errs.assert_function("Path:rename", function()
return utils.tables.is_path_module(target)
end, "target is not a Path object.")
return self.nuv.fs_rename(self:tostring(), target:tostring())
end
---Move `self` to `target`. Overwrites `target` if exists. Ref: `Path:rename`
---@param target PathlibPath
---@return boolean|nil success # whether operation succeeded
function Path:move(target)
errs.assert_function("Path:move", function()
return utils.tables.is_path_module(target)
end, "target is not a Path object.")
if target:exists() then
target:unlink()
end
return self.nuv.fs_rename(self:tostring(), target:tostring())
end
---@deprecated Use `Path:move` instead.
---@param target PathlibPath
function Path:replace(target)
return self:move(target)
end
---Change the permission of the path to `mode`.
---@param mode integer # permission. You may use `Path.permission()` to convert from "rwxrwxrwx"
---@param follow_symlinks boolean # Whether to resolve symlinks
---@return boolean|nil success # whether operation succeeded
function Path:chmod(mode, follow_symlinks)
if follow_symlinks then
return self.nuv.fs_chmod(self:realpath():tostring(), mode)
else
return self.nuv.fs_chmod(self:tostring(), mode)
end
end
---Remove this file or link. If the path is a directory, use `Path:rmdir()` instead.
---@return boolean|nil success # whether operation succeeded
function Path:unlink()
return self.nuv.fs_unlink(self:tostring())
end
---Remove this directory. The directory must be empty.
---@return boolean|nil success # whether operation succeeded
function Path:rmdir()
return self.nuv.fs_rmdir(self:tostring())
end
---Call `luv.fs_open`.
---@param flags uv.aliases.fs_access_flags|integer
---@param mode integer|nil # permission. You may use `Path.permission()` to convert from "rwxrwxrwx". Default to 0o644.
---@param ensure_dir integer|boolean|nil # if not nil, runs `mkdir -p self:parent()` with permission to ensure parent exists.
--- `true` will default to 0o755.
---@return integer|nil fd
---@nodiscard
function Path:fs_open(flags, mode, ensure_dir)
if ensure_dir == true then
ensure_dir = const.o755
end
if type(ensure_dir) == "number" then
self:parent():mkdir(ensure_dir, true)
end
return self.nuv.fs_open(self:tostring(), flags, mode or const.o644)
end
---Call `luv.fs_open("r") -> luv.fs_read`.
---@param size integer|nil # if nil, uses `self:stat().size`
---@param offset integer|nil
---@return string|nil content # content of the file
function Path:fs_read(size, offset)
local fd = self:fs_open("r")
return fd and self.nuv.fs_read(fd, size or self:size() or 0, offset) --[[@as string]]
end
---Call `luv.fs_open("w") -> luv.fs_write`.
---@param data uv.aliases.buffer
---@param offset integer|nil
---@return integer|nil bytes # number of bytes written
function Path:fs_write(data, offset)
local fd = self:fs_open("w", nil, true)
return fd and self.nuv.fs_write(fd, data, offset) --[[@as integer]]
end
---Call `luv.fs_open("a") -> luv.fs_write`.
---@param data uv.aliases.buffer
---@param offset integer|nil
---@return integer|nil bytes # number of bytes written
function Path:fs_append(data, offset)
local fd = self:fs_open("a", nil, true)
return fd and self.nuv.fs_write(fd, data, offset) --[[@as integer]]
end
---Call `io.read`. Use `self:fs_read` to use with `nio.run` instead.
---@return string|nil data # whole file content
function Path:io_read()
local file, err_msg = io.open(self:tostring(), "r")
if not file then
self.error_msg = err_msg
return nil
end
local data, err_read = file:read("*a")
if not data then
self.error_msg = err_read
return nil
end
return data
end
---Call `io.read` with byte read mode.
---@return string|nil bytes # whole file content
function Path:io_read_bytes()
local file, err_msg = io.open(self:tostring(), "rb")
if not file then
self.error_msg = err_msg
return nil
end
local data, err_read = file:read("*a")
if not data then
self.error_msg = err_read
return nil
end